id
int64 22
34.9k
| comment_id
int64 0
328
| comment
stringlengths 2
2.55k
| code
stringlengths 31
107k
| classification
stringclasses 6
values | isFinished
bool 1
class | code_context_2
stringlengths 21
27.3k
| code_context_10
stringlengths 29
27.3k
| code_context_20
stringlengths 29
27.3k
|
---|---|---|---|---|---|---|---|---|
23,375 | 0 | //TODO send email here | public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) {
try {
String customer = Utils.getCustomer();
Url url = cycle.getRequest().getUrl();
Url clientUrl = cycle.getRequest().getClientUrl();
String exStr = ExceptionUtils.getStackTrace(ex);
String fullUrl = cycle.getUrlRenderer().renderFullUrl(url);
int currUserId = 0;
RequestData currRd = logger.getCurrentRequest();
String currSessId = Session.get().getId();
SessionData sd = null;
if(currSessId != null) {
SessionData[] sessions = logger.getLiveSessions();
for(SessionData s : sessions) {
if(s.getSessionId().equals(currSessId)) {
sd = s;
break;
}
}
}
String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd);
StringBuilder currSessStr = new StringBuilder();
if(sd != null) {
currSessStr.append("id:").append(sd.getSessionId()).append('\n');
currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n');
currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n');
currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n');
currSessStr.append("startDate:").append(sd.getStartDate()).append('\n');
currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n');
currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n");
}
currSessStr.append("Requests: \n");
((CustomRequestLogger)logger).getRequests(currSessStr);
String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n "
+ "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s";
String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore
}
} | IMPLEMENTATION | true | String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore | currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n');
currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n");
}
currSessStr.append("Requests: \n");
((CustomRequestLogger)logger).getRequests(currSessStr);
String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n "
+ "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s";
String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore
}
} | }
String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd);
StringBuilder currSessStr = new StringBuilder();
if(sd != null) {
currSessStr.append("id:").append(sd.getSessionId()).append('\n');
currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n');
currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n');
currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n');
currSessStr.append("startDate:").append(sd.getStartDate()).append('\n');
currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n');
currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n");
}
currSessStr.append("Requests: \n");
((CustomRequestLogger)logger).getRequests(currSessStr);
String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n "
+ "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s";
String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore
}
} |
23,375 | 1 | //ignore | public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) {
try {
String customer = Utils.getCustomer();
Url url = cycle.getRequest().getUrl();
Url clientUrl = cycle.getRequest().getClientUrl();
String exStr = ExceptionUtils.getStackTrace(ex);
String fullUrl = cycle.getUrlRenderer().renderFullUrl(url);
int currUserId = 0;
RequestData currRd = logger.getCurrentRequest();
String currSessId = Session.get().getId();
SessionData sd = null;
if(currSessId != null) {
SessionData[] sessions = logger.getLiveSessions();
for(SessionData s : sessions) {
if(s.getSessionId().equals(currSessId)) {
sd = s;
break;
}
}
}
String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd);
StringBuilder currSessStr = new StringBuilder();
if(sd != null) {
currSessStr.append("id:").append(sd.getSessionId()).append('\n');
currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n');
currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n');
currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n');
currSessStr.append("startDate:").append(sd.getStartDate()).append('\n');
currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n');
currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n");
}
currSessStr.append("Requests: \n");
((CustomRequestLogger)logger).getRequests(currSessStr);
String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n "
+ "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s";
String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore
}
} | NONSATD | true | //TODO send email here
} catch (Exception e) {
//ignore
}
} | currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n");
}
currSessStr.append("Requests: \n");
((CustomRequestLogger)logger).getRequests(currSessStr);
String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n "
+ "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s";
String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore
}
} | StringBuilder currSessStr = new StringBuilder();
if(sd != null) {
currSessStr.append("id:").append(sd.getSessionId()).append('\n');
currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n');
currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n');
currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n');
currSessStr.append("startDate:").append(sd.getStartDate()).append('\n');
currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n');
currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n');
currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n");
}
currSessStr.append("Requests: \n");
((CustomRequestLogger)logger).getRequests(currSessStr);
String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n "
+ "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s";
String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr);
String subject = customer + " error";
//TODO send email here
} catch (Exception e) {
//ignore
}
} |
31,571 | 0 | // For integral number type things, need to convert "null" into 0. | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} | NONSATD | true | return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0); | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} |
31,571 | 1 | // For decimal number type things, need to convert "null" into 0.0. | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} | NONSATD | true | return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0); | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} |
31,571 | 2 | // What can we do in this case :( | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} | DESIGN | true | return new Double(0.0);
}
return null; // What can we do in this case :(
} | return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} | private Object convertNullValue(RdsTableColumnDetails theColumnDetail) {
if (theColumnDetail.isNullable()) {
return null;
}
// For integral number type things, need to convert "null" into 0.
if (theColumnDetail.isIntegralType()) {
return new Integer(0);
}
// For decimal number type things, need to convert "null" into 0.0.
if (theColumnDetail.isDecimalType()) {
return new Double(0.0);
}
return null; // What can we do in this case :(
} |
31,583 | 0 | //TODO: FIX ANNOTATION STUFF
//log.println("[Red Team Controller: " + quote(game.getController(Team.RED).getIdString()) + "]");
//log.println("[Blue Team Controller: " + quote(game.getController(Team.BLUE).getIdString()) + "]"); | private void logGameStart(CFMap map) {
log.println("=== CodeFray Version 1 [Capture the Flag] Official Game Log ===\n");
//TODO: FIX ANNOTATION STUFF
//log.println("[Red Team Controller: " + quote(game.getController(Team.RED).getIdString()) + "]");
//log.println("[Blue Team Controller: " + quote(game.getController(Team.BLUE).getIdString()) + "]");
log.println();
log.println("> Game started.");
} | IMPLEMENTATION | true | private void logGameStart(CFMap map) {
log.println("=== CodeFray Version 1 [Capture the Flag] Official Game Log ===\n");
//TODO: FIX ANNOTATION STUFF
//log.println("[Red Team Controller: " + quote(game.getController(Team.RED).getIdString()) + "]");
//log.println("[Blue Team Controller: " + quote(game.getController(Team.BLUE).getIdString()) + "]");
log.println();
log.println("> Game started."); | private void logGameStart(CFMap map) {
log.println("=== CodeFray Version 1 [Capture the Flag] Official Game Log ===\n");
//TODO: FIX ANNOTATION STUFF
//log.println("[Red Team Controller: " + quote(game.getController(Team.RED).getIdString()) + "]");
//log.println("[Blue Team Controller: " + quote(game.getController(Team.BLUE).getIdString()) + "]");
log.println();
log.println("> Game started.");
} | private void logGameStart(CFMap map) {
log.println("=== CodeFray Version 1 [Capture the Flag] Official Game Log ===\n");
//TODO: FIX ANNOTATION STUFF
//log.println("[Red Team Controller: " + quote(game.getController(Team.RED).getIdString()) + "]");
//log.println("[Blue Team Controller: " + quote(game.getController(Team.BLUE).getIdString()) + "]");
log.println();
log.println("> Game started.");
} |
23,397 | 0 | //only reassign if not -1 as messes up code further down | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} | NONSATD | true | final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue); | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} |
23,397 | 1 | //fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} | DEFECT | true | glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph); | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
} | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} |
23,397 | 2 | //this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} | NONSATD | true | }else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue); | if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} | static boolean remapGlyph(PdfFont currentFontData, GlyphData glyphData){
boolean alreadyRemaped=false;
final String charGlyph= currentFontData.getMappedChar(glyphData.getRawInt(), false);
if(charGlyph!=null){
final int newRawInt=currentFontData.getDiffChar(charGlyph);
if(newRawInt!=-1){
glyphData.setRawInt(newRawInt); //only reassign if not -1 as messes up code further down
glyphData.setDisplayValue(String.valueOf((char)newRawInt));
//fix for PDFdata/sample_pdfs_html/general-July2012/klar--men-aldri-ferdig_dacecc.pdf
//in some examples the unicode table is wrong and maps the character into this odd range, but the glyph is always correct
//this is a sanity check to fix this mapping issue
}else if(!glyphData.getDisplayValue().isEmpty() && glyphData.getDisplayValue().charAt(0)<32){
final int altValue=StandardFonts.getAdobeMap(charGlyph);
//this test can return -1 for invalid value as in sample_pdfs_html/general-May2014/18147.pdf
//which breaks code further down so we reject this value
if(altValue>-1) {
glyphData.setRawInt(altValue);
glyphData.set(String.valueOf((char) altValue));
alreadyRemaped = true;
}
}
}
return alreadyRemaped;
} |
31,644 | 0 | /**
* Obtains the priority of this rule. It actually is a dynamic priority
* that depends on the question that was asked.
* The priority is:
* - 100% if the question asked is the same to the background of the rule.
* - 50% if the question asked is an ordered subset of the filtered question.
* - 0% otherwise.
* @param questionAsked Question asked by the user, that underwent the filtering process.
* @return The dynamic priority of the rule.
*/ | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | NONSATD | true | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} |
31,644 | 1 | // If the filtered question is the same than asked | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | NONSATD | true | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100; | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} |
31,644 | 2 | // If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | DESIGN | true | if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65; | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} |
31,644 | 3 | // Otherwise | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | NONSATD | true | else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0; | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} | public int getPriorityLevel(LinkedList<String> questionAsked) {
// If the filtered question is the same than asked
if(normalizedQuestion.equals(questionAsked))
return 100;
// If it is an ordered subset
// TODO I'M NOT SURE IF THIS IS WORKING
else if(isSubset(questionAsked))
return 65;
else if(containsWords(questionAsked)>0)
return 30;
// Otherwise
else
return 0;
} |
31,645 | 0 | /**
* Evaluates if the normalized questions contains the words of the question asked
* and returns the amount of words found.
* TODO I DON'T KNOW IF THIS IS SLOPPY OR IT SHOULD WORK LIKE THIS
* @param questionAsked The question to compare.
* @return The amount of words of questionAsked found in normalizedQuestion.
*/ | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | DESIGN | true | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} |
31,645 | 1 | // Create a counter | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | NONSATD | true | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} |
31,645 | 2 | // For each word asked | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | NONSATD | true | // Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} |
31,645 | 3 | // If found, we add one, otherwise, we add zero | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | NONSATD | true | // For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} |
31,645 | 4 | // Return the value | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | NONSATD | true | containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} | private int containsWords(LinkedList<String> questionAsked) {
// Create a counter
int containedWords = 0;
// For each word asked
for(String wordAsked : questionAsked) {
// If found, we add one, otherwise, we add zero
containedWords += normalizedQuestion.contains(wordAsked) ? 1 : 0;
}
// Return the value
return containedWords;
} |
23,465 | 0 | /**
* Returns the referenced resource, fetching it <b>if it has not already been loaded</b>. This method invokes the HTTP client to retrieve the resource unless it has already been loaded, or was a
* contained resource in which case it is simply returned.
*/ | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | NONSATD | true | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} |
23,465 | 1 | // TODO: choose appropriate parser based on response CT | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | IMPLEMENTATION | true | HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response); | String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} | public IResource loadResource(IRestfulClient theClient) throws IOException {
if (myResource != null) {
return myResource;
}
IdDt resourceId = getReference();
if (resourceId == null) {
throw new IllegalStateException("Reference has no resource ID defined");
}
String resourceUrl = resourceId.getValue();
ourLog.debug("Loading resource at URL: {}", resourceUrl);
HttpClient httpClient = theClient.getHttpClient();
FhirContext context = theClient.getFhirContext();
if (!resourceUrl.startsWith("http")) {
resourceUrl = theClient.getServerBase() + resourceUrl;
}
HttpGet get = new HttpGet(resourceUrl);
HttpResponse response = httpClient.execute(get);
try {
// TODO: choose appropriate parser based on response CT
IParser parser = context.newXmlParser();
Reader responseReader = BaseClient.createReaderFromResponse(response);
myResource = parser.parseResource(responseReader);
} finally {
if (response instanceof CloseableHttpResponse) {
((CloseableHttpResponse) response).close();
}
}
return myResource;
} |
31,695 | 0 | //TORE: [by YS] should be storing repo once interfaces refactoring is done | @Override
@Nonnull
public MutableVfsItem getMutableItem(RepoPath repoPath) {
//TORE: [by YS] should be storing repo once interfaces refactoring is done
LocalRepo localRepo = localOrCachedRepositoryByKey(repoPath.getRepoKey());
if (localRepo != null) {
MutableVfsItem mutableFsItem = localRepo.getMutableFsItem(repoPath);
if (mutableFsItem != null) {
return mutableFsItem;
}
}
throw new ItemNotFoundRuntimeException(repoPath);
} | DESIGN | true | @Nonnull
public MutableVfsItem getMutableItem(RepoPath repoPath) {
//TORE: [by YS] should be storing repo once interfaces refactoring is done
LocalRepo localRepo = localOrCachedRepositoryByKey(repoPath.getRepoKey());
if (localRepo != null) { | @Override
@Nonnull
public MutableVfsItem getMutableItem(RepoPath repoPath) {
//TORE: [by YS] should be storing repo once interfaces refactoring is done
LocalRepo localRepo = localOrCachedRepositoryByKey(repoPath.getRepoKey());
if (localRepo != null) {
MutableVfsItem mutableFsItem = localRepo.getMutableFsItem(repoPath);
if (mutableFsItem != null) {
return mutableFsItem;
}
}
throw new ItemNotFoundRuntimeException(repoPath);
} | @Override
@Nonnull
public MutableVfsItem getMutableItem(RepoPath repoPath) {
//TORE: [by YS] should be storing repo once interfaces refactoring is done
LocalRepo localRepo = localOrCachedRepositoryByKey(repoPath.getRepoKey());
if (localRepo != null) {
MutableVfsItem mutableFsItem = localRepo.getMutableFsItem(repoPath);
if (mutableFsItem != null) {
return mutableFsItem;
}
}
throw new ItemNotFoundRuntimeException(repoPath);
} |
15,312 | 0 | //TODO: file was choosen; | private void initMenuItems() {
menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
var fileChooser = new FileChooser();
var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
}
});
menuItemLibraryCatalog.setDisable(true);
menuItemLibraryImport.setDisable(true);
menuItemSettingsCheat.setDisable(true);
menuItemSettingsSettings.setDisable(true);
} | NONSATD | true | var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
} | private void initMenuItems() {
menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
var fileChooser = new FileChooser();
var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart(); | private void initMenuItems() {
menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
var fileChooser = new FileChooser();
var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
} |
15,312 | 1 | //TODO: Ask You are sure ? | private void initMenuItems() {
menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
var fileChooser = new FileChooser();
var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
}
});
menuItemLibraryCatalog.setDisable(true);
menuItemLibraryImport.setDisable(true);
menuItemSettingsCheat.setDisable(true);
menuItemSettingsSettings.setDisable(true);
} | IMPLEMENTATION | true | @Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
} | if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit(); | private void initMenuItems() {
menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
var fileChooser = new FileChooser();
var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
}
});
menuItemLibraryCatalog.setDisable(true);
menuItemLibraryImport.setDisable(true);
menuItemSettingsCheat.setDisable(true);
menuItemSettingsSettings.setDisable(true);
} |
15,312 | 2 | //TODO: Add question: You are really want to exit. | private void initMenuItems() {
menuItemFileOpen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
var fileChooser = new FileChooser();
var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
}
});
menuItemLibraryCatalog.setDisable(true);
menuItemLibraryImport.setDisable(true);
menuItemSettingsCheat.setDisable(true);
menuItemSettingsSettings.setDisable(true);
} | IMPLEMENTATION | true | @Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
} | public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
}
});
menuItemLibraryCatalog.setDisable(true);
menuItemLibraryImport.setDisable(true);
menuItemSettingsCheat.setDisable(true);
menuItemSettingsSettings.setDisable(true);
} | var selected = fileChooser.showOpenDialog(null);
if (selected != null) {
//TODO: file was choosen;
ifmlEngine.loadStory(selected);
}
}
});
menuItemFileRestart.setDisable(true);
menuItemFileRestart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Ask You are sure ?
ifmlEngine.restart();
}
});
menuItemFileSave.setDisable(true);
menuItemFileLoad.setDisable(true);
menuItemFileExit.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//TODO: Add question: You are really want to exit.
Platform.exit();
}
});
menuItemLibraryCatalog.setDisable(true);
menuItemLibraryImport.setDisable(true);
menuItemSettingsCheat.setDisable(true);
menuItemSettingsSettings.setDisable(true);
} |
31,699 | 0 | /**
* Returns a string representing the supplied day-of-the-week.
* <P>
* Need to find a better approach.
*
* @param weekday the day of the week.
*
* @return a string representing the supplied day-of-the-week.
*/ | public static String weekdayCodeToString(int weekday) {
String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays();
return weekdays[weekday];
} | DESIGN | true | public static String weekdayCodeToString(int weekday) {
String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays();
return weekdays[weekday];
} | public static String weekdayCodeToString(int weekday) {
String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays();
return weekdays[weekday];
} | public static String weekdayCodeToString(int weekday) {
String[] weekdays = DATE_FORMAT_SYMBOLS.getWeekdays();
return weekdays[weekday];
} |
31,700 | 0 | /**
* Returns a string corresponding to the week-in-the-month code.
* <P>
* Need to find a better approach.
*
* @param count an integer code representing the week-in-the-month.
*
* @return a string corresponding to the week-in-the-month code.
*/ | public static String weekInMonthToString(int count) {
switch (count) {
case SerialDate.FIRST_WEEK_IN_MONTH : return "First";
case SerialDate.SECOND_WEEK_IN_MONTH : return "Second";
case SerialDate.THIRD_WEEK_IN_MONTH : return "Third";
case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth";
case SerialDate.LAST_WEEK_IN_MONTH : return "Last";
default :
return "SerialDate.weekInMonthToString(...): invalid code.";
}
} | DESIGN | true | public static String weekInMonthToString(int count) {
switch (count) {
case SerialDate.FIRST_WEEK_IN_MONTH : return "First";
case SerialDate.SECOND_WEEK_IN_MONTH : return "Second";
case SerialDate.THIRD_WEEK_IN_MONTH : return "Third";
case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth";
case SerialDate.LAST_WEEK_IN_MONTH : return "Last";
default :
return "SerialDate.weekInMonthToString(...): invalid code.";
}
} | public static String weekInMonthToString(int count) {
switch (count) {
case SerialDate.FIRST_WEEK_IN_MONTH : return "First";
case SerialDate.SECOND_WEEK_IN_MONTH : return "Second";
case SerialDate.THIRD_WEEK_IN_MONTH : return "Third";
case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth";
case SerialDate.LAST_WEEK_IN_MONTH : return "Last";
default :
return "SerialDate.weekInMonthToString(...): invalid code.";
}
} | public static String weekInMonthToString(int count) {
switch (count) {
case SerialDate.FIRST_WEEK_IN_MONTH : return "First";
case SerialDate.SECOND_WEEK_IN_MONTH : return "Second";
case SerialDate.THIRD_WEEK_IN_MONTH : return "Third";
case SerialDate.FOURTH_WEEK_IN_MONTH : return "Fourth";
case SerialDate.LAST_WEEK_IN_MONTH : return "Last";
default :
return "SerialDate.weekInMonthToString(...): invalid code.";
}
} |
15,338 | 0 | // 0=yes, 1=no, 2=cancel | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} | NONSATD | true | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No. | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} |
15,338 | 1 | //TODO remove the Cancel button. Should only be Yes and No. | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} | DESIGN | true | // 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} | public static boolean yesNo(String yesNoQuestion){
int input = JOptionPane.showConfirmDialog(null, yesNoQuestion);
// 0=yes, 1=no, 2=cancel
return input==0;
//TODO remove the Cancel button. Should only be Yes and No.
} |
31,742 | 0 | /**
* Recolors map colors in the aether dimension to look nicer.
* Could be a redirect, but that would actually probably be less compatible with other mods.
* However, if the game updates this won't break, which is a bad thing
*/ | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} | DESIGN | true | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} |
31,742 | 1 | // MapColor.CLEAR | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} | NONSATD | true | int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please! | value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel(); | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} |
31,742 | 2 | // Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please! | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} | NONSATD | true | int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else { | target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} | @Inject(
method = "updateTexture()V",
at = @At(
value = "HEAD",
target = "net/minecraft/client/render/MapRenderer$MapTexture.updateTexture()V"
),
cancellable = true)
private void updateAetherTexture(CallbackInfo ci) {
if (this.state.dimension == AetherDimension.AETHER_WORLD_KEY){
for (int i = 0; i < 128; ++i) {
for (int j = 0; j < 128; ++j) {
int k = j + i * 128;
int l = this.state.colors[k] & 255;
if (l >> 2 == 0) { // MapColor.CLEAR
// Who knows what this does? Nothing, it seems. But just in case I'll let it stick around.
// Comment your code please!
this.texture.getImage().setColor(j, i, (k + k / 128 & 1) * 8 + 16 << 24);
} else {
this.texture.getImage().setColor(j, i, AetherMapColorUtil.getColor(MapColor.COLORS[l >> 2], l & 3));
}
}
}
this.texture.upload();
ci.cancel();
}
} |
15,371 | 0 | /** Returns the target for the given SpecialInvokeExpr. */ | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} | NONSATD | true | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} |
15,371 | 1 | /*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/ | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} | DESIGN | true | SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target; | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} | public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) {
container.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
SootMethod target = ie.getMethod();
target.getDeclaringClass().checkLevel(SootClass.HIERARCHY);
/*
* This is a bizarre condition! Hopefully the implementation is correct. See VM Spec, 2nd Edition, Chapter 6, in the
* definition of invokespecial.
*/
if ("<init>".equals(target.getName()) || target.isPrivate()) {
return target;
} else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) {
return resolveConcreteDispatch(container.getDeclaringClass(), target);
} else {
return target;
}
} |
31,761 | 0 | // Hash Calculator | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME) | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator) | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0); |
31,761 | 1 | // Encryptor for encrypting secret keys | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | .build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor; | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null; | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId()) |
31,761 | 2 | // AES-256 encrypted | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | @Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME) | InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys. | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator( |
31,761 | 3 | // unencrypted key pair | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | .build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
} | .get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder( | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec); |
31,761 | 4 | // First key is the Master Key | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys. | @Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets(); | public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else { |
31,761 | 5 | // Remove master key, so that we later only add sub keys. | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | // First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key | // AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator( | InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
} |
31,761 | 6 | // Generate Master Key | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | // Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature | .setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator, | final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing(); |
31,761 | 7 | // Signer for creating self-signature | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | // Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId()) | } else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) { | .build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released |
31,761 | 8 | // Generator which the user can get the key pair from | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | .setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey, | final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null); | if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder() |
31,761 | 9 | // TODO: Remove once BC 1.61 is released | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | DESIGN | true | final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) { | for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null; | // Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
} |
31,761 | 10 | // AES-256 encrypted | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | @Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME) | InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys. | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator( |
31,761 | 11 | // unencrypted key pair | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec);
if (subKeySpec.isInheritedSubPackets()) {
ringGenerator.addSubKey(subKey);
} else {
ringGenerator.addSubKey(subKey, subKeySpec.getSubpackets(), null);
}
}
final PGPPublicKeyRing publicKeys = ringGenerator.generatePublicKeyRing();
PGPSecretKeyRing secretKeys = ringGenerator.generateSecretKeyRing();
// TODO: Remove once BC 1.61 is released
final PBESecretKeyDecryptor decryptor;
if (withPassphrase) {
// AES-256 encrypted
decryptor = new JcePBESecretKeyDecryptorBuilder(
new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()).build(passphrase.getChars());
} else {
// unencrypted key pair
decryptor = null;
}
secretKeys = KeyRingSubKeyFixUtil.repairSubkeyPackets(secretKeys, decryptor, encryptor);
final InMemoryKeyring keyring;
if (passphrase.isEmpty()) {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withUnprotectedKeys());
} else {
keyring = KeyringConfigs
.forGpgExportedKeys(KeyringConfigCallbacks.withPassword(passphrase.getChars()));
}
keyring.addSecretKeyRing(secretKeys);
keyring.addPublicKeyRing(publicKeys);
passphrase.clear();
return keyring;
} | NONSATD | true | .build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
} | .get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder( | @Override
public KeyringConfig build()
throws NoSuchAlgorithmException, PGPException, NoSuchProviderException,
InvalidAlgorithmParameterException, IOException {
// Hash Calculator
final PGPDigestCalculator calculator = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build()
.get(PGPHashAlgorithms.SHA1.getAlgorithmId());
// Encryptor for encrypting secret keys
final boolean withPassphrase = !passphrase.isEmpty();
@Nullable final PBESecretKeyEncryptor encryptor;
if (withPassphrase) {
// AES-256 encrypted
encryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, calculator)
.setProvider(BouncyCastleProvider.PROVIDER_NAME)
.build(passphrase.getChars());
} else {
// unencrypted key pair
encryptor = null;
}
// First key is the Master Key
final KeySpec certKeySpec = keySpecs.get(0);
// Remove master key, so that we later only add sub keys.
keySpecs.remove(0);
// Generate Master Key
final PGPKeyPair certKey = generateKeyPair(certKeySpec);
// Signer for creating self-signature
final PGPContentSignerBuilder signer = new JcaPGPContentSignerBuilder(
certKey.getPublicKey().getAlgorithm(), PGPHashAlgorithms.SHA_512.getAlgorithmId())
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PGPSignatureSubpacketVector hashedSubPackets = certKeySpec.getSubpackets();
// Generator which the user can get the key pair from
final PGPKeyRingGenerator ringGenerator = new PGPKeyRingGenerator(
PGPSignature.POSITIVE_CERTIFICATION, certKey,
userId, calculator,
hashedSubPackets, null, signer, encryptor);
for (final KeySpec subKeySpec : keySpecs) {
final PGPKeyPair subKey = generateKeyPair(subKeySpec); |
31,763 | 0 | // TODO Does not work with Boot Integeration tests: | @Test
public void test_EchoUser_restTemplate() {
String firstName = "Chuck";
String lastName = "Norris";
String result = restTemplate.getForObject(
"http://localhost:8888/"+firstName+"/"+lastName,
String.class);
String expected = "{\"firstName\":\""+firstName+"\",\"lastName\":\""+lastName+"\"}";
assertThat(result, containsString(expected));
log.info("*** Successfully echoed a User ("+firstName+" "+lastName+") through REST ***");
} | DEFECT | true | @Test
public void test_EchoUser_restTemplate() {
String firstName = "Chuck";
String lastName = "Norris";
String result = restTemplate.getForObject(
"http://localhost:8888/"+firstName+"/"+lastName,
String.class);
String expected = "{\"firstName\":\""+firstName+"\",\"lastName\":\""+lastName+"\"}";
assertThat(result, containsString(expected));
log.info("*** Successfully echoed a User ("+firstName+" "+lastName+") through REST ***");
} | @Test
public void test_EchoUser_restTemplate() {
String firstName = "Chuck";
String lastName = "Norris";
String result = restTemplate.getForObject(
"http://localhost:8888/"+firstName+"/"+lastName,
String.class);
String expected = "{\"firstName\":\""+firstName+"\",\"lastName\":\""+lastName+"\"}";
assertThat(result, containsString(expected));
log.info("*** Successfully echoed a User ("+firstName+" "+lastName+") through REST ***");
} | @Test
public void test_EchoUser_restTemplate() {
String firstName = "Chuck";
String lastName = "Norris";
String result = restTemplate.getForObject(
"http://localhost:8888/"+firstName+"/"+lastName,
String.class);
String expected = "{\"firstName\":\""+firstName+"\",\"lastName\":\""+lastName+"\"}";
assertThat(result, containsString(expected));
log.info("*** Successfully echoed a User ("+firstName+" "+lastName+") through REST ***");
} |
23,575 | 0 | // TODO Auto-generated method stub
//Assuming stock of each sport is 2 | public static void main(String[] args) {
// TODO Auto-generated method stub
//Assuming stock of each sport is 2
Sports sp1=new IndoorSports();
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Billiards(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Carrom(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Badminton(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
Sports sp2=new OutdoorSports();
System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new Trekking(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new Cricket(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new HighJump(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new LongJump(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
} | DESIGN | true | public static void main(String[] args) {
// TODO Auto-generated method stub
//Assuming stock of each sport is 2
Sports sp1=new IndoorSports();
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); | public static void main(String[] args) {
// TODO Auto-generated method stub
//Assuming stock of each sport is 2
Sports sp1=new IndoorSports();
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Billiards(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Carrom(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Badminton(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
Sports sp2=new OutdoorSports();
System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock()); | public static void main(String[] args) {
// TODO Auto-generated method stub
//Assuming stock of each sport is 2
Sports sp1=new IndoorSports();
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Billiards(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Carrom(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
sp1=new Badminton(sp1);
System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock());
Sports sp2=new OutdoorSports();
System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new Trekking(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new Cricket(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new HighJump(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
sp2=new LongJump(sp2);
System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock());
} |
15,390 | 0 | /**
* Finds the main action predicates in the sentence and their respective arguments.
* For each, creates a RecipeEvent object to store the information. This information
* is stored in the predicate_idx_to_event map.
*
* @param node verb node to be examining
* @param edge_rels map of governor/dependent pairs and the edge relation that connects
* them, if any.
* @param node_to_deps map that connects a governor node to its dependents.
* @param leaves list of leaf nodes of the constituent parse tree
* @param lemmas list of lemmas of tokens in the sentence
* @param tags list of POS tags of the tokens in the sentence
* @param words list of words in the sentence
* @param recipe_name name of the recipe
* @param sentence_idx index of the sentence within the current recipe
* @param curr_sentence_char_offset starting no-space character offset of the
* current sentence
* @param sentence_string full text string of the current sentence
* @param predicate_idx_to_event map of character offsets to the recipe events that start
* at that offset. Note that this is not the no-space character offset since
* the tree map just cares about the relative order
*/ | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} |
15,390 | 1 | // Find the no-space character offset of the predicate | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset); | Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
} | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset); |
15,390 | 2 | // Create RecipeEvent | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event); | sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) { | int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index(); |
15,390 | 3 | // check for pcomp | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null; | }
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
} | no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
} |
15,390 | 4 | // Create RecipeEvent | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event); | sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) { | int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index(); |
15,390 | 5 | // If the verb has a subject other than "I", assume parse error and add the subject as an argument. | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | }
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type); | boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx, | RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
} |
15,390 | 6 | // TODO(chloe): do something else in this case? | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | DESIGN | true | }
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node); | break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument. | dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
} |
15,390 | 7 | // Search through the dependents of the verb and add each expanded dependent as an argument. | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | }
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null; | // TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
} | break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1)); |
15,390 | 8 | // skip subjects | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
} | gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) { | TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
} |
15,390 | 9 | // Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found. | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | }
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue; | String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) { | int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string); |
15,390 | 10 | // For vmod and xcomp edges, create an argument for the current verb | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true); | if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
} | gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
} |
15,390 | 11 | // Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out. | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1); | }
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) { | if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) { |
15,390 | 12 | // prepositional phrase | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue; | if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) { | int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string); |
15,390 | 13 | // Find the true preposition from the collapsed dependency relation | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | }
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) { | args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
} | curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) { |
15,390 | 14 | // event.setDirectObject(arg_string); | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1; | arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string); | }
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
} |
15,390 | 15 | // This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it. | private void findActionVerbsAndArguments(TreeGraphNode node,
Map<Pair<Integer, Integer>, String> edge_rels,
Map<TreeGraphNode, Set<TreeGraphNode>> node_to_deps,
Map<TreeGraphNode, TreeGraphNode> dep_to_gov,
String root_type,
List<Tree> leaves,
List<String> lemmas, List<Label> tags, List<HasWord> words,
String recipe_name, int sentence_idx, int curr_sentence_char_offset,
String sentence_string, TreeMap<Integer, RecipeEvent> predicate_idx_to_event) {
String node_string = node.nodeString();
int index = node.index();
Label tag = tags.get(index - 1);
int hw_character_offset = charOffset(leaves.get(index - 1));
// Find the no-space character offset of the predicate
int no_space_character_offset = hw_character_offset;
String sentence_prefix = sentence_string.substring(0, hw_character_offset);
while (sentence_prefix.contains(" I would ")) {
no_space_character_offset -= 9;
sentence_prefix = sentence_prefix.replaceFirst(" I would ", "");
}
while (sentence_prefix.contains("I would ")) {
no_space_character_offset -= 8;
sentence_prefix = sentence_prefix.replaceFirst("I would ", "");
}
while (sentence_prefix.contains(" ")) {
no_space_character_offset--;
sentence_prefix = sentence_prefix.replaceFirst(" ", "");
}
if (tag.value().startsWith("V")) {
Set<TreeGraphNode> deps = node_to_deps.get(node);
if (deps == null) {
System.out.println(node + " " + deps);
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
predicate_idx_to_event.put(hw_character_offset, event);
return;
}
// check for pcomp
boolean has_pcomp = false;
TreeGraphNode pcomp = null;
for (TreeGraphNode dep3 : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep3)));
if (rel_string2.equals("pcomp")) {
has_pcomp = true;
pcomp = dep3;
break;
}
}
if (has_pcomp) {
System.out.println("has pcomp");
TreeGraphNode grandgov = dep_to_gov.get(node);
if (grandgov != null) {
int grandgov_index = grandgov.index();
RecipeEvent grandevent = predicate_idx_to_event.get(grandgov_index);
if (grandevent != null) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, true);
grandevent.addPrepositionalArgument(hw_character_offset, args.getFirst(), pcomp.nodeString());
}
}
return;
}
// Create RecipeEvent
RecipeEvent event = new RecipeEvent(node_string.toLowerCase(), recipe_name, sentence_idx, curr_sentence_char_offset + no_space_character_offset);
boolean has_subj = false;
TreeGraphNode subj = null;
for (TreeGraphNode dep : deps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(hw_character_offset, charOffset(dep)));
if (rel_string2.equals("nsubj") && !root_type.equals("SINV")) {
has_subj = true;
subj = dep;
break;
}
}
// If the verb has a subject other than "I", assume parse error and add the subject as an argument.
if (has_subj && !root_type.equals("SINV")) {
System.out.println(has_subj + " " + root_type);
if (!subj.nodeString().equals("I")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
if (verbs.size() == 1) {
TreeGraphNode verb = verbs.iterator().next();
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
RecipeEvent dep_event = predicate_idx_to_event.get(charOffset(leaves.get(verb.index() - 1)));
if (dep_event != null) {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(node.nodeString())) {
found = i;
break;
}
}
if (tags.get(index - found - 1).value().equals("IN")) {
dep_event.addPrepositionalArgument(hw_character_offset, arg_string);
} else {
dep_event.addOtherArgument(hw_character_offset, arg_string);
}
}
} else {
// TODO(chloe): do something else in this case?
for (TreeGraphNode verb : verbs) {
dep_to_gov.put(verb, node);
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
return;
}
}
// Search through the dependents of the verb and add each expanded dependent as an argument.
Set<TreeGraphNode> new_deps = new HashSet<TreeGraphNode>(deps);
TreeGraphNode pobj = null;
while (new_deps.size() != 0) {
List<TreeGraphNode> deps_list = new ArrayList<TreeGraphNode>(new_deps);
new_deps.clear();
for (TreeGraphNode dep : deps_list) {
TreeGraphNode gov = dep_to_gov.get(dep);
if (gov == null) {
gov = node;
}
int gov_index = index;
int gov_hw_offset = hw_character_offset;
String gov_string = node_string;
if (gov != null) {
gov_index = gov.index();
gov_hw_offset = charOffset(leaves.get(gov_index - 1));
gov_string = gov.nodeString();
}
int dep_index = dep.index();
int dep_hw_offset = charOffset(leaves.get(dep_index - 1));
String dep_string = dep.nodeString();
if (dep.nodeString().equals("would")) {
continue;
}
String rel_string = edge_rels.get(new Pair<Integer, Integer>(gov_hw_offset, dep_hw_offset));
if (rel_string.startsWith("nsubj") && !root_type.equals("SINV") && (gov == node || dep.nodeString().equals("I"))) {
// skip subjects
continue;
}
if (rel_string.startsWith("pobj")) {
// Store the prepositional object, but ignore for now. We will deal with it when the
// prepositional phrase is found.
pobj = dep;
continue;
}
// For vmod and xcomp edges, create an argument for the current verb
if (rel_string.equals("vmod") || rel_string.equals("xcomp")) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
continue;
}
// Deal with prepositional phrases and determining whether or not a dependent verb is a new verb or
// part of the current verb. Uses heuristics to find out.
boolean is_prep = rel_string.startsWith("prep") || tags.get(dep_index - 1).value().equals("IN");
Label dep_tag = tags.get(dep_index - 1);
if (dep_tag.value().startsWith("V") && !is_prep && !rel_string.equals("advcl")
) {
if (dep_index == index + 2 && rel_string.startsWith("conj")) {
int underscore = rel_string.indexOf('_');
String conj_string = rel_string.substring(underscore + 1);
node_string += " " + conj_string + " " + dep_string;
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), conj_string, (dep.index() > gov_index));
} else if (rel_string.startsWith("conj") || rel_string.equals("parataxis") || rel_string.equals("dep")) {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
has_subj = false;
if (depdeps != null) {
for (TreeGraphNode depdep : depdeps) {
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(dep_hw_offset, charOffset(leaves.get(depdep.index() - 1))));
if (rel_string2.equals("nsubj")) {
has_subj = true;
break;
}
}
if (has_subj) {
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, true);
String arg_string = args.getFirst();
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
} else {
findActionVerbsAndArguments(dep, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
}
} else {
Set<TreeGraphNode> depdeps = node_to_deps.get(dep);
if (depdeps != null) {
new_deps.addAll(depdeps);
for (TreeGraphNode depdep : depdeps) {
dep_to_gov.put(depdep, dep);
}
}
event.addVerbToPredicate(dep.nodeString(), "", (dep.index() > gov_index));
}
} else { // prepositional phrase
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(dep, node_to_deps, edge_rels, lemmas, tags, words, is_prep || rel_string.equals("dobj"));
String arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
if (is_prep) {
String pobj_arg_string = null;
if (pobj != null) {
args = getTreeGraphString(pobj, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "" , leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
} else {
for (TreeGraphNode dep2 : deps_list) {
TreeGraphNode gov2 = dep_to_gov.get(dep2);
if (gov2 == null) {
gov2 = gov;
}
String rel_string2 = edge_rels.get(new Pair<Integer, Integer>(charOffset(leaves.get(gov2.index() - 1)), charOffset(leaves.get(dep2.index() - 1))));
if (rel_string2.equals("pobj")) {
args = getTreeGraphString(dep2, node_to_deps, edge_rels, lemmas, tags, words, is_prep);
pobj_arg_string = args.getFirst();
for (TreeGraphNode verb : args.getSecond()) {
findActionVerbsAndArguments(verb, edge_rels, node_to_deps, dep_to_gov, "", leaves, lemmas, tags, words, recipe_name, sentence_idx,
curr_sentence_char_offset, sentence_string, predicate_idx_to_event);
}
break;
}
}
}
// Find the true preposition from the collapsed dependency relation
int underscore = rel_string.indexOf('_');
if (underscore != -1) {
String prep_string = rel_string.substring(underscore + 1);
prep_string = prep_string.replace('_', ' ');
if (pobj_arg_string != null) {
if (prep_string.contains(arg_string)) {
arg_string = prep_string + " " + pobj_arg_string;
} else {
arg_string = prep_string + " " + arg_string + " " + pobj_arg_string;
}
} else {
arg_string = prep_string + " " + arg_string;
}
}
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else if (rel_string.equals("dobj") || rel_string.equals("nsubj")) {
// event.setDirectObject(arg_string);
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
System.out.println("DIRECTOBJECT " + arg_string);
if (tags.get(dep_index - found - 1).value().equals("IN")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
if (arg_string.contains("minutes") || arg_string.contains("hours")) {
event.addPrepositionalArgument(dep_hw_offset, arg_string, "for");
} else {
event.setDirectObject(arg_string);
}
}
}
} else {
String[] split = arg_string.split(" ");
int found = -1;
for (int i = 0; i < split.length; i++) {
if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | NONSATD | true | predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst(); | event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} | if (split[i].equals(dep.nodeString())) {
found = i;
break;
}
}
if (found != -1) {
if (tags.get(dep_index - found - 1).value().equals("IN")) {
System.out.println("prep");
event.addPrepositionalArgument(dep_hw_offset, arg_string);
} else {
event.addOtherArgument(dep_hw_offset, arg_string);
}
}
}
}
}
}
System.out.println(event);
predicate_idx_to_event.put(index, event);
} else {
// This method should not be called if the node is not a verb.
//
// Not sure if this happens, so I will currently have it crash so I can investigate it.
Pair<String, Set<TreeGraphNode>> args = getTreeGraphString(node, node_to_deps, edge_rels, lemmas, tags, words, false);
String arg_string = args.getFirst();
Set<TreeGraphNode> verbs = args.getSecond();
System.out.println(arg_string);
System.out.println("getting args error");
System.exit(1);
}
} |
15,413 | 0 | // FIXME this breaks referential equality, but maybe it's OK | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} | DEFECT | true | ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return; | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) { | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err); |
15,413 | 1 | //System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName()); | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} | NONSATD | true | return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class); | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get(); | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} |
15,413 | 2 | // FIXME FIXME super ad-hoc | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} | DEFECT | true | }
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) { | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
} | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} |
15,413 | 3 | // here's a place where two locations could be bound to each other? | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} | NONSATD | true | value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) { | ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return; | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} |
15,413 | 4 | // FIXME is there a better way??? | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} | DESIGN | true | value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) { | variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
} | public void put(String name, Scriptable start, Object value) {
try {
ObjectLocation variable = this.extractFieldVariable(name);
if (value instanceof NativeArray) {
// FIXME this breaks referential equality, but maybe it's OK
variable.set(this.sequenceFromArray((NativeArray)value, start));
return;
}
//System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName());
if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc
value = Context.jsToJava(value, Float.class);
} else if (value instanceof ObjectLocation) {
// here's a place where two locations could be bound to each other?
value = ((ObjectLocation)value).get();
} else if (value instanceof Wrapper) {
// FIXME is there a better way???
value = ((Wrapper)value).unwrap();
if (value instanceof ObjectLocation) {
value = ((ObjectLocation)value).get();
}
}
variable.set(value);
return;
} catch (Exception e) {
e.printStackTrace(System.err);
}
} |
15,430 | 0 | // Note: Do not change method | private static Method getMethod() {
return method.get(0);
} | DESIGN | true | private static Method getMethod() {
return method.get(0);
} | private static Method getMethod() {
return method.get(0);
} | private static Method getMethod() {
return method.get(0);
} |
15,434 | 0 | /** GETTER
* TODO: Write general description for this method
*/ | @JsonGetter("name")
public String getName ( ) {
return this.name;
} | DOCUMENTATION | true | @JsonGetter("name")
public String getName ( ) {
return this.name;
} | @JsonGetter("name")
public String getName ( ) {
return this.name;
} | @JsonGetter("name")
public String getName ( ) {
return this.name;
} |
15,435 | 0 | /** SETTER
* TODO: Write general description for this method
*/ | @JsonSetter("name")
public void setName (String value) {
this.name = value;
} | DOCUMENTATION | true | @JsonSetter("name")
public void setName (String value) {
this.name = value;
} | @JsonSetter("name")
public void setName (String value) {
this.name = value;
} | @JsonSetter("name")
public void setName (String value) {
this.name = value;
} |
15,436 | 0 | /** GETTER
* TODO: Write general description for this method
*/ | @JsonGetter("product_details")
public ProductData getProductDetails ( ) {
return this.productDetails;
} | DOCUMENTATION | true | @JsonGetter("product_details")
public ProductData getProductDetails ( ) {
return this.productDetails;
} | @JsonGetter("product_details")
public ProductData getProductDetails ( ) {
return this.productDetails;
} | @JsonGetter("product_details")
public ProductData getProductDetails ( ) {
return this.productDetails;
} |
15,437 | 0 | /** SETTER
* TODO: Write general description for this method
*/ | @JsonSetter("product_details")
public void setProductDetails (ProductData value) {
this.productDetails = value;
} | DOCUMENTATION | true | @JsonSetter("product_details")
public void setProductDetails (ProductData value) {
this.productDetails = value;
} | @JsonSetter("product_details")
public void setProductDetails (ProductData value) {
this.productDetails = value;
} | @JsonSetter("product_details")
public void setProductDetails (ProductData value) {
this.productDetails = value;
} |
15,438 | 0 | /** GETTER
* TODO: Write general description for this method
*/ | @JsonGetter("product_id")
public Integer getProductId ( ) {
return this.productId;
} | DOCUMENTATION | true | @JsonGetter("product_id")
public Integer getProductId ( ) {
return this.productId;
} | @JsonGetter("product_id")
public Integer getProductId ( ) {
return this.productId;
} | @JsonGetter("product_id")
public Integer getProductId ( ) {
return this.productId;
} |
15,439 | 0 | /** SETTER
* TODO: Write general description for this method
*/ | @JsonSetter("product_id")
public void setProductId (Integer value) {
this.productId = value;
} | DOCUMENTATION | true | @JsonSetter("product_id")
public void setProductId (Integer value) {
this.productId = value;
} | @JsonSetter("product_id")
public void setProductId (Integer value) {
this.productId = value;
} | @JsonSetter("product_id")
public void setProductId (Integer value) {
this.productId = value;
} |
15,440 | 0 | /** GETTER
* TODO: Write general description for this method
*/ | @JsonGetter("product_identifiers")
public ProductIdentifiers getProductIdentifiers ( ) {
return this.productIdentifiers;
} | DOCUMENTATION | true | @JsonGetter("product_identifiers")
public ProductIdentifiers getProductIdentifiers ( ) {
return this.productIdentifiers;
} | @JsonGetter("product_identifiers")
public ProductIdentifiers getProductIdentifiers ( ) {
return this.productIdentifiers;
} | @JsonGetter("product_identifiers")
public ProductIdentifiers getProductIdentifiers ( ) {
return this.productIdentifiers;
} |
15,441 | 0 | /** SETTER
* TODO: Write general description for this method
*/ | @JsonSetter("product_identifiers")
public void setProductIdentifiers (ProductIdentifiers value) {
this.productIdentifiers = value;
} | DOCUMENTATION | true | @JsonSetter("product_identifiers")
public void setProductIdentifiers (ProductIdentifiers value) {
this.productIdentifiers = value;
} | @JsonSetter("product_identifiers")
public void setProductIdentifiers (ProductIdentifiers value) {
this.productIdentifiers = value;
} | @JsonSetter("product_identifiers")
public void setProductIdentifiers (ProductIdentifiers value) {
this.productIdentifiers = value;
} |
15,442 | 0 | /** GETTER
* TODO: Write general description for this method
*/ | @JsonGetter("product_timestamps")
public ProductTimestamps getProductTimestamps ( ) {
return this.productTimestamps;
} | DOCUMENTATION | true | @JsonGetter("product_timestamps")
public ProductTimestamps getProductTimestamps ( ) {
return this.productTimestamps;
} | @JsonGetter("product_timestamps")
public ProductTimestamps getProductTimestamps ( ) {
return this.productTimestamps;
} | @JsonGetter("product_timestamps")
public ProductTimestamps getProductTimestamps ( ) {
return this.productTimestamps;
} |
15,443 | 0 | /** SETTER
* TODO: Write general description for this method
*/ | @JsonSetter("product_timestamps")
public void setProductTimestamps (ProductTimestamps value) {
this.productTimestamps = value;
} | DOCUMENTATION | true | @JsonSetter("product_timestamps")
public void setProductTimestamps (ProductTimestamps value) {
this.productTimestamps = value;
} | @JsonSetter("product_timestamps")
public void setProductTimestamps (ProductTimestamps value) {
this.productTimestamps = value;
} | @JsonSetter("product_timestamps")
public void setProductTimestamps (ProductTimestamps value) {
this.productTimestamps = value;
} |
15,444 | 0 | /** GETTER
* TODO: Write general description for this method
*/ | @JsonGetter("purchase_history")
public List<PurchaseInfo> getPurchaseHistory ( ) {
return this.purchaseHistory;
} | DOCUMENTATION | true | @JsonGetter("purchase_history")
public List<PurchaseInfo> getPurchaseHistory ( ) {
return this.purchaseHistory;
} | @JsonGetter("purchase_history")
public List<PurchaseInfo> getPurchaseHistory ( ) {
return this.purchaseHistory;
} | @JsonGetter("purchase_history")
public List<PurchaseInfo> getPurchaseHistory ( ) {
return this.purchaseHistory;
} |
15,445 | 0 | /** SETTER
* TODO: Write general description for this method
*/ | @JsonSetter("purchase_history")
public void setPurchaseHistory (List<PurchaseInfo> value) {
this.purchaseHistory = value;
} | DOCUMENTATION | true | @JsonSetter("purchase_history")
public void setPurchaseHistory (List<PurchaseInfo> value) {
this.purchaseHistory = value;
} | @JsonSetter("purchase_history")
public void setPurchaseHistory (List<PurchaseInfo> value) {
this.purchaseHistory = value;
} | @JsonSetter("purchase_history")
public void setPurchaseHistory (List<PurchaseInfo> value) {
this.purchaseHistory = value;
} |
15,468 | 0 | // Retrieves <input type="file" name="file"> | private void handleUpload(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException, WsException {
checkPermission(WebswingAction.file_upload);
try {
String uuid = request.getParameter("uuid");
if (uuid != null) {
SwingInstance instance = manager.findInstanceBySessionId(uuid);
if (instance != null) {
double maxMB = instance.getAppConfig().getUploadMaxSize();
long maxsize = (long) (maxMB * 1024 * 1024);
Part filePart = request.getPart("files[]"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
if (maxsize > 0 && filePart.getSize() > maxsize) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB));
} else {
String tempDir = System.getProperty(Constants.TEMP_DIR_PATH);
String tempName = UUID.randomUUID().toString();
InputStream filecontent = filePart.getInputStream();
File f = new File(URI.create(tempDir + "/" + tempName));
FileOutputStream output = new FileOutputStream(f);
IOUtils.copy(filecontent, output);
output.close();
filecontent.close();
log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath());
UploadEventMsgIn msg = new UploadEventMsgIn();
msg.setFileName(filename);
msg.setTempFileLocation(f.getAbsolutePath());
boolean sent = instance.sendToSwing(null, msg);
if (!sent) {
log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId());
f.delete();
} else {
resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); // TODO size
}
}
} else {
throw new Exception("Related App instance not found.(" + uuid + ")");
}
} else {
throw new Exception("UUID not specified in request");
}
} catch (Exception e) {
if (e.getCause() instanceof EOFException) {
log.warn("File upload canceled by user: " + e.getMessage());
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
resp.getWriter().write("Upload finished with error...");
log.error("Error while uploading file: " + e.getMessage(), e);
}
}
} | NONSATD | true | double maxMB = instance.getAppConfig().getUploadMaxSize();
long maxsize = (long) (maxMB * 1024 * 1024);
Part filePart = request.getPart("files[]"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
if (maxsize > 0 && filePart.getSize() > maxsize) { | private void handleUpload(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException, WsException {
checkPermission(WebswingAction.file_upload);
try {
String uuid = request.getParameter("uuid");
if (uuid != null) {
SwingInstance instance = manager.findInstanceBySessionId(uuid);
if (instance != null) {
double maxMB = instance.getAppConfig().getUploadMaxSize();
long maxsize = (long) (maxMB * 1024 * 1024);
Part filePart = request.getPart("files[]"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
if (maxsize > 0 && filePart.getSize() > maxsize) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB));
} else {
String tempDir = System.getProperty(Constants.TEMP_DIR_PATH);
String tempName = UUID.randomUUID().toString();
InputStream filecontent = filePart.getInputStream();
File f = new File(URI.create(tempDir + "/" + tempName));
FileOutputStream output = new FileOutputStream(f); | private void handleUpload(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException, WsException {
checkPermission(WebswingAction.file_upload);
try {
String uuid = request.getParameter("uuid");
if (uuid != null) {
SwingInstance instance = manager.findInstanceBySessionId(uuid);
if (instance != null) {
double maxMB = instance.getAppConfig().getUploadMaxSize();
long maxsize = (long) (maxMB * 1024 * 1024);
Part filePart = request.getPart("files[]"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
if (maxsize > 0 && filePart.getSize() > maxsize) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB));
} else {
String tempDir = System.getProperty(Constants.TEMP_DIR_PATH);
String tempName = UUID.randomUUID().toString();
InputStream filecontent = filePart.getInputStream();
File f = new File(URI.create(tempDir + "/" + tempName));
FileOutputStream output = new FileOutputStream(f);
IOUtils.copy(filecontent, output);
output.close();
filecontent.close();
log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath());
UploadEventMsgIn msg = new UploadEventMsgIn();
msg.setFileName(filename);
msg.setTempFileLocation(f.getAbsolutePath());
boolean sent = instance.sendToSwing(null, msg);
if (!sent) {
log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId()); |
15,468 | 1 | // TODO size | private void handleUpload(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException, WsException {
checkPermission(WebswingAction.file_upload);
try {
String uuid = request.getParameter("uuid");
if (uuid != null) {
SwingInstance instance = manager.findInstanceBySessionId(uuid);
if (instance != null) {
double maxMB = instance.getAppConfig().getUploadMaxSize();
long maxsize = (long) (maxMB * 1024 * 1024);
Part filePart = request.getPart("files[]"); // Retrieves <input type="file" name="file">
String filename = getFilename(filePart);
if (maxsize > 0 && filePart.getSize() > maxsize) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB));
} else {
String tempDir = System.getProperty(Constants.TEMP_DIR_PATH);
String tempName = UUID.randomUUID().toString();
InputStream filecontent = filePart.getInputStream();
File f = new File(URI.create(tempDir + "/" + tempName));
FileOutputStream output = new FileOutputStream(f);
IOUtils.copy(filecontent, output);
output.close();
filecontent.close();
log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath());
UploadEventMsgIn msg = new UploadEventMsgIn();
msg.setFileName(filename);
msg.setTempFileLocation(f.getAbsolutePath());
boolean sent = instance.sendToSwing(null, msg);
if (!sent) {
log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId());
f.delete();
} else {
resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); // TODO size
}
}
} else {
throw new Exception("Related App instance not found.(" + uuid + ")");
}
} else {
throw new Exception("UUID not specified in request");
}
} catch (Exception e) {
if (e.getCause() instanceof EOFException) {
log.warn("File upload canceled by user: " + e.getMessage());
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
resp.getWriter().write("Upload finished with error...");
log.error("Error while uploading file: " + e.getMessage(), e);
}
}
} | NONSATD | true | f.delete();
} else {
resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); // TODO size
}
} | filecontent.close();
log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath());
UploadEventMsgIn msg = new UploadEventMsgIn();
msg.setFileName(filename);
msg.setTempFileLocation(f.getAbsolutePath());
boolean sent = instance.sendToSwing(null, msg);
if (!sent) {
log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId());
f.delete();
} else {
resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); // TODO size
}
}
} else {
throw new Exception("Related App instance not found.(" + uuid + ")");
}
} else {
throw new Exception("UUID not specified in request");
}
} catch (Exception e) {
if (e.getCause() instanceof EOFException) { | resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().write(String.format("File '%s' is too large. (Max. file size is %.1fMB)", filename, maxMB));
} else {
String tempDir = System.getProperty(Constants.TEMP_DIR_PATH);
String tempName = UUID.randomUUID().toString();
InputStream filecontent = filePart.getInputStream();
File f = new File(URI.create(tempDir + "/" + tempName));
FileOutputStream output = new FileOutputStream(f);
IOUtils.copy(filecontent, output);
output.close();
filecontent.close();
log.info("File " + filename + " uploaded (size:" + filePart.getSize() + ") to " + f.getAbsolutePath());
UploadEventMsgIn msg = new UploadEventMsgIn();
msg.setFileName(filename);
msg.setTempFileLocation(f.getAbsolutePath());
boolean sent = instance.sendToSwing(null, msg);
if (!sent) {
log.error("Failed to send upload notification to app session. File:" + filename + "+ClientID:" + instance.getClientId());
f.delete();
} else {
resp.getWriter().write("{\"files\":[{\"name\":\"" + filename + "\"}]}"); // TODO size
}
}
} else {
throw new Exception("Related App instance not found.(" + uuid + ")");
}
} else {
throw new Exception("UUID not specified in request");
}
} catch (Exception e) {
if (e.getCause() instanceof EOFException) {
log.warn("File upload canceled by user: " + e.getMessage());
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
resp.getWriter().write("Upload finished with error...");
log.error("Error while uploading file: " + e.getMessage(), e);
}
}
} |
15,473 | 0 | // Ensure directories exist | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath());
}
return parent.resolve(path);
} | NONSATD | true | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) { | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath());
}
return parent.resolve(path);
} | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath());
}
return parent.resolve(path);
} |
15,473 | 1 | // Failed to create directories... should probably let this crash | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath());
}
return parent.resolve(path);
} | DEFECT | true | File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath()); | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath());
}
return parent.resolve(path);
} | private static Path resolve(Path parent, String path) {
// Ensure directories exist
File directory = parent.toFile();
if (!directory.exists() && !directory.mkdirs()) {
// Failed to create directories... should probably let this crash
ScalingHealth.LOGGER.error("Failed to create config directory '{}'. This won't end well...",
directory.getAbsolutePath());
}
return parent.resolve(path);
} |
23,670 | 0 | // Ignore IO exception, what are we going to do anyway? | public Configs getConfigs() {
Configs configs = null;
InputStream is = settingsFacade.getRawConfig(SMS_CONFIGS_FILE_NAME);
String errorMessage = null;
if (is == null) {
throw new JsonIOException(SMS_CONFIGS_FILE_NAME + " missing");
}
try {
String jsonText = IOUtils.toString(is);
Gson gson = new Gson();
configs = gson.fromJson(jsonText, Configs.class);
} catch (Exception e) {
errorMessage = "Might you have a malformed " + SMS_CONFIGS_FILE_NAME + " file? " + e.toString();
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore IO exception, what are we going to do anyway?
logger.error("IOException when closing config file {}: {}", SMS_CONFIGS_FILE_NAME, e);
}
}
if (errorMessage != null) {
throw new JsonIOException(errorMessage);
}
return configs;
} | DESIGN | true | is.close();
} catch (IOException e) {
// Ignore IO exception, what are we going to do anyway?
logger.error("IOException when closing config file {}: {}", SMS_CONFIGS_FILE_NAME, e);
} | try {
String jsonText = IOUtils.toString(is);
Gson gson = new Gson();
configs = gson.fromJson(jsonText, Configs.class);
} catch (Exception e) {
errorMessage = "Might you have a malformed " + SMS_CONFIGS_FILE_NAME + " file? " + e.toString();
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore IO exception, what are we going to do anyway?
logger.error("IOException when closing config file {}: {}", SMS_CONFIGS_FILE_NAME, e);
}
}
if (errorMessage != null) {
throw new JsonIOException(errorMessage);
}
return configs;
} | public Configs getConfigs() {
Configs configs = null;
InputStream is = settingsFacade.getRawConfig(SMS_CONFIGS_FILE_NAME);
String errorMessage = null;
if (is == null) {
throw new JsonIOException(SMS_CONFIGS_FILE_NAME + " missing");
}
try {
String jsonText = IOUtils.toString(is);
Gson gson = new Gson();
configs = gson.fromJson(jsonText, Configs.class);
} catch (Exception e) {
errorMessage = "Might you have a malformed " + SMS_CONFIGS_FILE_NAME + " file? " + e.toString();
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore IO exception, what are we going to do anyway?
logger.error("IOException when closing config file {}: {}", SMS_CONFIGS_FILE_NAME, e);
}
}
if (errorMessage != null) {
throw new JsonIOException(errorMessage);
}
return configs;
} |
15,483 | 0 | // TODO: set working dir | private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> ctor = clazz.getDeclaredConstructors()[0];
ctor.setAccessible(true);
Object instance = ctor.newInstance();
Method method = null;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} | IMPLEMENTATION | true | private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> ctor = clazz.getDeclaredConstructors()[0];
ctor.setAccessible(true);
Object instance = ctor.newInstance();
Method method = null;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} | private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> ctor = clazz.getDeclaredConstructors()[0];
ctor.setAccessible(true);
Object instance = ctor.newInstance();
Method method = null;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} | private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> ctor = clazz.getDeclaredConstructors()[0];
ctor.setAccessible(true);
Object instance = ctor.newInstance();
Method method = null;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} |
15,483 | 1 | // we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs | private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> ctor = clazz.getDeclaredConstructors()[0];
ctor.setAccessible(true);
Object instance = ctor.newInstance();
Method method = null;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} | NONSATD | true | result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace()); | Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} | private static Object invokeAnnotation(Class<?> clazz, Object[] trees) throws InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor<?> ctor = clazz.getDeclaredConstructors()[0];
ctor.setAccessible(true);
Object instance = ctor.newInstance();
Method method = null;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method m : declaredMethods) {
if (m.getName().equals("apply")) method = m;
}
assert method != null: "Method 'apply' not found in annotation class";
method.setAccessible(true);
Object result;
try {
result = method.invoke(instance, trees);
} catch (InvocationTargetException e) {
// we can't even pass exceptions without re-wraping them since classes on the invoking side are incompatible
// also flatten to avoid getting nested ITEs
RuntimeException exception = new RuntimeException(e.getTargetException().toString());
exception.setStackTrace(e.getStackTrace());
throw exception;
}
return result;
} |
15,506 | 0 | //TODO pass anything.may be Object needed? | public boolean validateBinaryExpr(BinaryExpr node) {
ExprNode expr1 = node.getExpr1();
ExprNode expr2 = node.getExpr2();
Type t1 = expr1.getType();
Type t2 = expr2.getType();
String op = node.getOperation();
switch (op) {
case "==":
case "!=":
if (Types.isNumber(t1)) {
return this.requireNumber(expr2,t2);
} else {
return true;
//TODO pass anything.may be Object needed?
}
case "+":
case "-":
case "*":
case "/":
case "%":
case ">=":
case "<=":
case ">":
case "<":
case "&":
case "|":
case "^":
case BinaryExpr.OP_SHIFT_LEFT:
case BinaryExpr.OP_SHIFT_RIGHT:
case BinaryExpr.OP_UNSIGNED_SHIFT_RIGHT:
return this.requireNumber(expr1, t1) && this.requireNumber(expr2, t2);
case "&&":
case "||":
return requireBoolean(expr1, t1) && requireBoolean(expr2, t2);
default:
diagnosisReporter.report(Diagnosis.Kind.ERROR, "unsupported operation:" + op, node.offset);
return false;
}
} | IMPLEMENTATION | true | } else {
return true;
//TODO pass anything.may be Object needed?
}
case "+": | Type t1 = expr1.getType();
Type t2 = expr2.getType();
String op = node.getOperation();
switch (op) {
case "==":
case "!=":
if (Types.isNumber(t1)) {
return this.requireNumber(expr2,t2);
} else {
return true;
//TODO pass anything.may be Object needed?
}
case "+":
case "-":
case "*":
case "/":
case "%":
case ">=":
case "<=":
case ">":
case "<": | public boolean validateBinaryExpr(BinaryExpr node) {
ExprNode expr1 = node.getExpr1();
ExprNode expr2 = node.getExpr2();
Type t1 = expr1.getType();
Type t2 = expr2.getType();
String op = node.getOperation();
switch (op) {
case "==":
case "!=":
if (Types.isNumber(t1)) {
return this.requireNumber(expr2,t2);
} else {
return true;
//TODO pass anything.may be Object needed?
}
case "+":
case "-":
case "*":
case "/":
case "%":
case ">=":
case "<=":
case ">":
case "<":
case "&":
case "|":
case "^":
case BinaryExpr.OP_SHIFT_LEFT:
case BinaryExpr.OP_SHIFT_RIGHT:
case BinaryExpr.OP_UNSIGNED_SHIFT_RIGHT:
return this.requireNumber(expr1, t1) && this.requireNumber(expr2, t2);
case "&&":
case "||":
return requireBoolean(expr1, t1) && requireBoolean(expr2, t2); |
15,511 | 0 | // TLS layer | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} |
15,511 | 1 | // we don't need the plainSocket | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet. | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
} | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
} |
15,511 | 2 | // create and connect SSL socket, but don't do hostname/certificate verification yet. | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | // we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager); | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers... | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try { |
15,511 | 3 | // Protocols... | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) { | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0])); | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) { |
15,511 | 4 | // Ciphers... | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | }
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites())); | // create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try { | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); |
15,511 | 5 | // All all already enabled ones for compatibility. | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake. | final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
} | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} |
15,511 | 6 | // set up SNI before the handshake. | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host); | final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e)); | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} |
15,511 | 7 | // This hack seems to work on my 4.0.4 tablet. | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | DESIGN | true | sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class); | sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession(); | if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} |
15,511 | 8 | // verify hostname and certificate. | @Override
public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException {
// we don't need the plainSocket
if (autoClose) plainSocket.close();
// create and connect SSL socket, but don't do hostname/certificate verification yet.
final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
sslSocketFactory.setTrustManagers(this.trustManager);
final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
// Protocols...
final List<String> protocols = new ArrayList<String>();
for (final String protocol : sock.getSupportedProtocols()) {
if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol);
}
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | NONSATD | true | }
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); | }
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} | }
sock.setEnabledProtocols(protocols.toArray(new String[0]));
// Ciphers...
final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS);
ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites()));
ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility.
sock.setEnabledCipherSuites(ciphers.toArray(new String[0]));
// set up SNI before the handshake.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
sslSocketFactory.setHostname(sock, host);
}
else { // This hack seems to work on my 4.0.4 tablet.
try {
final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sock, host);
}
catch (final Exception e) {
LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e));
}
}
// verify hostname and certificate.
final SSLSession session = sock.getSession();
if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite());
return sock;
} |
23,703 | 0 | // TODO(T48080142): When we wrap up all of these validation errors into something human
// friendly, this will become a build file error | @Test
public void providerCannotBeUsedIfNotAssigned() throws IOException, InterruptedException {
setupWorkspace("user_defined_providers");
EventCollector collector = new EventCollector(EnumSet.allOf(EventKind.class));
parser = createParser(collector);
// TODO(T48080142): When we wrap up all of these validation errors into something human
// friendly, this will become a build file error
thrown.expect(Exception.class);
thrown.expectMessage("//not_assigned:defs.bzl referenced from //not_assigned:BUCK");
parser.getManifest(ForwardRelPath.of("not_assigned/BUCK"));
} | DEFECT | true | EventCollector collector = new EventCollector(EnumSet.allOf(EventKind.class));
parser = createParser(collector);
// TODO(T48080142): When we wrap up all of these validation errors into something human
// friendly, this will become a build file error
thrown.expect(Exception.class);
thrown.expectMessage("//not_assigned:defs.bzl referenced from //not_assigned:BUCK"); | @Test
public void providerCannotBeUsedIfNotAssigned() throws IOException, InterruptedException {
setupWorkspace("user_defined_providers");
EventCollector collector = new EventCollector(EnumSet.allOf(EventKind.class));
parser = createParser(collector);
// TODO(T48080142): When we wrap up all of these validation errors into something human
// friendly, this will become a build file error
thrown.expect(Exception.class);
thrown.expectMessage("//not_assigned:defs.bzl referenced from //not_assigned:BUCK");
parser.getManifest(ForwardRelPath.of("not_assigned/BUCK"));
} | @Test
public void providerCannotBeUsedIfNotAssigned() throws IOException, InterruptedException {
setupWorkspace("user_defined_providers");
EventCollector collector = new EventCollector(EnumSet.allOf(EventKind.class));
parser = createParser(collector);
// TODO(T48080142): When we wrap up all of these validation errors into something human
// friendly, this will become a build file error
thrown.expect(Exception.class);
thrown.expectMessage("//not_assigned:defs.bzl referenced from //not_assigned:BUCK");
parser.getManifest(ForwardRelPath.of("not_assigned/BUCK"));
} |
23,710 | 0 | /* TODO Consider moving elsewhere. */ | @Provides
@Singleton
Retrofit provideCall() {
Cache cache = null;
try {
cache = new Cache(cacheFile, 10 * 1024 * 1024);
} catch (Exception e) {
e.printStackTrace();
}
/* TODO Consider moving elsewhere. */
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("APPID", BuildConfig.API_OPENWEATHERMAP_KEY)
.build();
Request request = original.newBuilder()
.header("Content-Type", "application/json")
.removeHeader("Pragma")
.header("Cache-Control", String.format("max-age=%d", BuildConfig.CACHETIME))
.url(url)
.build();
okhttp3.Response response = chain.proceed(request);
response.cacheResponse();
return response;
}
})
.cache(cache)
.build();
return new Retrofit.Builder()
.baseUrl(BuildConfig.API_OPENWEATHERMAP_BASEURL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
} | IMPLEMENTATION | true | e.printStackTrace();
}
/* TODO Consider moving elsewhere. */
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() { | @Provides
@Singleton
Retrofit provideCall() {
Cache cache = null;
try {
cache = new Cache(cacheFile, 10 * 1024 * 1024);
} catch (Exception e) {
e.printStackTrace();
}
/* TODO Consider moving elsewhere. */
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("APPID", BuildConfig.API_OPENWEATHERMAP_KEY)
.build();
Request request = original.newBuilder() | @Provides
@Singleton
Retrofit provideCall() {
Cache cache = null;
try {
cache = new Cache(cacheFile, 10 * 1024 * 1024);
} catch (Exception e) {
e.printStackTrace();
}
/* TODO Consider moving elsewhere. */
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl originalHttpUrl = original.url();
HttpUrl url = originalHttpUrl.newBuilder()
.addQueryParameter("APPID", BuildConfig.API_OPENWEATHERMAP_KEY)
.build();
Request request = original.newBuilder()
.header("Content-Type", "application/json")
.removeHeader("Pragma")
.header("Cache-Control", String.format("max-age=%d", BuildConfig.CACHETIME))
.url(url)
.build();
okhttp3.Response response = chain.proceed(request);
response.cacheResponse();
return response;
}
}) |