vul_code,patch,is_vulnerable,file_name
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
",FALSE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char[] c = t.consumeCharacterReference(null, false);
if (c == null)
t.emit('&');
else
t.emit(c);
t.transition(Data);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInRcdata);
break;
case '<':
t.advanceTransition(RcdataLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('&', '<', nullChar);
t.emit(data);
break;
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char[] c = t.consumeCharacterReference(null, false);
if (c == null)
t.emit('&');
else
t.emit(c);
t.transition(Rcdata);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '<':
t.advanceTransition(RawtextLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('<', nullChar);
t.emit(data);
break;
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '<':
t.advanceTransition(ScriptDataLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeToAny('<', nullChar);
t.emit(data);
break;
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeTo(nullChar);
t.emit(data);
break;
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '!':
t.advanceTransition(MarkupDeclarationOpen);
break;
case '/':
t.advanceTransition(EndTagOpen);
break;
case '?':
t.advanceTransition(BogusComment);
break;
default:
if (r.matchesLetter()) {
t.createTagPending(true);
t.transition(TagName);
} else {
t.error(this);
t.emit('<'); // char that got us here
t.transition(Data);
}
break;
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.emit("""");
t.transition(Data);
} else if (r.matchesLetter()) {
t.createTagPending(false);
t.transition(TagName);
} else if (r.matches('>')) {
t.error(this);
t.advanceTransition(Data);
} else {
t.error(this);
t.advanceTransition(BogusComment);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
// previous TagOpen state did NOT consume, will have a letter char in current
//String tagName = r.consumeToAnySorted(tagCharsSorted).toLowerCase();
String tagName = r.consumeTagName().toLowerCase();
t.tagPending.appendTagName(tagName);
switch (r.consume()) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar: // replacement
t.tagPending.appendTagName(replacementStr);
break;
case eof: // should emit pending tag?
t.eofError(this);
t.transition(Data);
// no default, as covered with above consumeToAny
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(RCDATAEndTagOpen);
} else if (r.matchesLetter() && t.appropriateEndTagName() != null && !r.containsIgnoreCase("""" + t.appropriateEndTagName())) {
// diverge from spec: got a start tag, but there's no appropriate end tag (), so rather than
// consuming to EOF; break out here
t.tagPending = t.createTagPending(false).name(t.appropriateEndTagName());
t.emitTagPending();
r.unconsume(); // undo ""<""
t.transition(Data);
} else {
t.emit(""<"");
t.transition(Rcdata);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.tagPending.appendTagName(Character.toLowerCase(r.current()));
t.dataBuffer.append(Character.toLowerCase(r.current()));
t.advanceTransition(RCDATAEndTagName);
} else {
t.emit("""");
t.transition(Rcdata);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
if (t.isAppropriateEndTagToken())
t.transition(BeforeAttributeName);
else
anythingElse(t, r);
break;
case '/':
if (t.isAppropriateEndTagToken())
t.transition(SelfClosingStartTag);
else
anythingElse(t, r);
break;
case '>':
if (t.isAppropriateEndTagToken()) {
t.emitTagPending();
t.transition(Data);
}
else
anythingElse(t, r);
break;
default:
anythingElse(t, r);
}
}
",TRUE,TokeniserState.java
" private void anythingElse(Tokeniser t, CharacterReader r) {
t.emit("""" + t.dataBuffer.toString());
r.unconsume();
t.transition(Rcdata);
}
"," private void anythingElse(Tokeniser t, CharacterReader r) {
t.emit("""" + t.dataBuffer.toString());
r.unconsume();
t.transition(Rcdata);
}
",FALSE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(RawtextEndTagOpen);
} else {
t.emit('<');
t.transition(Rawtext);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.transition(RawtextEndTagName);
} else {
t.emit("""");
t.transition(Rawtext);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, Rawtext);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
switch (r.consume()) {
case '/':
t.createTempBuffer();
t.transition(ScriptDataEndTagOpen);
break;
case '!':
t.emit(""':
t.emit(c);
t.transition(ScriptData);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataEscaped);
break;
default:
t.emit(c);
t.transition(ScriptDataEscaped);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTempBuffer();
t.dataBuffer.append(Character.toLowerCase(r.current()));
t.emit(""<"" + r.current());
t.advanceTransition(ScriptDataDoubleEscapeStart);
} else if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(ScriptDataEscapedEndTagOpen);
} else {
t.emit('<');
t.transition(ScriptDataEscaped);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createTagPending(false);
t.tagPending.appendTagName(Character.toLowerCase(r.current()));
t.dataBuffer.append(r.current());
t.advanceTransition(ScriptDataEscapedEndTagName);
} else {
t.emit("""");
t.transition(ScriptDataEscaped);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, ScriptDataEscaped);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
handleDataDoubleEscapeTag(t, r, ScriptDataDoubleEscaped, ScriptDataEscaped);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.current();
switch (c) {
case '-':
t.emit(c);
t.advanceTransition(ScriptDataDoubleEscapedDash);
break;
case '<':
t.emit(c);
t.advanceTransition(ScriptDataDoubleEscapedLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
String data = r.consumeToAny('-', '<', nullChar);
t.emit(data);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
t.transition(ScriptDataDoubleEscapedDashDash);
break;
case '<':
t.emit(c);
t.transition(ScriptDataDoubleEscapedLessthanSign);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataDoubleEscaped);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.emit(c);
t.transition(ScriptDataDoubleEscaped);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
break;
case '<':
t.emit(c);
t.transition(ScriptDataDoubleEscapedLessthanSign);
break;
case '>':
t.emit(c);
t.transition(ScriptData);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataDoubleEscaped);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.emit(c);
t.transition(ScriptDataDoubleEscaped);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.emit('/');
t.createTempBuffer();
t.advanceTransition(ScriptDataDoubleEscapeEnd);
} else {
t.transition(ScriptDataDoubleEscaped);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
handleDataDoubleEscapeTag(t,r, ScriptDataEscaped, ScriptDataDoubleEscaped);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break; // ignore whitespace
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '""':
case '\'':
case '<':
case '=':
t.error(this);
t.tagPending.newAttribute();
t.tagPending.appendAttributeName(c);
t.transition(AttributeName);
break;
default: // A-Z, anything else
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
String name = r.consumeToAnySorted(attributeNameCharsSorted);
t.tagPending.appendAttributeName(name.toLowerCase());
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(AfterAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '=':
t.transition(BeforeAttributeValue);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeName(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '""':
case '\'':
case '<':
t.error(this);
t.tagPending.appendAttributeName(c);
// no default, as covered in consumeToAny
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
// ignore
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '=':
t.transition(BeforeAttributeValue);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeName(replacementChar);
t.transition(AttributeName);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '""':
case '\'':
case '<':
t.error(this);
t.tagPending.newAttribute();
t.tagPending.appendAttributeName(c);
t.transition(AttributeName);
break;
default: // A-Z, anything else
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
// ignore
break;
case '""':
t.transition(AttributeValue_doubleQuoted);
break;
case '&':
r.unconsume();
t.transition(AttributeValue_unquoted);
break;
case '\'':
t.transition(AttributeValue_singleQuoted);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
t.transition(AttributeValue_unquoted);
break;
case eof:
t.eofError(this);
t.emitTagPending();
t.transition(Data);
break;
case '>':
t.error(this);
t.emitTagPending();
t.transition(Data);
break;
case '<':
case '=':
case '`':
t.error(this);
t.tagPending.appendAttributeValue(c);
t.transition(AttributeValue_unquoted);
break;
default:
r.unconsume();
t.transition(AttributeValue_unquoted);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
String value = r.consumeToAnySorted(attributeDoubleValueCharsSorted);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '""':
t.transition(AfterAttributeValue_quoted);
break;
case '&':
char[] ref = t.consumeCharacterReference('""', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
// no default, handled in consume to any above
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
String value = r.consumeToAnySorted(attributeSingleValueCharsSorted);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterAttributeValue_quoted);
break;
case '&':
char[] ref = t.consumeCharacterReference('\'', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
// no default, handled in consume to any above
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
String value = r.consumeToAny('\t', '\n', '\r', '\f', ' ', '&', '>', nullChar, '""', '\'', '<', '=', '`');
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '&':
char[] ref = t.consumeCharacterReference('>', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '""':
case '\'':
case '<':
case '=':
case '`':
t.error(this);
t.tagPending.appendAttributeValue(c);
break;
// no default, handled in consume to any above
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.error(this);
r.unconsume();
t.transition(BeforeAttributeName);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.tagPending.selfClosing = true;
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.error(this);
t.transition(BeforeAttributeName);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
// todo: handle bogus comment starting from eof. when does that trigger?
// rewind to capture character that lead us here
r.unconsume();
Token.Comment comment = new Token.Comment();
comment.bogus = true;
comment.data.append(r.consumeTo('>'));
// todo: replace nullChar with replaceChar
t.emit(comment);
t.advanceTransition(Data);
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchConsume(""--"")) {
t.createCommentPending();
t.transition(CommentStart);
} else if (r.matchConsumeIgnoreCase(""DOCTYPE"")) {
t.transition(Doctype);
} else if (r.matchConsume(""[CDATA["")) {
// todo: should actually check current namepspace, and only non-html allows cdata. until namespace
// is implemented properly, keep handling as cdata
//} else if (!t.currentNodeInHtmlNS() && r.matchConsume(""[CDATA["")) {
t.transition(CdataSection);
} else {
t.error(this);
t.advanceTransition(BogusComment); // advance so this character gets in bogus comment data's rewind
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentStartDash);
break;
case nullChar:
t.error(this);
t.commentPending.data.append(replacementChar);
t.transition(Comment);
break;
case '>':
t.error(this);
t.emitCommentPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(c);
t.transition(Comment);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentStartDash);
break;
case nullChar:
t.error(this);
t.commentPending.data.append(replacementChar);
t.transition(Comment);
break;
case '>':
t.error(this);
t.emitCommentPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(c);
t.transition(Comment);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.current();
switch (c) {
case '-':
t.advanceTransition(CommentEndDash);
break;
case nullChar:
t.error(this);
r.advance();
t.commentPending.data.append(replacementChar);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(r.consumeToAny('-', nullChar));
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentEnd);
break;
case nullChar:
t.error(this);
t.commentPending.data.append('-').append(replacementChar);
t.transition(Comment);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append('-').append(c);
t.transition(Comment);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.emitCommentPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.commentPending.data.append(""--"").append(replacementChar);
t.transition(Comment);
break;
case '!':
t.error(this);
t.transition(CommentEndBang);
break;
case '-':
t.error(this);
t.commentPending.data.append('-');
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.error(this);
t.commentPending.data.append(""--"").append(c);
t.transition(Comment);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.commentPending.data.append(""--!"");
t.transition(CommentEndDash);
break;
case '>':
t.emitCommentPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.commentPending.data.append(""--!"").append(replacementChar);
t.transition(Comment);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.data.append(""--!"").append(c);
t.transition(Comment);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypeName);
break;
case eof:
t.eofError(this);
// note: fall through to > case
case '>': // catch invalid
t.error(this);
t.createDoctypePending();
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.transition(BeforeDoctypeName);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
t.createDoctypePending();
t.transition(DoctypeName);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break; // ignore whitespace
case nullChar:
t.error(this);
t.createDoctypePending();
t.doctypePending.name.append(replacementChar);
t.transition(DoctypeName);
break;
case eof:
t.eofError(this);
t.createDoctypePending();
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.createDoctypePending();
t.doctypePending.name.append(c);
t.transition(DoctypeName);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.doctypePending.name.append(name.toLowerCase());
return;
}
char c = r.consume();
switch (c) {
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(AfterDoctypeName);
break;
case nullChar:
t.error(this);
t.doctypePending.name.append(replacementChar);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.name.append(c);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
return;
}
if (r.matchesAny('\t', '\n', '\r', '\f', ' '))
r.advance(); // ignore whitespace
else if (r.matches('>')) {
t.emitDoctypePending();
t.advanceTransition(Data);
} else if (r.matchConsumeIgnoreCase(""PUBLIC"")) {
t.transition(AfterDoctypePublicKeyword);
} else if (r.matchConsumeIgnoreCase(""SYSTEM"")) {
t.transition(AfterDoctypeSystemKeyword);
} else {
t.error(this);
t.doctypePending.forceQuirks = true;
t.advanceTransition(BogusDoctype);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypePublicIdentifier);
break;
case '""':
t.error(this);
// set public id to empty string
t.transition(DoctypePublicIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// set public id to empty string
t.transition(DoctypePublicIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '""':
// set public id to empty string
t.transition(DoctypePublicIdentifier_doubleQuoted);
break;
case '\'':
// set public id to empty string
t.transition(DoctypePublicIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '""':
t.transition(AfterDoctypePublicIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.publicIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.publicIdentifier.append(c);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterDoctypePublicIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.publicIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.publicIdentifier.append(c);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BetweenDoctypePublicAndSystemIdentifiers);
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '""':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '""':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypeSystemIdentifier);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case '""':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '""':
// set system id to empty string
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
// set public id to empty string
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '""':
t.transition(AfterDoctypeSystemIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.systemIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.systemIdentifier.append(c);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterDoctypeSystemIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.systemIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.systemIdentifier.append(c);
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.transition(BogusDoctype);
// NOT force quirks
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.emitDoctypePending();
t.transition(Data);
break;
default:
// ignore char
break;
}
}
",TRUE,TokeniserState.java
" void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
"," void read(Tokeniser t, CharacterReader r) {
String data = r.consumeTo(""]]>"");
t.emit(data);
r.matchConsume(""]]>"");
t.transition(Data);
}
",TRUE,TokeniserState.java
" private static void handleDataEndTag(Tokeniser t, CharacterReader r, TokeniserState elseTransition) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
boolean needsExitTransition = false;
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
needsExitTransition = true;
}
} else {
needsExitTransition = true;
}
if (needsExitTransition) {
t.emit("""" + t.dataBuffer.toString());
t.transition(elseTransition);
}
}
"," private static void handleDataEndTag(Tokeniser t, CharacterReader r, TokeniserState elseTransition) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
boolean needsExitTransition = false;
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
needsExitTransition = true;
}
} else {
needsExitTransition = true;
}
if (needsExitTransition) {
t.emit("""" + t.dataBuffer.toString());
t.transition(elseTransition);
}
}
",FALSE,TokeniserState.java
" private static void handleDataDoubleEscapeTag(Tokeniser t, CharacterReader r, TokeniserState primary, TokeniserState fallback) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.dataBuffer.append(name.toLowerCase());
t.emit(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
case '/':
case '>':
if (t.dataBuffer.toString().equals(""script""))
t.transition(primary);
else
t.transition(fallback);
t.emit(c);
break;
default:
r.unconsume();
t.transition(fallback);
}
}
"," private static void handleDataDoubleEscapeTag(Tokeniser t, CharacterReader r, TokeniserState primary, TokeniserState fallback) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.dataBuffer.append(name.toLowerCase());
t.emit(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
case '/':
case '>':
if (t.dataBuffer.toString().equals(""script""))
t.transition(primary);
else
t.transition(fallback);
t.emit(c);
break;
default:
r.unconsume();
t.transition(fallback);
}
}
",FALSE,TokeniserState.java
" public void testSimpleXmlParse() {
String xml = ""Foo One Two "";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, ""http://foo.com/"");
assertEquals(""Foo One Two "",
TextUtil.stripNewlines(doc.html()));
assertEquals(doc.getElementById(""2"").absUrl(""href""), ""http://foo.com/bar"");
}
"," public void testSimpleXmlParse() {
String xml = ""Foo One Two "";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, ""http://foo.com/"");
assertEquals(""Foo One Two "",
TextUtil.stripNewlines(doc.html()));
assertEquals(doc.getElementById(""2"").absUrl(""href""), ""http://foo.com/bar"");
}
",FALSE,XmlTreeBuilderTest.java
" public void testPopToClose() {
// test: closes Two, ignored
String xml = ""OneTwo Three "";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, ""http://foo.com/"");
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(doc.html()));
}
"," public void testPopToClose() {
// test: closes Two, ignored
String xml = ""OneTwo Three "";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, ""http://foo.com/"");
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(doc.html()));
}
",FALSE,XmlTreeBuilderTest.java
" public void testCommentAndDocType() {
String xml = ""One Two"";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, ""http://foo.com/"");
assertEquals(""One Two"",
TextUtil.stripNewlines(doc.html()));
}
"," public void testCommentAndDocType() {
String xml = ""One Two"";
XmlTreeBuilder tb = new XmlTreeBuilder();
Document doc = tb.parse(xml, ""http://foo.com/"");
assertEquals(""One Two"",
TextUtil.stripNewlines(doc.html()));
}
",FALSE,XmlTreeBuilderTest.java
" public void testSupplyParserToJsoupClass() {
String xml = ""OneTwo Three "";
Document doc = Jsoup.parse(xml, ""http://foo.com/"", Parser.xmlParser());
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(doc.html()));
}
"," public void testSupplyParserToJsoupClass() {
String xml = ""OneTwo Three "";
Document doc = Jsoup.parse(xml, ""http://foo.com/"", Parser.xmlParser());
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(doc.html()));
}
",FALSE,XmlTreeBuilderTest.java
" public void testSupplyParserToConnection() throws IOException {
String xmlUrl = ""http://direct.infohound.net/tools/jsoup-xml-test.xml"";
// parse with both xml and html parser, ensure different
Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get();
Document htmlDoc = Jsoup.connect(xmlUrl).get();
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(xmlDoc.html()));
assertNotSame(htmlDoc, xmlDoc);
assertEquals(1, htmlDoc.select(""head"").size()); // html parser normalises
assertEquals(0, xmlDoc.select(""head"").size()); // xml parser does not
}
"," public void testSupplyParserToConnection() throws IOException {
String xmlUrl = ""http://direct.infohound.net/tools/jsoup-xml-test.xml"";
// parse with both xml and html parser, ensure different
Document xmlDoc = Jsoup.connect(xmlUrl).parser(Parser.xmlParser()).get();
Document htmlDoc = Jsoup.connect(xmlUrl).get();
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(xmlDoc.html()));
assertNotSame(htmlDoc, xmlDoc);
assertEquals(1, htmlDoc.select(""head"").size()); // html parser normalises
assertEquals(0, xmlDoc.select(""head"").size()); // xml parser does not
}
",FALSE,XmlTreeBuilderTest.java
" public void testSupplyParserToDataStream() throws IOException, URISyntaxException {
File xmlFile = new File(XmlTreeBuilder.class.getResource(""/htmltests/xml-test.xml"").toURI());
InputStream inStream = new FileInputStream(xmlFile);
Document doc = Jsoup.parse(inStream, null, ""http://foo.com"", Parser.xmlParser());
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(doc.html()));
}
"," public void testSupplyParserToDataStream() throws IOException, URISyntaxException {
File xmlFile = new File(XmlTreeBuilder.class.getResource(""/htmltests/xml-test.xml"").toURI());
InputStream inStream = new FileInputStream(xmlFile);
Document doc = Jsoup.parse(inStream, null, ""http://foo.com"", Parser.xmlParser());
assertEquals(""OneTwo Three "",
TextUtil.stripNewlines(doc.html()));
}
",FALSE,XmlTreeBuilderTest.java
" public void testDoesNotForceSelfClosingKnownTags() {
// html will force "" one"" to logically "" One "". XML should be stay "" one -- don't recognise tag.
Document htmlDoc = Jsoup.parse("" one"");
assertEquals("" one\n "", htmlDoc.body().html());
Document xmlDoc = Jsoup.parse("" one"", """", Parser.xmlParser());
assertEquals("" one"", xmlDoc.html());
}
"," public void testDoesNotForceSelfClosingKnownTags() {
// html will force "" one"" to logically "" One "". XML should be stay "" one -- don't recognise tag.
Document htmlDoc = Jsoup.parse("" one"");
assertEquals("" one\n "", htmlDoc.body().html());
Document xmlDoc = Jsoup.parse("" one"", """", Parser.xmlParser());
assertEquals("" one"", xmlDoc.html());
}
",FALSE,XmlTreeBuilderTest.java
" @Test public void handlesXmlDeclarationAsDeclaration() {
String html = ""
One"";
Document doc = Jsoup.parse(html, """", Parser.xmlParser());
assertEquals("" One "",
StringUtil.normaliseWhitespace(doc.outerHtml()));
assertEquals(""#declaration"", doc.childNode(0).nodeName());
assertEquals(""#comment"", doc.childNode(2).nodeName());
}
"," @Test public void handlesXmlDeclarationAsDeclaration() {
String html = ""One"";
Document doc = Jsoup.parse(html, """", Parser.xmlParser());
assertEquals("" One "",
StringUtil.normaliseWhitespace(doc.outerHtml()));
assertEquals(""#declaration"", doc.childNode(0).nodeName());
assertEquals(""#comment"", doc.childNode(2).nodeName());
}
",FALSE,XmlTreeBuilderTest.java
" @Test public void xmlFragment() {
String xml = "" Two "";
List nodes = Parser.parseXmlFragment(xml, ""http://example.com/"");
assertEquals(3, nodes.size());
assertEquals(""http://example.com/foo/"", nodes.get(0).absUrl(""src""));
assertEquals(""one"", nodes.get(0).nodeName());
assertEquals(""Two"", ((TextNode)nodes.get(1)).text());
}
"," @Test public void xmlFragment() {
String xml = "" Two "";
List nodes = Parser.parseXmlFragment(xml, ""http://example.com/"");
assertEquals(3, nodes.size());
assertEquals(""http://example.com/foo/"", nodes.get(0).absUrl(""src""));
assertEquals(""one"", nodes.get(0).nodeName());
assertEquals(""Two"", ((TextNode)nodes.get(1)).text());
}
",FALSE,XmlTreeBuilderTest.java
" @Test public void xmlParseDefaultsToHtmlOutputSyntax() {
Document doc = Jsoup.parse(""x"", """", Parser.xmlParser());
assertEquals(Syntax.xml, doc.outputSettings().syntax());
}
"," @Test public void xmlParseDefaultsToHtmlOutputSyntax() {
Document doc = Jsoup.parse(""x"", """", Parser.xmlParser());
assertEquals(Syntax.xml, doc.outputSettings().syntax());
}
",FALSE,XmlTreeBuilderTest.java
" }
"," public void testDoesHandleEOFInTag() {
String html = "" "", xmlDoc.html());
}
",TRUE,XmlTreeBuilderTest.java
" public ObjectArrayCodec(){
}
"," public ObjectArrayCodec(){
}
",FALSE,ObjectArrayCodec.java
" public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
throws IOException {
SerializeWriter out = serializer.out;
Object[] array = (Object[]) object;
if (object == null) {
out.writeNull(SerializerFeature.WriteNullListAsEmpty);
return;
}
int size = array.length;
int end = size - 1;
if (end == -1) {
out.append(""[]"");
return;
}
SerialContext context = serializer.context;
serializer.setContext(context, object, fieldName, 0);
try {
Class> preClazz = null;
ObjectSerializer preWriter = null;
out.append('[');
if (out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.incrementIndent();
serializer.println();
for (int i = 0; i < size; ++i) {
if (i != 0) {
out.write(',');
serializer.println();
}
serializer.write(array[i]);
}
serializer.decrementIdent();
serializer.println();
out.write(']');
return;
}
for (int i = 0; i < end; ++i) {
Object item = array[i];
if (item == null) {
out.append(""null,"");
} else {
if (serializer.containsReference(item)) {
serializer.writeReference(item);
} else {
Class> clazz = item.getClass();
if (clazz == preClazz) {
preWriter.write(serializer, item, null, null, 0);
} else {
preClazz = clazz;
preWriter = serializer.getObjectWriter(clazz);
preWriter.write(serializer, item, null, null, 0);
}
}
out.append(',');
}
}
Object item = array[end];
if (item == null) {
out.append(""null]"");
} else {
if (serializer.containsReference(item)) {
serializer.writeReference(item);
} else {
serializer.writeWithFieldName(item, end);
}
out.append(']');
}
} finally {
serializer.context = context;
}
}
"," public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
throws IOException {
SerializeWriter out = serializer.out;
Object[] array = (Object[]) object;
if (object == null) {
out.writeNull(SerializerFeature.WriteNullListAsEmpty);
return;
}
int size = array.length;
int end = size - 1;
if (end == -1) {
out.append(""[]"");
return;
}
SerialContext context = serializer.context;
serializer.setContext(context, object, fieldName, 0);
try {
Class> preClazz = null;
ObjectSerializer preWriter = null;
out.append('[');
if (out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.incrementIndent();
serializer.println();
for (int i = 0; i < size; ++i) {
if (i != 0) {
out.write(',');
serializer.println();
}
serializer.write(array[i]);
}
serializer.decrementIdent();
serializer.println();
out.write(']');
return;
}
for (int i = 0; i < end; ++i) {
Object item = array[i];
if (item == null) {
out.append(""null,"");
} else {
if (serializer.containsReference(item)) {
serializer.writeReference(item);
} else {
Class> clazz = item.getClass();
if (clazz == preClazz) {
preWriter.write(serializer, item, null, null, 0);
} else {
preClazz = clazz;
preWriter = serializer.getObjectWriter(clazz);
preWriter.write(serializer, item, null, null, 0);
}
}
out.append(',');
}
}
Object item = array[end];
if (item == null) {
out.append(""null]"");
} else {
if (serializer.containsReference(item)) {
serializer.writeReference(item);
} else {
serializer.writeWithFieldName(item, end);
}
out.append(']');
}
} finally {
serializer.context = context;
}
}
",FALSE,ObjectArrayCodec.java
" public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
final JSONLexer lexer = parser.lexer;
if (lexer.token() == JSONToken.NULL) {
lexer.nextToken(JSONToken.COMMA);
return null;
}
if (lexer.token() == JSONToken.LITERAL_STRING) {
byte[] bytes = lexer.bytesValue();
lexer.nextToken(JSONToken.COMMA);
return (T) bytes;
}
Class componentClass;
Type componentType;
if (type instanceof GenericArrayType) {
GenericArrayType clazz = (GenericArrayType) type;
componentType = clazz.getGenericComponentType();
if (componentType instanceof TypeVariable) {
TypeVariable typeVar = (TypeVariable) componentType;
Type objType = parser.getContext().type;
if (objType instanceof ParameterizedType) {
ParameterizedType objParamType = (ParameterizedType) objType;
Type objRawType = objParamType.getRawType();
Type actualType = null;
if (objRawType instanceof Class) {
TypeVariable[] objTypeParams = ((Class) objRawType).getTypeParameters();
for (int i = 0; i < objTypeParams.length; ++i) {
if (objTypeParams[i].getName().equals(typeVar.getName())) {
actualType = objParamType.getActualTypeArguments()[i];
}
}
}
if (actualType instanceof Class) {
componentClass = (Class) actualType;
} else {
componentClass = Object.class;
}
} else {
componentClass = TypeUtils.getClass(typeVar.getBounds()[0]);
}
} else {
componentClass = TypeUtils.getClass(componentType);
}
} else {
Class clazz = (Class) type;
componentType = componentClass = clazz.getComponentType();
}
JSONArray array = new JSONArray();
parser.parseArray(componentClass, array, fieldName);
return (T) toObjectArray(parser, componentClass, array);
}
"," public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
final JSONLexer lexer = parser.lexer;
if (lexer.token() == JSONToken.NULL) {
lexer.nextToken(JSONToken.COMMA);
return null;
}
if (lexer.token() == JSONToken.LITERAL_STRING) {
byte[] bytes = lexer.bytesValue();
lexer.nextToken(JSONToken.COMMA);
return (T) bytes;
}
Class componentClass;
Type componentType;
if (type instanceof GenericArrayType) {
GenericArrayType clazz = (GenericArrayType) type;
componentType = clazz.getGenericComponentType();
if (componentType instanceof TypeVariable) {
TypeVariable typeVar = (TypeVariable) componentType;
Type objType = parser.getContext().type;
if (objType instanceof ParameterizedType) {
ParameterizedType objParamType = (ParameterizedType) objType;
Type objRawType = objParamType.getRawType();
Type actualType = null;
if (objRawType instanceof Class) {
TypeVariable[] objTypeParams = ((Class) objRawType).getTypeParameters();
for (int i = 0; i < objTypeParams.length; ++i) {
if (objTypeParams[i].getName().equals(typeVar.getName())) {
actualType = objParamType.getActualTypeArguments()[i];
}
}
}
if (actualType instanceof Class) {
componentClass = (Class) actualType;
} else {
componentClass = Object.class;
}
} else {
componentClass = TypeUtils.getClass(typeVar.getBounds()[0]);
}
} else {
componentClass = TypeUtils.getClass(componentType);
}
} else {
Class clazz = (Class) type;
componentType = componentClass = clazz.getComponentType();
}
JSONArray array = new JSONArray();
parser.parseArray(componentType, array, fieldName);
return (T) toObjectArray(parser, componentClass, array);
}
",TRUE,ObjectArrayCodec.java
" private T toObjectArray(DefaultJSONParser parser, Class> componentType, JSONArray array) {
if (array == null) {
return null;
}
int size = array.size();
Object objArray = Array.newInstance(componentType, size);
for (int i = 0; i < size; ++i) {
Object value = array.get(i);
if (value == array) {
Array.set(objArray, i, objArray);
continue;
}
if (componentType.isArray()) {
Object element;
if (componentType.isInstance(value)) {
element = value;
} else {
element = toObjectArray(parser, componentType, (JSONArray) value);
}
Array.set(objArray, i, element);
} else {
Object element = null;
if (value instanceof JSONArray) {
boolean contains = false;
JSONArray valueArray = (JSONArray) value;
int valueArraySize = valueArray.size();
for (int y = 0; y < valueArraySize; ++y) {
Object valueItem = valueArray.get(y);
if (valueItem == array) {
valueArray.set(i, objArray);
contains = true;
}
}
if (contains) {
element = valueArray.toArray();
}
}
if (element == null) {
element = TypeUtils.cast(value, componentType, parser.getConfig());
}
Array.set(objArray, i, element);
}
}
array.setRelatedArray(objArray);
array.setComponentType(componentType);
return (T) objArray; // TODO
}
"," private T toObjectArray(DefaultJSONParser parser, Class> componentType, JSONArray array) {
if (array == null) {
return null;
}
int size = array.size();
Object objArray = Array.newInstance(componentType, size);
for (int i = 0; i < size; ++i) {
Object value = array.get(i);
if (value == array) {
Array.set(objArray, i, objArray);
continue;
}
if (componentType.isArray()) {
Object element;
if (componentType.isInstance(value)) {
element = value;
} else {
element = toObjectArray(parser, componentType, (JSONArray) value);
}
Array.set(objArray, i, element);
} else {
Object element = null;
if (value instanceof JSONArray) {
boolean contains = false;
JSONArray valueArray = (JSONArray) value;
int valueArraySize = valueArray.size();
for (int y = 0; y < valueArraySize; ++y) {
Object valueItem = valueArray.get(y);
if (valueItem == array) {
valueArray.set(i, objArray);
contains = true;
}
}
if (contains) {
element = valueArray.toArray();
}
}
if (element == null) {
element = TypeUtils.cast(value, componentType, parser.getConfig());
}
Array.set(objArray, i, element);
}
}
array.setRelatedArray(objArray);
array.setComponentType(componentType);
return (T) objArray; // TODO
}
",FALSE,ObjectArrayCodec.java
" public int getFastMatchToken() {
return JSONToken.LBRACKET;
}
"," public int getFastMatchToken() {
return JSONToken.LBRACKET;
}
",FALSE,ObjectArrayCodec.java
" public void test_for_issue() throws Exception {
Model model = JSON.parseObject(""{\""values\"":[1,2,3]}"", Model.class);
assertNotNull(model.values);
assertEquals(3, model.values.size());
assertEquals(Byte.class, model.values.get(0).getClass());
assertEquals(Byte.class, model.values.get(1).getClass());
assertEquals(Byte.class, model.values.get(2).getClass());
}
"," public void test_for_issue() throws Exception {
Model model = JSON.parseObject(""{\""values\"":[[1,2,3]]}"", Model.class);
assertNotNull(model.values);
assertEquals(3, model.values[0].size());
assertEquals(Byte.class, model.values[0].get(0).getClass());
assertEquals(Byte.class, model.values[0].get(1).getClass());
assertEquals(Byte.class, model.values[0].get(2).getClass());
}
",TRUE,Issue1005.java
" }
"," public void test_for_List() throws Exception {
Model2 model = JSON.parseObject(""{\""values\"":[1,2,3]}"", Model2.class);
assertNotNull(model.values);
assertEquals(3, model.values.size());
assertEquals(Byte.class, model.values.get(0).getClass());
assertEquals(Byte.class, model.values.get(1).getClass());
assertEquals(Byte.class, model.values.get(2).getClass());
}
",TRUE,Issue1005.java
" public static JWTDecoder getInstance() {
if (instance == null) {
instance = new JWTDecoder();
}
return instance;
}
"," public static JWTDecoder getInstance() {
if (instance == null) {
instance = new JWTDecoder();
}
return instance;
}
",FALSE,JWTDecoder.java
" public JWT decode(String encodedJWT, Verifier... verifiers) {
Objects.requireNonNull(encodedJWT);
Objects.requireNonNull(verifiers);
// An unsecured JWT will not contain a signature and should only have a header and a payload.
String[] parts = getParts(encodedJWT);
Header header = Mapper.deserialize(base64Decode(parts[0].getBytes(StandardCharsets.UTF_8)), Header.class);
// If parts.length == 2 we have no signature, if no verifiers were provided, decode if header says 'none', else throw an exception
if (parts.length == 2 && verifiers.length == 0) {
if (header.algorithm == Algorithm.none) {
return Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class);
} else {
throw new InvalidJWTSignatureException();
}
}
// If verifiers were provided, ensure it is able to verify this JWT.
Verifier verifier = null;
for (Verifier v : verifiers) {
if (v.canVerify(header.algorithm)) {
verifier = v;
}
}
return decode(encodedJWT, header, parts, verifier);
}
"," public JWT decode(String encodedJWT, Verifier... verifiers) {
Objects.requireNonNull(encodedJWT);
Objects.requireNonNull(verifiers);
// An unsecured JWT will not contain a signature and should only have a header and a payload.
String[] parts = getParts(encodedJWT);
Header header = Mapper.deserialize(base64Decode(parts[0].getBytes(StandardCharsets.UTF_8)), Header.class);
// If parts.length == 2 we have no signature, if no verifiers were provided, decode if header says 'none', else throw an exception
if (parts.length == 2 && verifiers.length == 0) {
if (header.algorithm == Algorithm.none) {
return Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class);
} else {
throw new InvalidJWTSignatureException();
}
}
// If verifiers were provided, ensure it is able to verify this JWT.
Verifier verifier = null;
for (Verifier v : verifiers) {
if (v.canVerify(header.algorithm)) {
verifier = v;
}
}
return decode(encodedJWT, header, parts, verifier);
}
",FALSE,JWTDecoder.java
" public JWT decode(String encodedJWT, Map verifiers) {
return decode(encodedJWT, verifiers, h -> h.get(""kid""));
}
"," public JWT decode(String encodedJWT, Map verifiers) {
return decode(encodedJWT, verifiers, h -> h.get(""kid""));
}
",FALSE,JWTDecoder.java
" public JWT decode(String encodedJWT, Map verifiers, Function keyFunction) {
Objects.requireNonNull(encodedJWT);
Objects.requireNonNull(verifiers);
Objects.requireNonNull(keyFunction);
String[] parts = getParts(encodedJWT);
Header header = Mapper.deserialize(base64Decode(parts[0].getBytes(StandardCharsets.UTF_8)), Header.class);
// If parts.length == 2 we have no signature, if no verifiers were provided, decode if header says 'none', else throw an exception
if (parts.length == 2 && verifiers.isEmpty()) {
if (header.algorithm == Algorithm.none) {
return Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class);
} else {
throw new InvalidJWTSignatureException();
}
}
// If verifiers were provided, ensure it is able to verify this JWT.
String key = keyFunction.apply(header);
Verifier verifier = verifiers.get(key);
if (verifier != null) {
if (!verifier.canVerify(header.algorithm)) {
verifier = null;
}
}
return decode(encodedJWT, header, parts, verifier);
}
"," public JWT decode(String encodedJWT, Map verifiers, Function keyFunction) {
Objects.requireNonNull(encodedJWT);
Objects.requireNonNull(verifiers);
Objects.requireNonNull(keyFunction);
String[] parts = getParts(encodedJWT);
Header header = Mapper.deserialize(base64Decode(parts[0].getBytes(StandardCharsets.UTF_8)), Header.class);
// If parts.length == 2 we have no signature, if no verifiers were provided, decode if header says 'none', else throw an exception
if (parts.length == 2 && verifiers.isEmpty()) {
if (header.algorithm == Algorithm.none) {
return Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class);
} else {
throw new InvalidJWTSignatureException();
}
}
// If verifiers were provided, ensure it is able to verify this JWT.
String key = keyFunction.apply(header);
Verifier verifier = verifiers.get(key);
if (verifier != null) {
if (!verifier.canVerify(header.algorithm)) {
verifier = null;
}
}
return decode(encodedJWT, header, parts, verifier);
}
",FALSE,JWTDecoder.java
" private byte[] base64Decode(byte[] bytes) {
try {
return Base64.getUrlDecoder().decode(bytes);
} catch (IllegalArgumentException e) {
throw new InvalidJWTException(""The encoded JWT is not properly Base64 encoded."", e);
}
}
"," private byte[] base64Decode(byte[] bytes) {
try {
return Base64.getUrlDecoder().decode(bytes);
} catch (IllegalArgumentException e) {
throw new InvalidJWTException(""The encoded JWT is not properly Base64 encoded."", e);
}
}
",FALSE,JWTDecoder.java
" private JWT decode(String encodedJWT, Header header, String[] parts, Verifier verifier) {
int index = encodedJWT.lastIndexOf(""."");
// The message comprises the first two segments of the entire JWT, the signature is the last segment.
byte[] message = encodedJWT.substring(0, index).getBytes(StandardCharsets.UTF_8);
// If a signature is provided and verifier must be provided.
if (parts.length == 3 && verifier == null) {
throw new MissingVerifierException(""No Verifier has been provided for verify a signature signed using ["" + header.algorithm.getName() + ""]"");
}
// A verifier was provided but no signature exists, this is treated as an invalid signature.
if (parts.length == 2 && verifier != null) {
throw new InvalidJWTSignatureException();
}
if (parts.length == 3) {
// Verify the signature before de-serializing the payload.
byte[] signature = base64Decode(parts[2].getBytes(StandardCharsets.UTF_8));
verifier.verify(header.algorithm, message, signature);
}
JWT jwt = Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class);
// Verify expiration claim
if (jwt.isExpired()) {
throw new JWTExpiredException();
}
// Verify the notBefore claim
if (jwt.isUnavailableForProcessing()) {
throw new JWTUnavailableForProcessingException();
}
return jwt;
}
"," private JWT decode(String encodedJWT, Header header, String[] parts, Verifier verifier) {
// The callers of this decode will have already handled 'none' if it was deemed to be valid based upon
// the provided verifiers. At this point, if we have a 'none' algorithm specified in the header, it is invalid.
if (header.algorithm == Algorithm.none) {
throw new MissingVerifierException(""No Verifier has been provided for verify a signature signed using ["" + header.algorithm.getName() + ""]"");
}
// If a signature is provided and verifier must be provided.
if (parts.length == 3 && verifier == null) {
throw new MissingVerifierException(""No Verifier has been provided for verify a signature signed using ["" + header.algorithm.getName() + ""]"");
}
// A verifier was provided but no signature exists, this is treated as an invalid signature.
if (parts.length == 2 && verifier != null) {
throw new InvalidJWTSignatureException();
}
int index = encodedJWT.lastIndexOf(""."");
// The message comprises the first two segments of the entire JWT, the signature is the last segment.
byte[] message = encodedJWT.substring(0, index).getBytes(StandardCharsets.UTF_8);
if (parts.length == 3) {
// Verify the signature before de-serializing the payload.
byte[] signature = base64Decode(parts[2].getBytes(StandardCharsets.UTF_8));
verifier.verify(header.algorithm, message, signature);
}
JWT jwt = Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class);
// Verify expiration claim
if (jwt.isExpired()) {
throw new JWTExpiredException();
}
// Verify the notBefore claim
if (jwt.isUnavailableForProcessing()) {
throw new JWTUnavailableForProcessingException();
}
return jwt;
}
",TRUE,JWTDecoder.java
" private String[] getParts(String encodedJWT) {
String[] parts = encodedJWT.split(""\\."");
// Secured JWT XXXXX.YYYYY.ZZZZZ, Unsecured JWT XXXXX.YYYYY.
if (parts.length == 3 || (parts.length == 2 && encodedJWT.endsWith("".""))) {
return parts;
}
throw new InvalidJWTException(""The encoded JWT is not properly formatted. Expected a three part dot separated string."");
}
"," private String[] getParts(String encodedJWT) {
String[] parts = encodedJWT.split(""\\."");
// Secured JWT XXXXX.YYYYY.ZZZZZ, Unsecured JWT XXXXX.YYYYY.
if (parts.length == 3 || (parts.length == 2 && encodedJWT.endsWith("".""))) {
return parts;
}
throw new InvalidJWTException(""The encoded JWT is not properly formatted. Expected a three part dot separated string."");
}
",FALSE,JWTDecoder.java
" public void test_SignedWithoutSignature() throws Exception {
JWT inputJwt = new JWT()
.setSubject(""123456789"")
.setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC))
.setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(2));
String encodedJWT = JWT.getEncoder().encode(inputJwt, HMACSigner.newSHA256Signer(""secret""));
String encodedJWTNoSignature = encodedJWT.substring(0, encodedJWT.lastIndexOf('.') + 1);
expectException(InvalidJWTSignatureException.class, () -> JWT.getDecoder().decode(encodedJWTNoSignature, HMACVerifier.newVerifier(""secret"")));
// Also cannot be decoded even if the caller calls decode w/out a signature because the header still indicates a signature algorithm.
expectException(InvalidJWTSignatureException.class, () -> JWT.getDecoder().decode(encodedJWTNoSignature));
}
"," public void test_SignedWithoutSignature() throws Exception {
JWT inputJwt = new JWT()
.setSubject(""123456789"")
.setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC))
.setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusHours(2));
String encodedJWT = JWT.getEncoder().encode(inputJwt, HMACSigner.newSHA256Signer(""secret""));
String encodedJWTNoSignature = encodedJWT.substring(0, encodedJWT.lastIndexOf('.') + 1);
expectException(InvalidJWTSignatureException.class, () -> JWT.getDecoder().decode(encodedJWTNoSignature, HMACVerifier.newVerifier(""secret"")));
// Also cannot be decoded even if the caller calls decode w/out a signature because the header still indicates a signature algorithm.
expectException(InvalidJWTSignatureException.class, () -> JWT.getDecoder().decode(encodedJWTNoSignature));
}
",FALSE,VulnerabilityTest.java
" public void test_encodedJwtWithSignatureRemoved() throws Exception {
// Sign a JWT and then attempt to verify it using None.
JWT jwt = new JWT().setSubject(""art"");
String encodedJWT = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer(""secret""));
String hackedJWT = encodedJWT.substring(0, encodedJWT.lastIndexOf("".""));
expectException(InvalidJWTException.class, ()
-> JWT.getDecoder().decode(hackedJWT, HMACVerifier.newVerifier(""secret"")));
}
"," public void test_encodedJwtWithSignatureRemoved() throws Exception {
// Sign a JWT and then attempt to verify it using None.
JWT jwt = new JWT().setSubject(""art"");
String encodedJWT = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer(""secret""));
String hackedJWT = encodedJWT.substring(0, encodedJWT.lastIndexOf("".""));
expectException(InvalidJWTException.class, () -> JWT.getDecoder().decode(hackedJWT, HMACVerifier.newVerifier(""secret"")));
}
",TRUE,VulnerabilityTest.java
" public void test_noVerification() throws Exception {
// Sign a JWT and then attempt to verify it using None.
JWT jwt = new JWT().setSubject(""art"");
String encodedJWT = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer(""secret""));
expectException(MissingVerifierException.class, ()
-> JWT.getDecoder().decode(encodedJWT));
}
"," public void test_noVerification() throws Exception {
// Sign a JWT and then attempt to verify it using None.
JWT jwt = new JWT().setSubject(""art"");
String encodedJWT = JWT.getEncoder().encode(jwt, HMACSigner.newSHA256Signer(""secret""));
expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedJWT));
}
",TRUE,VulnerabilityTest.java
" }
"," public void test_unsecuredJWT_validation() throws Exception {
JWT jwt = new JWT().setSubject(""123456789"");
Signer signer = new UnsecuredSigner();
Verifier hmacVerifier = HMACVerifier.newVerifier(""too many secrets"");
String encodedUnsecuredJWT = JWTEncoder.getInstance().encode(jwt, signer);
// Ensure that attempting to decode an un-secured JWT fails when we provide a verifier
expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT, hmacVerifier));
String encodedUnsecuredJWT_withKid = JWTEncoder.getInstance().encode(jwt, signer, (header) -> header.set(""kid"", ""abc""));
String encodedUnsecuredJWT_withoutKid = JWTEncoder.getInstance().encode(jwt, signer);
Map verifierMap = new HashMap<>();
verifierMap.put(null, hmacVerifier);
verifierMap.put(""abc"", hmacVerifier);
// Ensure that attempting to decode an un-secured JWT fails when we provide a verifier with or without using a kid
expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withKid, verifierMap));
expectException(MissingVerifierException.class, () -> JWT.getDecoder().decode(encodedUnsecuredJWT_withoutKid, verifierMap));
}
",TRUE,VulnerabilityTest.java
" public void test_vulnerability_HMAC_forgery() throws Exception {
// Generate a JWT using HMAC with an RSA public key to attempt to trick the library into verifying the JWT
// Testing for the vulnerability described by Tim McLean
// https://threatpost.com/critical-vulnerabilities-affect-json-web-token-libraries/111943/
// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
JWT jwt = new JWT().setSubject(""123456789"");
// Hacked signer, obtain a publicly available RSA Public Key in use by the JWT issuer
Signer hackedSigner = HMACSigner.newSHA512Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem""))));
// Forged a JWT - sign your own token using the hacked Signer
String hmacSignedJWT = JWTEncoder.getInstance().encode(jwt, hackedSigner, h -> h.set(""kid"", ""abc""));
// Server side Verifiers used to validate JWTs they have issued
Verifier rsaVerifier = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem""))));
Verifier hmacVerifier = HMACVerifier.newVerifier(""secret"");
// Attempt to decode using var-args call to decode, no kid. This correctly fails because we only ask the HMAC verifier to decode an HMAC signed JWT.
// And the server has built an HMAC verifier using their shared secret.
expectException(InvalidJWTSignatureException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWT, rsaVerifier, hmacVerifier));
Map verifierMap = new HashMap<>();
verifierMap.put(""abc"", rsaVerifier);
verifierMap.put(""def"", hmacVerifier);
// Attempt to decode using a map of verifiers. This correctly fails because the verifier for the kid does not support the algorithm in the header
// The kid in this case causes us to look up the verifier built by the server which is an RSA verifier.
expectException(MissingVerifierException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWT, verifierMap));
// Forge another JWT - but assume we know ahead of time all of the kids and which one maps to the hmac verifier
String hmacSignedJWTTakeTwo = JWTEncoder.getInstance().encode(jwt, hackedSigner, h -> h.set(""kid"", ""def""));
// This call fails because we ask the HMAC verifier to validate a signature built using a public key.
expectException(InvalidJWTSignatureException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWTTakeTwo, rsaVerifier, hmacVerifier));
// This call fails because in this case we have the correct kid 'def' which is the hmac verifier - but again the verifier was not built with the public key.
// The kid in this case causes us to look up the HMAC verifier which is what the hacker wants, but it again is already built using the correct shared secret.
expectException(InvalidJWTSignatureException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWTTakeTwo, verifierMap));
}
"," public void test_vulnerability_HMAC_forgery() throws Exception {
// Generate a JWT using HMAC with an RSA public key to attempt to trick the library into verifying the JWT
// Testing for the vulnerability described by Tim McLean
// https://threatpost.com/critical-vulnerabilities-affect-json-web-token-libraries/111943/
// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
JWT jwt = new JWT().setSubject(""123456789"");
// Hacked signer, obtain a publicly available RSA Public Key in use by the JWT issuer
Signer hackedSigner = HMACSigner.newSHA512Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem""))));
// Forged a JWT - sign your own token using the hacked Signer
String hmacSignedJWT = JWTEncoder.getInstance().encode(jwt, hackedSigner, h -> h.set(""kid"", ""abc""));
// Server side Verifiers used to validate JWTs they have issued
Verifier rsaVerifier = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem""))));
Verifier hmacVerifier = HMACVerifier.newVerifier(""secret"");
// Attempt to decode using var-args call to decode, no kid. This correctly fails because we only ask the HMAC verifier to decode an HMAC signed JWT.
// And the server has built an HMAC verifier using their shared secret.
expectException(InvalidJWTSignatureException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWT, rsaVerifier, hmacVerifier));
Map verifierMap = new HashMap<>();
verifierMap.put(""abc"", rsaVerifier);
verifierMap.put(""def"", hmacVerifier);
// Attempt to decode using a map of verifiers. This correctly fails because the verifier for the kid does not support the algorithm in the header
// The kid in this case causes us to look up the verifier built by the server which is an RSA verifier.
expectException(MissingVerifierException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWT, verifierMap));
// Forge another JWT - but assume we know ahead of time all of the kids and which one maps to the hmac verifier
String hmacSignedJWTTakeTwo = JWTEncoder.getInstance().encode(jwt, hackedSigner, h -> h.set(""kid"", ""def""));
// This call fails because we ask the HMAC verifier to validate a signature built using a public key.
expectException(InvalidJWTSignatureException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWTTakeTwo, rsaVerifier, hmacVerifier));
// This call fails because in this case we have the correct kid 'def' which is the hmac verifier - but again the verifier was not built with the public key.
// The kid in this case causes us to look up the HMAC verifier which is what the hacker wants, but it again is already built using the correct shared secret.
expectException(InvalidJWTSignatureException.class, () -> JWTDecoder.getInstance().decode(hmacSignedJWTTakeTwo, verifierMap));
}
",FALSE,VulnerabilityTest.java
" public COSArray()
{
//default constructor
}
"," public COSArray()
{
//default constructor
}
",FALSE,COSArray.java
" public void add( COSBase object )
{
objects.add( object );
}
"," public void add( COSBase object )
{
objects.add( object );
}
",FALSE,COSArray.java
" public void add( COSObjectable object )
{
objects.add( object.getCOSObject() );
}
"," public void add( COSObjectable object )
{
objects.add( object.getCOSObject() );
}
",FALSE,COSArray.java
" public void add( int i, COSBase object)
{
objects.add( i, object );
}
"," public void add( int i, COSBase object)
{
objects.add( i, object );
}
",FALSE,COSArray.java
" public void clear()
{
objects.clear();
}
"," public void clear()
{
objects.clear();
}
",FALSE,COSArray.java
" public void removeAll( Collection objectsList )
{
objects.removeAll( objectsList );
}
"," public void removeAll( Collection objectsList )
{
objects.removeAll( objectsList );
}
",FALSE,COSArray.java
" public void retainAll( Collection objectsList )
{
objects.retainAll( objectsList );
}
"," public void retainAll( Collection objectsList )
{
objects.retainAll( objectsList );
}
",FALSE,COSArray.java
" public void addAll( Collection objectsList )
{
objects.addAll( objectsList );
}
"," public void addAll( Collection objectsList )
{
objects.addAll( objectsList );
}
",FALSE,COSArray.java
" public void addAll( COSArray objectList )
{
if( objectList != null )
{
objects.addAll( objectList.objects );
}
}
"," public void addAll( COSArray objectList )
{
if( objectList != null )
{
objects.addAll( objectList.objects );
}
}
",FALSE,COSArray.java
" public void addAll( int i, Collection objectList )
{
objects.addAll( i, objectList );
}
"," public void addAll( int i, Collection objectList )
{
objects.addAll( i, objectList );
}
",FALSE,COSArray.java
" public void set( int index, COSBase object )
{
objects.set( index, object );
}
"," public void set( int index, COSBase object )
{
objects.set( index, object );
}
",FALSE,COSArray.java
" public void set( int index, int intVal )
{
objects.set( index, COSInteger.get(intVal) );
}
"," public void set( int index, int intVal )
{
objects.set( index, COSInteger.get(intVal) );
}
",FALSE,COSArray.java
" public void set( int index, COSObjectable object )
{
COSBase base = null;
if( object != null )
{
base = object.getCOSObject();
}
objects.set( index, base );
}
"," public void set( int index, COSObjectable object )
{
COSBase base = null;
if( object != null )
{
base = object.getCOSObject();
}
objects.set( index, base );
}
",FALSE,COSArray.java
" public COSBase getObject( int index )
{
Object obj = objects.get( index );
if( obj instanceof COSObject )
{
obj = ((COSObject)obj).getObject();
}
if (obj instanceof COSNull)
{
obj = null;
}
return (COSBase)obj;
}
"," public COSBase getObject( int index )
{
Object obj = objects.get( index );
if( obj instanceof COSObject )
{
obj = ((COSObject)obj).getObject();
}
if (obj instanceof COSNull)
{
obj = null;
}
return (COSBase)obj;
}
",FALSE,COSArray.java
" public COSBase get( int index )
{
return objects.get( index );
}
"," public COSBase get( int index )
{
return objects.get( index );
}
",FALSE,COSArray.java
" public int getInt( int index )
{
return getInt( index, -1 );
}
"," public int getInt( int index )
{
return getInt( index, -1 );
}
",FALSE,COSArray.java
" public int getInt( int index, int defaultValue )
{
int retval = defaultValue;
if ( index < size() )
{
Object obj = objects.get( index );
if( obj instanceof COSNumber )
{
retval = ((COSNumber)obj).intValue();
}
}
return retval;
}
"," public int getInt( int index, int defaultValue )
{
int retval = defaultValue;
if ( index < size() )
{
Object obj = objects.get( index );
if( obj instanceof COSNumber )
{
retval = ((COSNumber)obj).intValue();
}
}
return retval;
}
",FALSE,COSArray.java
" public void setInt( int index, int value )
{
set( index, COSInteger.get( value ) );
}
"," public void setInt( int index, int value )
{
set( index, COSInteger.get( value ) );
}
",FALSE,COSArray.java
" public void setName( int index, String name )
{
set( index, COSName.getPDFName( name ) );
}
"," public void setName( int index, String name )
{
set( index, COSName.getPDFName( name ) );
}
",FALSE,COSArray.java
" public String getName( int index )
{
return getName( index, null );
}
"," public String getName( int index )
{
return getName( index, null );
}
",FALSE,COSArray.java
" public String getName( int index, String defaultValue )
{
String retval = defaultValue;
if( index < size() )
{
Object obj = objects.get( index );
if( obj instanceof COSName )
{
retval = ((COSName)obj).getName();
}
}
return retval;
}
"," public String getName( int index, String defaultValue )
{
String retval = defaultValue;
if( index < size() )
{
Object obj = objects.get( index );
if( obj instanceof COSName )
{
retval = ((COSName)obj).getName();
}
}
return retval;
}
",FALSE,COSArray.java
" public void setString( int index, String string )
{
if ( string != null )
{
set( index, new COSString( string ) );
}
else
{
set( index, null );
}
}
"," public void setString( int index, String string )
{
if ( string != null )
{
set( index, new COSString( string ) );
}
else
{
set( index, null );
}
}
",FALSE,COSArray.java
" public String getString( int index )
{
return getString( index, null );
}
"," public String getString( int index )
{
return getString( index, null );
}
",FALSE,COSArray.java
" public String getString( int index, String defaultValue )
{
String retval = defaultValue;
if( index < size() )
{
Object obj = objects.get( index );
if( obj instanceof COSString )
{
retval = ((COSString)obj).getString();
}
}
return retval;
}
"," public String getString( int index, String defaultValue )
{
String retval = defaultValue;
if( index < size() )
{
Object obj = objects.get( index );
if( obj instanceof COSString )
{
retval = ((COSString)obj).getString();
}
}
return retval;
}
",FALSE,COSArray.java
" public int size()
{
return objects.size();
}
"," public int size()
{
return objects.size();
}
",FALSE,COSArray.java
" public COSBase remove( int i )
{
return objects.remove( i );
}
"," public COSBase remove( int i )
{
return objects.remove( i );
}
",FALSE,COSArray.java
" public boolean remove( COSBase o )
{
return objects.remove( o );
}
"," public boolean remove( COSBase o )
{
return objects.remove( o );
}
",FALSE,COSArray.java
" public boolean removeObject(COSBase o)
{
boolean removed = this.remove(o);
if (!removed)
{
for (int i = 0; i < this.size(); i++)
{
COSBase entry = this.get(i);
if (entry instanceof COSObject)
{
COSObject objEntry = (COSObject) entry;
if (objEntry.getObject().equals(o))
{
return this.remove(entry);
}
}
}
}
return removed;
}
"," public boolean removeObject(COSBase o)
{
boolean removed = this.remove(o);
if (!removed)
{
for (int i = 0; i < this.size(); i++)
{
COSBase entry = this.get(i);
if (entry instanceof COSObject)
{
COSObject objEntry = (COSObject) entry;
if (objEntry.getObject().equals(o))
{
return this.remove(entry);
}
}
}
}
return removed;
}
",FALSE,COSArray.java
" public String toString()
{
return ""COSArray{"" + objects + ""}"";
}
"," public String toString()
{
return ""COSArray{"" + objects + ""}"";
}
",FALSE,COSArray.java
" public Iterator iterator()
{
return objects.iterator();
}
"," public Iterator iterator()
{
return objects.iterator();
}
",FALSE,COSArray.java
" public int indexOf( COSBase object )
{
int retval = -1;
for( int i=0; retval < 0 && i toList()
{
List retList = new ArrayList<>(size());
for (int i = 0; i < size(); i++)
{
retList.add(get(i));
}
return retList;
}
"," public List extends COSBase> toList()
{
List retList = new ArrayList<>(size());
for (int i = 0; i < size(); i++)
{
retList.add(get(i));
}
return retList;
}
",FALSE,COSArray.java
" public MagicSAXFilter(ResourceBundle messages) {
this.messages = messages;
}
"," public MagicSAXFilter(ResourceBundle messages) {
this.messages = messages;
}
",FALSE,MagicSAXFilter.java
" public void reset(InternalPolicy instance){
this.policy = instance;
isNofollowAnchors = policy.isNofollowAnchors();
isValidateParamAsEmbed = policy.isValidateParamAsEmbed();
preserveComments = policy.isPreserveComments();
maxInputSize = policy.getMaxInputSize();
externalCssScanner = policy.isEmbedStyleSheets();
operations.clear();
errorMessages.clear();
cssContent = null;
cssAttributes = null;
cssScanner = null;
inCdata = false;
}
"," public void reset(InternalPolicy instance){
this.policy = instance;
isNofollowAnchors = policy.isNofollowAnchors();
isValidateParamAsEmbed = policy.isValidateParamAsEmbed();
preserveComments = policy.isPreserveComments();
maxInputSize = policy.getMaxInputSize();
externalCssScanner = policy.isEmbedStyleSheets();
operations.clear();
errorMessages.clear();
cssContent = null;
cssAttributes = null;
cssScanner = null;
inCdata = false;
}
",FALSE,MagicSAXFilter.java
" public void characters(XMLString text, Augmentations augs) throws XNIException {
//noinspection StatementWithEmptyBody
Ops topOp = peekTop();
//noinspection StatementWithEmptyBody
if (topOp == Ops.REMOVE) {
// content is removed altogether
} else if (topOp == Ops.CSS) {
// we record the style element's text content
// to filter it later
cssContent.append(text.ch, text.offset, text.length);
} else {
// pass through all character content.
if ( inCdata ) {
String encoded = HTMLEntityEncoder.htmlEntityEncode(text.toString());
addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[]{encoded});
}
super.characters(text, augs);
}
}
"," public void characters(XMLString text, Augmentations augs) throws XNIException {
//noinspection StatementWithEmptyBody
Ops topOp = peekTop();
//noinspection StatementWithEmptyBody
if (topOp == Ops.REMOVE) {
// content is removed altogether
} else if (topOp == Ops.CSS) {
// we record the style element's text content
// to filter it later
cssContent.append(text.ch, text.offset, text.length);
} else {
// pass through all character content.
if ( inCdata ) {
String encoded = HTMLEntityEncoder.htmlEntityEncode(text.toString());
addError(ErrorMessageUtil.ERROR_CDATA_FOUND, new Object[]{encoded});
}
super.characters(text, augs);
}
}
",FALSE,MagicSAXFilter.java
" public void comment(XMLString text, Augmentations augs) throws XNIException {
if (preserveComments) {
String value = text.toString();
// Strip conditional directives regardless of the
// PRESERVE_COMMENTS setting.
if (value != null) {
value = conditionalDirectives.matcher(value).replaceAll("""");
super.comment(new XMLString(value.toCharArray(), 0, value.length()), augs);
}
}
}
"," public void comment(XMLString text, Augmentations augs) throws XNIException {
if (preserveComments) {
String value = text.toString();
// Strip conditional directives regardless of the
// PRESERVE_COMMENTS setting.
if (value != null) {
value = conditionalDirectives.matcher(value).replaceAll("""");
super.comment(new XMLString(value.toCharArray(), 0, value.length()), augs);
}
}
}
",FALSE,MagicSAXFilter.java
" public void doctypeDecl(String root, String publicId, String systemId, Augmentations augs) throws XNIException {
// user supplied doctypes are ignored
}
"," public void doctypeDecl(String root, String publicId, String systemId, Augmentations augs) throws XNIException {
// user supplied doctypes are ignored
}
",FALSE,MagicSAXFilter.java
" public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException {
this.startElement(element, attributes, augs);
this.endElement(element, augs);
}
"," public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException {
this.startElement(element, attributes, augs);
this.endElement(element, augs);
}
",FALSE,MagicSAXFilter.java
" private Ops peekTop(){
return operations.empty() ? null : operations.peek();
}
"," private Ops peekTop(){
return operations.empty() ? null : operations.peek();
}
",FALSE,MagicSAXFilter.java
" public void endElement(QName element, Augmentations augs) throws XNIException {
Ops topOp = peekTop();
if (Ops.REMOVE == topOp) {
// content is removed altogether
operations.pop();
} else if (Ops.FILTER == topOp) {
// content is removed, but child nodes not
operations.pop();
} else if (Ops.CSS == topOp) {
operations.pop();
// now scan the CSS.
CssScanner cssScanner = makeCssScanner();
try {
CleanResults results = cssScanner.scanStyleSheet(cssContent.toString(), maxInputSize);
// report all errors found
errorMessages.addAll(results.getErrorMessages());
/*
* If IE gets an empty style tag, i.e. it will break
* all CSS on the page. I wish I was kidding. So, if after
* validation no CSS properties are left, we would normally be
* left with an empty style tag and break all CSS. To prevent
* that, we have this check.
*/
//noinspection StatementWithEmptyBody
if (results.getCleanHTML() == null || results.getCleanHTML().equals("""")) {
// we do not generate empty style elements
} else {
// XMLAttributes attributes = new XMLAttributesImpl();
// attributes.addAttribute(makeSimpleQname(""type""), ""CDATA"",
// ""text/css"");
// start the CSS element
super.startElement(element, cssAttributes, new AugmentationsImpl());
// send the cleaned content
super.characters(new XMLStringBuffer(results.getCleanHTML()), new AugmentationsImpl());
// end the CSS element
super.endElement(element, augs);
}
} catch (ScanException e) {
// if the CSS is unscannable, we report the error, but skip the
// style element
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] {
HTMLEntityEncoder.htmlEntityEncode(cssContent.toString())
});
} finally {
// reset the string buffer to allow fresh recording of next
// style tag
cssContent = null;
cssAttributes = null;
}
} else {
// keep or truncate means the end-tag stays intact
operations.pop();
super.endElement(element, augs);
}
}
"," public void endElement(QName element, Augmentations augs) throws XNIException {
Ops topOp = peekTop();
if (Ops.REMOVE == topOp) {
// content is removed altogether
operations.pop();
} else if (Ops.FILTER == topOp) {
// content is removed, but child nodes not
operations.pop();
} else if (Ops.CSS == topOp) {
operations.pop();
// now scan the CSS.
CssScanner cssScanner = makeCssScanner();
try {
CleanResults results = cssScanner.scanStyleSheet(cssContent.toString(), maxInputSize);
// report all errors found
errorMessages.addAll(results.getErrorMessages());
/*
* If IE gets an empty style tag, i.e. it will break
* all CSS on the page. I wish I was kidding. So, if after
* validation no CSS properties are left, we would normally be
* left with an empty style tag and break all CSS. To prevent
* that, we have this check.
*/
//noinspection StatementWithEmptyBody
if (results.getCleanHTML() == null || results.getCleanHTML().equals("""")) {
// we do not generate empty style elements
} else {
// XMLAttributes attributes = new XMLAttributesImpl();
// attributes.addAttribute(makeSimpleQname(""type""), ""CDATA"",
// ""text/css"");
// start the CSS element
super.startElement(element, cssAttributes, new AugmentationsImpl());
// send the cleaned content
super.characters(new XMLStringBuffer(results.getCleanHTML()), new AugmentationsImpl());
// end the CSS element
super.endElement(element, augs);
}
} catch (ScanException e) {
// if the CSS is unscannable, we report the error, but skip the
// style element
addError(ErrorMessageUtil.ERROR_CSS_TAG_MALFORMED, new Object[] {
HTMLEntityEncoder.htmlEntityEncode(cssContent.toString())
});
} finally {
// reset the string buffer to allow fresh recording of next
// style tag
cssContent = null;
cssAttributes = null;
}
} else {
// keep or truncate means the end-tag stays intact
operations.pop();
super.endElement(element, augs);
}
}
",FALSE,MagicSAXFilter.java
" private CssScanner makeCssScanner() {
if (cssScanner == null) {
cssScanner = externalCssScanner ? new ExternalCssScanner(policy, messages) : new CssScanner(policy, messages);
}
return cssScanner;
}
"," private CssScanner makeCssScanner() {
if (cssScanner == null) {
cssScanner = externalCssScanner ? new ExternalCssScanner(policy, messages) : new CssScanner(policy, messages);
}
return cssScanner;
}
",FALSE,MagicSAXFilter.java
" public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException {
// processing instructions are being removed
}
"," public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException {
// processing instructions are being removed
}
",FALSE,MagicSAXFilter.java
" public void startCDATA(Augmentations augs) throws XNIException {
inCdata = true;
super.startCDATA(augs);
}
"," public void startCDATA(Augmentations augs) throws XNIException {
inCdata = true;
super.startCDATA(augs);
}
",FALSE,MagicSAXFilter.java
" public void endCDATA(Augmentations augs) throws XNIException {
inCdata = false;
super.endCDATA(augs);
}
"," public void endCDATA(Augmentations augs) throws XNIException {
inCdata = false;
super.endCDATA(augs);
}
",FALSE,MagicSAXFilter.java
" public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException {
// see if we have a policy for this tag.
String tagNameLowerCase = element.localpart.toLowerCase();
Tag tag = policy.getTagByLowercaseName(tagNameLowerCase);
/*
* Handle the automatic translation of to nested for IE.
* This is only if the ""validateParamAsEmbed"" directive is enabled.
*/
boolean masqueradingParam = false;
String embedName = null;
String embedValue = null;
if (tag == null && isValidateParamAsEmbed && ""param"".equals(tagNameLowerCase)) {
Tag embedPolicy = policy.getEmbedTag();
if (embedPolicy != null && embedPolicy.isAction( Policy.ACTION_VALIDATE)) {
tag = embedPolicy;// Constants.BASIC_PARAM_TAG_RULE;
masqueradingParam = true;
// take and turn into
//
embedName = attributes.getValue(""name"");
embedValue = attributes.getValue(""value"");
XMLAttributes masqueradingAttrs = new XMLAttributesImpl();
masqueradingAttrs.addAttribute(makeSimpleQname(embedName), ""CDATA"", embedValue);
attributes = masqueradingAttrs;
}
}
XMLAttributes validattributes = new XMLAttributesImpl();
Ops topOp = peekTop();
if (Ops.REMOVE == topOp || Ops.CSS == topOp) {
// we are in removal-mode, so remove this tag as well
// we also remove all child elements of a style element
this.operations.push( Ops.REMOVE);
} else if ((tag == null && policy.isEncodeUnknownTag()) || (tag != null && tag.isAction( ""encode"" ))) {
String name = ""<"" + element.localpart + "">"";
super.characters( new XMLString( name.toCharArray(), 0, name.length() ), augs );
this.operations.push(Ops.FILTER);
} else if (tag == null) {
addError( ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY,
new Object[]{ HTMLEntityEncoder.htmlEntityEncode( element.localpart ) } );
this.operations.push(Ops.FILTER);
} else if (tag.isAction( ""filter"")) {
addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[] {
HTMLEntityEncoder.htmlEntityEncode(element.localpart)
});
this.operations.push(Ops.FILTER);
} else if (tag.isAction( ""validate"")) {
boolean isStyle = ""style"".endsWith(element.localpart);
if (isStyle) {
this.operations.push(Ops.CSS);
cssContent = new StringBuffer();
cssAttributes = attributes;
} else {
// validate all attributes, we need to do this now to find out
// how to deal with the element
boolean removeTag = false;
boolean filterTag = false;
for (int i = 0; i < attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
String nameLower = name.toLowerCase();
Attribute attribute = tag.getAttributeByName(nameLower);
if (attribute == null) {
// no policy defined, perhaps it is a global attribute
attribute = policy.getGlobalAttributeByName(nameLower);
}
// boolean isAttributeValid = false;
if (""style"".equalsIgnoreCase(name)) {
CssScanner styleScanner = makeCssScanner();
try {
CleanResults cr = styleScanner.scanInlineStyle(value, element.localpart, maxInputSize);
attributes.setValue(i, cr.getCleanHTML());
validattributes.addAttribute(makeSimpleQname(name), ""CDATA"", cr.getCleanHTML());
errorMessages.addAll(cr.getErrorMessages());
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] {
element.localpart, HTMLEntityEncoder.htmlEntityEncode(value)
});
}
} else if (attribute != null) {
// validate the values against the policy
boolean isValid = false;
if (attribute.containsAllowedValue(value.toLowerCase())) {
validattributes.addAttribute(makeSimpleQname(name), ""CDATA"", value);
isValid = true;
}
if (!isValid) {
isValid = attribute.matchesAllowedExpression(value);
if (isValid) {
validattributes.addAttribute(makeSimpleQname(name), ""CDATA"", value);
}
}
// if value or regexp matched, attribute is already
// copied, but what happens if not
if (!isValid && ""removeTag"".equals(attribute.getOnInvalid())) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,
new Object[] { tag.getName(), HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
removeTag = true;
} else if (!isValid && (""filterTag"".equals(attribute.getOnInvalid()) || masqueradingParam)) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER,
new Object[] { tag.getName(), HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
filterTag = true;
} else if (!isValid) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID, new Object[] { tag.getName(), HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
}
} else { // attribute == null
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] {
element.localpart, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)
});
if (masqueradingParam) {
filterTag = true;
}
}
}
if (removeTag) {
this.operations.push(Ops.REMOVE);
} else if (filterTag) {
this.operations.push(Ops.FILTER);
} else {
if (isNofollowAnchors && ""a"".equals(element.localpart)) {
validattributes.addAttribute(makeSimpleQname(""rel""), ""CDATA"", ""nofollow"");
}
if (masqueradingParam) {
validattributes = new XMLAttributesImpl();
validattributes.addAttribute(makeSimpleQname(""name""), ""CDATA"", embedName);
validattributes.addAttribute(makeSimpleQname(""value""), ""CDATA"", embedValue);
}
this.operations.push(Ops.KEEP);
}
}
} else if (tag.isAction( ""truncate"")) {
this.operations.push(Ops.TRUNCATE);
} else {
// no options left, so the tag will be removed
addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[] {
HTMLEntityEncoder.htmlEntityEncode(element.localpart)
});
this.operations.push(Ops.REMOVE);
}
// now we know exactly what to do, let's do it
if ( Ops.TRUNCATE.equals( operations.peek() )) {
// copy the element, but remove all attributes
super.startElement(element, new XMLAttributesImpl(), augs);
} else if ( Ops.KEEP.equals(operations.peek())) {
// copy the element, but only copy accepted attributes
super.startElement(element, validattributes, augs);
}
}
"," public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException {
// see if we have a policy for this tag.
String tagNameLowerCase = element.localpart.toLowerCase();
Tag tag = policy.getTagByLowercaseName(tagNameLowerCase);
/*
* Handle the automatic translation of to nested for IE.
* This is only if the ""validateParamAsEmbed"" directive is enabled.
*/
boolean masqueradingParam = false;
String embedName = null;
String embedValue = null;
if (tag == null && isValidateParamAsEmbed && ""param"".equals(tagNameLowerCase)) {
Tag embedPolicy = policy.getEmbedTag();
if (embedPolicy != null && embedPolicy.isAction( Policy.ACTION_VALIDATE)) {
tag = embedPolicy;// Constants.BASIC_PARAM_TAG_RULE;
masqueradingParam = true;
// take and turn into
//
embedName = attributes.getValue(""name"");
embedValue = attributes.getValue(""value"");
XMLAttributes masqueradingAttrs = new XMLAttributesImpl();
masqueradingAttrs.addAttribute(makeSimpleQname(embedName), ""CDATA"", embedValue);
attributes = masqueradingAttrs;
}
}
XMLAttributes validattributes = new XMLAttributesImpl();
Ops topOp = peekTop();
if (Ops.REMOVE == topOp || Ops.CSS == topOp) {
// we are in removal-mode, so remove this tag as well
// we also remove all child elements of a style element
this.operations.push( Ops.REMOVE);
} else if ((tag == null && policy.isEncodeUnknownTag()) || (tag != null && tag.isAction( ""encode"" ))) {
String name = ""<"" + element.localpart + "">"";
super.characters( new XMLString( name.toCharArray(), 0, name.length() ), augs );
this.operations.push(Ops.FILTER);
} else if (tag == null) {
addError( ErrorMessageUtil.ERROR_TAG_NOT_IN_POLICY,
new Object[]{ HTMLEntityEncoder.htmlEntityEncode( element.localpart ) } );
this.operations.push(Ops.FILTER);
} else if (tag.isAction( ""filter"")) {
addError(ErrorMessageUtil.ERROR_TAG_FILTERED, new Object[] {
HTMLEntityEncoder.htmlEntityEncode(element.localpart)
});
this.operations.push(Ops.FILTER);
} else if (tag.isAction( ""validate"")) {
boolean isStyle = ""style"".endsWith(element.localpart);
// validate all attributes, we need to do this now to find out
// how to deal with the element
boolean removeTag = false;
boolean filterTag = false;
for (int i = 0; i < attributes.getLength(); i++) {
String name = attributes.getQName(i);
String value = attributes.getValue(i);
String nameLower = name.toLowerCase();
Attribute attribute = tag.getAttributeByName(nameLower);
if (attribute == null) {
// no policy defined, perhaps it is a global attribute
attribute = policy.getGlobalAttributeByName(nameLower);
}
// boolean isAttributeValid = false;
if (""style"".equalsIgnoreCase(name)) {
CssScanner styleScanner = makeCssScanner();
try {
CleanResults cr = styleScanner.scanInlineStyle(value, element.localpart, maxInputSize);
attributes.setValue(i, cr.getCleanHTML());
validattributes.addAttribute(makeSimpleQname(name), ""CDATA"", cr.getCleanHTML());
errorMessages.addAll(cr.getErrorMessages());
} catch (ScanException e) {
addError(ErrorMessageUtil.ERROR_CSS_ATTRIBUTE_MALFORMED, new Object[] {
element.localpart, HTMLEntityEncoder.htmlEntityEncode(value)
});
}
} else if (attribute != null) {
// validate the values against the policy
boolean isValid = false;
if (attribute.containsAllowedValue(value.toLowerCase())) {
validattributes.addAttribute(makeSimpleQname(name), ""CDATA"", value);
isValid = true;
}
if (!isValid) {
isValid = attribute.matchesAllowedExpression(value);
if (isValid) {
validattributes.addAttribute(makeSimpleQname(name), ""CDATA"", value);
}
}
// if value or regexp matched, attribute is already
// copied, but what happens if not
if (!isValid && ""removeTag"".equals(attribute.getOnInvalid())) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID_REMOVED,
new Object[] { tag.getName(), HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
removeTag = true;
} else if (!isValid && (""filterTag"".equals(attribute.getOnInvalid()) || masqueradingParam)) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_CAUSE_FILTER,
new Object[] { tag.getName(), HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
filterTag = true;
} else if (!isValid) {
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_INVALID, new Object[] { tag.getName(), HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value) });
}
} else { // attribute == null
addError(ErrorMessageUtil.ERROR_ATTRIBUTE_NOT_IN_POLICY, new Object[] {
element.localpart, HTMLEntityEncoder.htmlEntityEncode(name), HTMLEntityEncoder.htmlEntityEncode(value)
});
if (masqueradingParam) {
filterTag = true;
}
}
}
if (removeTag) {
this.operations.push(Ops.REMOVE);
} else if (isStyle) {
this.operations.push(Ops.CSS);
cssContent = new StringBuffer();
cssAttributes = validattributes;
} else if (filterTag) {
this.operations.push(Ops.FILTER);
} else {
if (isNofollowAnchors && ""a"".equals(element.localpart)) {
validattributes.addAttribute(makeSimpleQname(""rel""), ""CDATA"", ""nofollow"");
}
if (masqueradingParam) {
validattributes = new XMLAttributesImpl();
validattributes.addAttribute(makeSimpleQname(""name""), ""CDATA"", embedName);
validattributes.addAttribute(makeSimpleQname(""value""), ""CDATA"", embedValue);
}
this.operations.push(Ops.KEEP);
}
} else if (tag.isAction( ""truncate"")) {
this.operations.push(Ops.TRUNCATE);
} else {
// no options left, so the tag will be removed
addError(ErrorMessageUtil.ERROR_TAG_DISALLOWED, new Object[] {
HTMLEntityEncoder.htmlEntityEncode(element.localpart)
});
this.operations.push(Ops.REMOVE);
}
// now we know exactly what to do, let's do it
if ( Ops.TRUNCATE.equals( operations.peek() )) {
// copy the element, but remove all attributes
super.startElement(element, new XMLAttributesImpl(), augs);
} else if ( Ops.KEEP.equals(operations.peek())) {
// copy the element, but only copy accepted attributes
super.startElement(element, validattributes, augs);
}
}
",TRUE,MagicSAXFilter.java
" private QName makeSimpleQname(String name) {
return new QName("""", name, name, """");
}
"," private QName makeSimpleQname(String name) {
return new QName("""", name, name, """");
}
",FALSE,MagicSAXFilter.java
" private void addError(String errorKey, Object[] objs) {
errorMessages.add(ErrorMessageUtil.getMessage(messages, errorKey, objs));
}
"," private void addError(String errorKey, Object[] objs) {
errorMessages.add(ErrorMessageUtil.getMessage(messages, errorKey, objs));
}
",FALSE,MagicSAXFilter.java
" public List getErrorMessages() {
return errorMessages;
}
"," public List getErrorMessages() {
return errorMessages;
}
",FALSE,MagicSAXFilter.java
" HtmlSessionInformationsReport(List sessionsInformations, Writer writer) {
super(writer);
this.sessionsInformations = sessionsInformations;
}
"," HtmlSessionInformationsReport(List sessionsInformations, Writer writer) {
super(writer);
this.sessionsInformations = sessionsInformations;
}
",FALSE,HtmlSessionInformationsReport.java
" void toHtml() throws IOException {
writeBackAndRefreshLinks();
writeln("" "");
assert sessionsInformations != null;
if (sessionsInformations.isEmpty()) {
writeln(""#Aucune_session#"");
return;
}
writeTitle(""system-users.png"", getString(""Sessions""));
writeSessions(sessionsInformations);
long totalSerializedSize = 0;
int nbSerializableSessions = 0;
for (final SessionInformations sessionInformations : sessionsInformations) {
final int size = sessionInformations.getSerializedSize();
if (size >= 0) {
totalSerializedSize += size;
nbSerializableSessions++;
}
}
final long meanSerializedSize;
if (nbSerializableSessions > 0) {
meanSerializedSize = totalSerializedSize / nbSerializableSessions;
} else {
meanSerializedSize = -1;
}
writeln(""""
+ getFormattedString(""nb_sessions"", sessionsInformations.size()) + "" ""
+ getFormattedString(""taille_moyenne_sessions"", meanSerializedSize) + ""
"");
}
"," void toHtml() throws IOException {
writeBackAndRefreshLinks();
writeln("" "");
assert sessionsInformations != null;
if (sessionsInformations.isEmpty()) {
writeln(""#Aucune_session#"");
return;
}
writeTitle(""system-users.png"", getString(""Sessions""));
writeSessions(sessionsInformations);
long totalSerializedSize = 0;
int nbSerializableSessions = 0;
for (final SessionInformations sessionInformations : sessionsInformations) {
final int size = sessionInformations.getSerializedSize();
if (size >= 0) {
totalSerializedSize += size;
nbSerializableSessions++;
}
}
final long meanSerializedSize;
if (nbSerializableSessions > 0) {
meanSerializedSize = totalSerializedSize / nbSerializableSessions;
} else {
meanSerializedSize = -1;
}
writeln(""""
+ getFormattedString(""nb_sessions"", sessionsInformations.size()) + "" ""
+ getFormattedString(""taille_moyenne_sessions"", meanSerializedSize) + ""
"");
}
",FALSE,HtmlSessionInformationsReport.java
" private void writeSessions(List sessions) throws IOException {
boolean displayUser = false;
for (final SessionInformations sessionInformations : sessions) {
if (sessionInformations.getRemoteUser() != null) {
displayUser = true;
break;
}
}
final HtmlTable table = new HtmlTable();
table.beginTable(getString(""Sessions""));
write(""#Session_id# #Dernier_acces# "");
write(""#Age# #Expiration# "");
write(""#Nb_attributs# #Serialisable# #Taille_serialisee# "");
write(""#Adresse_IP# #Pays# "");
if (displayUser) {
write(""#Utilisateur# "");
}
write(""#Invalider# "");
for (final SessionInformations session : sessions) {
table.nextRow();
writeSession(session, displayUser);
}
table.endTable();
}
"," private void writeSessions(List sessions) throws IOException {
boolean displayUser = false;
for (final SessionInformations sessionInformations : sessions) {
if (sessionInformations.getRemoteUser() != null) {
displayUser = true;
break;
}
}
final HtmlTable table = new HtmlTable();
table.beginTable(getString(""Sessions""));
write(""#Session_id# #Dernier_acces# "");
write(""#Age# #Expiration# "");
write(""#Nb_attributs# #Serialisable# #Taille_serialisee# "");
write(""#Adresse_IP# #Pays# "");
if (displayUser) {
write(""#Utilisateur# "");
}
write(""#Invalider# "");
for (final SessionInformations session : sessions) {
table.nextRow();
writeSession(session, displayUser);
}
table.endTable();
}
",FALSE,HtmlSessionInformationsReport.java
" private void writeBackAndRefreshLinks() throws IOException {
writeln("""");
writeln(""
"");
writeln("" #Retour# "");
writeln("" "");
writeln(A_HREF_PART_SESSIONS + ""'>"");
writeln(""
#Actualiser#"");
if (isPdfEnabled()) {
writeln("" "");
write(A_HREF_PART_SESSIONS + ""&format=pdf' title='#afficher_PDF#'>"");
write(""
#PDF#"");
}
writeln("" "");
writeln(A_HREF_PART_SESSIONS
+ ""&action=invalidate_sessions' onclick=\""javascript:return confirm('""
+ getStringForJavascript(""confirm_invalidate_sessions"") + ""');\"">"");
writeln(""
#invalidate_sessions#"");
writeln(""
"");
}
"," private void writeBackAndRefreshLinks() throws IOException {
writeln("""");
writeln(""
"");
writeln("" #Retour# "");
writeln("" "");
writeln(A_HREF_PART_SESSIONS + ""'>"");
writeln(""
#Actualiser#"");
if (isPdfEnabled()) {
writeln("" "");
write(A_HREF_PART_SESSIONS + ""&format=pdf' title='#afficher_PDF#'>"");
write(""
#PDF#"");
}
writeln("" "");
writeln(A_HREF_PART_SESSIONS
+ ""&action=invalidate_sessions' onclick=\""javascript:return confirm('""
+ getStringForJavascript(""confirm_invalidate_sessions"") + ""');\"">"");
writeln(""
#invalidate_sessions#"");
writeln(""
"");
}
",FALSE,HtmlSessionInformationsReport.java
" private void writeBackAndRefreshLinksForSession(String sessionId) throws IOException {
writeln("""");
writeln(""
#Retour# "");
writeln(A_HREF_PART_SESSIONS + ""&sessionId="" + urlEncode(sessionId) + ""'>"");
writeln(""
#Actualiser#"");
writeln(""
"");
}
"," private void writeBackAndRefreshLinksForSession(String sessionId) throws IOException {
writeln("""");
writeln(""
#Retour# "");
writeln(A_HREF_PART_SESSIONS + ""&sessionId="" + urlEncode(sessionId) + ""'>"");
writeln(""
#Actualiser#"");
writeln(""
"");
}
",FALSE,HtmlSessionInformationsReport.java
" private void writeSession(SessionInformations session, boolean displayUser) throws IOException {
final String nextColumnAlignRight = """";
final String nextColumnAlignCenter = "" "";
write("" "");
write(htmlEncodeButNotSpace(session.getId()));
write("" "");
write(nextColumnAlignRight);
write(durationFormat.format(session.getLastAccess()));
write(nextColumnAlignRight);
write(durationFormat.format(session.getAge()));
write(nextColumnAlignRight);
write(expiryFormat.format(session.getExpirationDate()));
write(nextColumnAlignRight);
write(integerFormat.format(session.getAttributeCount()));
write(nextColumnAlignCenter);
if (session.isSerializable()) {
write(""#oui#"");
} else {
write(""#non# "");
}
write(nextColumnAlignRight);
write(integerFormat.format(session.getSerializedSize()));
final String nextColumn = """";
write(nextColumn);
final String remoteAddr = session.getRemoteAddr();
if (remoteAddr == null) {
write("" "");
} else {
write(remoteAddr);
}
write(nextColumnAlignCenter);
writeCountry(session);
if (displayUser) {
write(nextColumn);
final String remoteUser = session.getRemoteUser();
if (remoteUser == null) {
write("" "");
} else {
writeDirectly(htmlEncodeButNotSpace(remoteUser));
}
}
write("" "");
write(A_HREF_PART_SESSIONS);
write(""&action=invalidate_session&sessionId="");
write(urlEncode(session.getId()));
write(""' onclick=\""javascript:return confirm('""
+ getStringForJavascript(""confirm_invalidate_session"") + ""');\"">"");
write("" "");
write("""");
write("" "");
}
"," private void writeSession(SessionInformations session, boolean displayUser) throws IOException {
final String nextColumnAlignRight = """";
final String nextColumnAlignCenter = "" "";
write("" "");
write(htmlEncodeButNotSpace(session.getId()));
write("" "");
write(nextColumnAlignRight);
write(durationFormat.format(session.getLastAccess()));
write(nextColumnAlignRight);
write(durationFormat.format(session.getAge()));
write(nextColumnAlignRight);
write(expiryFormat.format(session.getExpirationDate()));
write(nextColumnAlignRight);
write(integerFormat.format(session.getAttributeCount()));
write(nextColumnAlignCenter);
if (session.isSerializable()) {
write(""#oui#"");
} else {
write(""#non# "");
}
write(nextColumnAlignRight);
write(integerFormat.format(session.getSerializedSize()));
final String nextColumn = """";
write(nextColumn);
final String remoteAddr = session.getRemoteAddr();
if (remoteAddr == null) {
write("" "");
} else {
write(htmlEncodeButNotSpace(remoteAddr));
}
write(nextColumnAlignCenter);
writeCountry(session);
if (displayUser) {
write(nextColumn);
final String remoteUser = session.getRemoteUser();
if (remoteUser == null) {
write("" "");
} else {
writeDirectly(htmlEncodeButNotSpace(remoteUser));
}
}
write("" "");
write(A_HREF_PART_SESSIONS);
write(""&action=invalidate_session&sessionId="");
write(urlEncode(session.getId()));
write(""' onclick=\""javascript:return confirm('""
+ getStringForJavascript(""confirm_invalidate_session"") + ""');\"">"");
write("" "");
write("""");
write("" "");
}
",TRUE,HtmlSessionInformationsReport.java
" private void writeCountry(SessionInformations session) throws IOException {
final String country = session.getCountry();
if (country == null) {
write("" "");
} else {
final String fileName = ""flags/"" + country + "".gif"";
if (getClass().getResource(Parameters.getResourcePath(fileName)) == null) {
write(country);
} else {
write("" "");
}
}
}
"," private void writeCountry(SessionInformations session) throws IOException {
final String country = session.getCountry();
if (country == null) {
write("" "");
} else {
final String fileName = ""flags/"" + country + "".gif"";
if (getClass().getResource(Parameters.getResourcePath(fileName)) == null) {
write(country);
} else {
write("" "");
}
}
}
",FALSE,HtmlSessionInformationsReport.java
" void writeSessionDetails(String sessionId, SessionInformations sessionInformations)
throws IOException {
writeBackAndRefreshLinksForSession(sessionId);
writeln("" "");
if (sessionInformations == null) {
writeln(getFormattedString(""session_invalidee"", htmlEncodeButNotSpace(sessionId)));
return;
}
writeTitle(""system-users.png"",
getFormattedString(""Details_session"", htmlEncodeButNotSpace(sessionId)));
writeSessions(Collections.singletonList(sessionInformations));
writeln(""#Attributs# "");
writeSessionAttributes(sessionInformations);
}
"," void writeSessionDetails(String sessionId, SessionInformations sessionInformations)
throws IOException {
writeBackAndRefreshLinksForSession(sessionId);
writeln("" "");
if (sessionInformations == null) {
writeln(getFormattedString(""session_invalidee"", htmlEncodeButNotSpace(sessionId)));
return;
}
writeTitle(""system-users.png"",
getFormattedString(""Details_session"", htmlEncodeButNotSpace(sessionId)));
writeSessions(Collections.singletonList(sessionInformations));
writeln(""#Attributs# "");
writeSessionAttributes(sessionInformations);
}
",FALSE,HtmlSessionInformationsReport.java
" private void writeSessionAttributes(SessionInformations sessionInformations) throws IOException {
final HtmlTable table = new HtmlTable();
table.beginTable(getString(""Attributs""));
write(""#Nom# Type #Serialisable# #Taille_serialisee# #Contenu# "");
for (final SessionAttribute sessionAttribute : sessionInformations.getAttributes()) {
table.nextRow();
writeAttribute(sessionAttribute);
}
table.endTable();
}
"," private void writeSessionAttributes(SessionInformations sessionInformations) throws IOException {
final HtmlTable table = new HtmlTable();
table.beginTable(getString(""Attributs""));
write(""#Nom# Type #Serialisable# #Taille_serialisee# #Contenu# "");
for (final SessionAttribute sessionAttribute : sessionInformations.getAttributes()) {
table.nextRow();
writeAttribute(sessionAttribute);
}
table.endTable();
}
",FALSE,HtmlSessionInformationsReport.java
" private void writeAttribute(SessionAttribute sessionAttribute) throws IOException {
write("""");
writeDirectly(htmlEncodeButNotSpace(sessionAttribute.getName()));
write("" "");
write(String.valueOf(sessionAttribute.getType()));
write("" "");
if (sessionAttribute.isSerializable()) {
write(""#oui#"");
} else {
write(""#non# "");
}
write("" "");
write(integerFormat.format(sessionAttribute.getSerializedSize()));
write("" "");
writeDirectly(htmlEncodeButNotSpace(String.valueOf(sessionAttribute.getContent())));
write("" "");
}
"," private void writeAttribute(SessionAttribute sessionAttribute) throws IOException {
write("""");
writeDirectly(htmlEncodeButNotSpace(sessionAttribute.getName()));
write("" "");
write(String.valueOf(sessionAttribute.getType()));
write("" "");
if (sessionAttribute.isSerializable()) {
write(""#oui#"");
} else {
write(""#non# "");
}
write("" "");
write(integerFormat.format(sessionAttribute.getSerializedSize()));
write("" "");
writeDirectly(htmlEncodeButNotSpace(String.valueOf(sessionAttribute.getContent())));
write("" "");
}
",FALSE,HtmlSessionInformationsReport.java
" public I18nInterceptor() {
LOG.debug(""new I18nInterceptor()"");
}
"," public I18nInterceptor() {
LOG.debug(""new I18nInterceptor()"");
}
",FALSE,I18nInterceptor.java
" public void setParameterName(String parameterName) {
this.parameterName = parameterName;
}
"," public void setParameterName(String parameterName) {
this.parameterName = parameterName;
}
",FALSE,I18nInterceptor.java
" public void setRequestOnlyParameterName(String requestOnlyParameterName) {
this.requestOnlyParameterName = requestOnlyParameterName;
}
"," public void setRequestOnlyParameterName(String requestOnlyParameterName) {
this.requestOnlyParameterName = requestOnlyParameterName;
}
",FALSE,I18nInterceptor.java
" public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
"," public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
",FALSE,I18nInterceptor.java
" public String intercept(ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug(""Intercept '{}/{}' {"", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName());
}
LocaleFinder localeFinder = new LocaleFinder(invocation);
Locale locale = getLocaleFromParam(localeFinder.getRequestedLocale());
locale = storeLocale(invocation, locale, localeFinder.getStorage());
saveLocale(invocation, locale);
if (LOG.isDebugEnabled()) {
LOG.debug(""before Locale: {}"", invocation.getStack().findValue(""locale""));
}
final String result = invocation.invoke();
if (LOG.isDebugEnabled()) {
LOG.debug(""after Locale {}"", invocation.getStack().findValue(""locale""));
LOG.debug(""intercept } "");
}
return result;
}
"," public String intercept(ActionInvocation invocation) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug(""Intercept '{}/{}' {"", invocation.getProxy().getNamespace(), invocation.getProxy().getActionName());
}
LocaleFinder localeFinder = new LocaleFinder(invocation);
Locale locale = getLocaleFromParam(localeFinder.getRequestedLocale());
locale = storeLocale(invocation, locale, localeFinder.getStorage());
saveLocale(invocation, locale);
if (LOG.isDebugEnabled()) {
LOG.debug(""before Locale: {}"", invocation.getStack().findValue(""locale""));
}
final String result = invocation.invoke();
if (LOG.isDebugEnabled()) {
LOG.debug(""after Locale {}"", invocation.getStack().findValue(""locale""));
LOG.debug(""intercept } "");
}
return result;
}
",FALSE,I18nInterceptor.java
" protected Locale storeLocale(ActionInvocation invocation, Locale locale, String storage) {
//save it in session
Map session = invocation.getInvocationContext().getSession();
if (session != null) {
synchronized (session) {
if (locale == null) {
storage = Storage.NONE.toString();
locale = readStoredLocale(invocation, session);
}
if (Storage.SESSION.toString().equals(storage)) {
session.put(attributeName, locale);
}
}
}
return locale;
}
"," protected Locale storeLocale(ActionInvocation invocation, Locale locale, String storage) {
//save it in session
Map session = invocation.getInvocationContext().getSession();
if (session != null) {
synchronized (session) {
if (locale == null) {
storage = Storage.NONE.toString();
locale = readStoredLocale(invocation, session);
}
if (Storage.SESSION.toString().equals(storage)) {
session.put(attributeName, locale);
}
}
}
return locale;
}
",FALSE,I18nInterceptor.java
" protected LocaleFinder(ActionInvocation invocation) {
actionInvocation = invocation;
find();
}
"," protected LocaleFinder(ActionInvocation invocation) {
actionInvocation = invocation;
find();
}
",FALSE,I18nInterceptor.java
" protected void find() {
//get requested locale
Map params = actionInvocation.getInvocationContext().getParameters();
storage = Storage.SESSION.toString();
requestedLocale = findLocaleParameter(params, parameterName);
if (requestedLocale != null) {
return;
}
requestedLocale = findLocaleParameter(params, requestOnlyParameterName);
if (requestedLocale != null) {
storage = Storage.NONE.toString();
}
}
"," protected void find() {
//get requested locale
Map params = actionInvocation.getInvocationContext().getParameters();
storage = Storage.SESSION.toString();
requestedLocale = findLocaleParameter(params, parameterName);
if (requestedLocale != null) {
return;
}
requestedLocale = findLocaleParameter(params, requestOnlyParameterName);
if (requestedLocale != null) {
storage = Storage.NONE.toString();
}
}
",FALSE,I18nInterceptor.java
" public String getStorage() {
return storage;
}
"," public String getStorage() {
return storage;
}
",FALSE,I18nInterceptor.java
" public Object getRequestedLocale() {
return requestedLocale;
}
"," public Object getRequestedLocale() {
return requestedLocale;
}
",FALSE,I18nInterceptor.java
" protected Locale getLocaleFromParam(Object requestedLocale) {
Locale locale = null;
if (requestedLocale != null) {
locale = (requestedLocale instanceof Locale) ?
(Locale) requestedLocale :
LocalizedTextUtil.localeFromString(requestedLocale.toString(), null);
if (locale != null) {
LOG.debug(""Applied request locale: {}"", locale);
}
}
return locale;
"," protected Locale getLocaleFromParam(Object requestedLocale) {
Locale locale = null;
if (requestedLocale != null) {
locale = (requestedLocale instanceof Locale) ?
(Locale) requestedLocale :
LocalizedTextUtil.localeFromString(requestedLocale.toString(), null);
if (locale != null) {
LOG.debug(""Applied request locale: {}"", locale);
}
}
if (locale != null && !Arrays.asList(Locale.getAvailableLocales()).contains(locale)) {
locale = Locale.getDefault();
}
return locale;
}
",TRUE,I18nInterceptor.java
" */
protected Locale readStoredLocale(ActionInvocation invocation, Map session) {
Locale locale = this.readStoredLocalFromSession(invocation, session);
if (locale != null) {
return locale;
}
return this.readStoredLocalFromCurrentInvocation(invocation);
"," protected Locale readStoredLocale(ActionInvocation invocation, Map session) {
Locale locale = this.readStoredLocalFromSession(invocation, session);
if (locale != null) {
return locale;
}
return this.readStoredLocalFromCurrentInvocation(invocation);
}
",TRUE,I18nInterceptor.java
"
protected Locale readStoredLocalFromSession(ActionInvocation invocation, Map session) {
// check session for saved locale
Object sessionLocale = session.get(attributeName);
if (sessionLocale != null && sessionLocale instanceof Locale) {
Locale locale = (Locale) sessionLocale;
LOG.debug(""Applied session locale: {}"", locale);
return locale;
}
return null;
"," protected Locale readStoredLocalFromSession(ActionInvocation invocation, Map session) {
// check session for saved locale
Object sessionLocale = session.get(attributeName);
if (sessionLocale != null && sessionLocale instanceof Locale) {
Locale locale = (Locale) sessionLocale;
LOG.debug(""Applied session locale: {}"", locale);
return locale;
}
return null;
}
",TRUE,I18nInterceptor.java
"
protected Locale readStoredLocalFromCurrentInvocation(ActionInvocation invocation) {
// no overriding locale definition found, stay with current invocation (=browser) locale
Locale locale = invocation.getInvocationContext().getLocale();
if (locale != null) {
LOG.debug(""Applied invocation context locale: {}"", locale);
}
return locale;
"," protected Locale readStoredLocalFromCurrentInvocation(ActionInvocation invocation) {
// no overriding locale definition found, stay with current invocation (=browser) locale
Locale locale = invocation.getInvocationContext().getLocale();
if (locale != null) {
LOG.debug(""Applied invocation context locale: {}"", locale);
}
return locale;
}
",TRUE,I18nInterceptor.java
"
protected Object findLocaleParameter(Map params, String parameterName) {
Object requestedLocale = params.remove(parameterName);
if (requestedLocale != null && requestedLocale.getClass().isArray()
&& ((Object[]) requestedLocale).length > 0) {
requestedLocale = ((Object[]) requestedLocale)[0];
LOG.debug(""Requested locale: {}"", requestedLocale);
}
return requestedLocale;
"," protected Object findLocaleParameter(Map params, String parameterName) {
Object requestedLocale = params.remove(parameterName);
if (requestedLocale != null && requestedLocale.getClass().isArray()
&& ((Object[]) requestedLocale).length > 0) {
requestedLocale = ((Object[]) requestedLocale)[0];
LOG.debug(""Requested locale: {}"", requestedLocale);
}
return requestedLocale;
}
",TRUE,I18nInterceptor.java
" */
protected void saveLocale(ActionInvocation invocation, Locale locale) {
invocation.getInvocationContext().setLocale(locale);
"," protected void saveLocale(ActionInvocation invocation, Locale locale) {
invocation.getInvocationContext().setLocale(locale);
}
",TRUE,I18nInterceptor.java
"import static org.junit.Assert.assertTrue;
public class I18nInterceptorTest {
","import static org.junit.Assert.assertTrue;
public class I18nInterceptorTest {
",FALSE,I18nInterceptorTest.java
" private ActionInvocation mai;
private ActionContext ac;
private Map params;
private Map session;
"," private ActionInvocation mai;
private ActionContext ac;
private Map params;
private Map session;
",FALSE,I18nInterceptorTest.java
" @Before
public void setUp() throws Exception {
interceptor = new I18nInterceptor();
interceptor.init();
params = new HashMap();
session = new HashMap();
Map ctx = new HashMap();
ctx.put(ActionContext.PARAMETERS, params);
"," @Before
public void setUp() throws Exception {
interceptor = new I18nInterceptor();
interceptor.init();
params = new HashMap();
session = new HashMap();
Map ctx = new HashMap();
ctx.put(ActionContext.PARAMETERS, params);
",FALSE,I18nInterceptorTest.java
" ac = new ActionContext(ctx);
Action action = new Action() {
public String execute() throws Exception {
return SUCCESS;
}
};
mai = new MockActionInvocation();
((MockActionInvocation) mai).setAction(action);
((MockActionInvocation) mai).setInvocationContext(ac);
"," ac = new ActionContext(ctx);
Action action = new Action() {
public String execute() throws Exception {
return SUCCESS;
}
};
mai = new MockActionInvocation();
((MockActionInvocation) mai).setAction(action);
((MockActionInvocation) mai).setInvocationContext(ac);
",FALSE,I18nInterceptorTest.java
"
@After
public void tearDown() throws Exception {
interceptor.destroy();
interceptor = null;
ac = null;
params = null;
session = null;
mai = null;
}
","
@After
public void tearDown() throws Exception {
interceptor.destroy();
interceptor = null;
ac = null;
params = null;
session = null;
mai = null;
}
",FALSE,I18nInterceptorTest.java
" static class CookieMatcher implements IArgumentMatcher {
private Cookie expected;
CookieMatcher(Cookie cookie) {
expected = cookie;
}
public boolean matches(Object argument) {
Cookie cookie = ((Cookie) argument);
return
"," static class CookieMatcher implements IArgumentMatcher {
private Cookie expected;
CookieMatcher(Cookie cookie) {
expected = cookie;
}
public boolean matches(Object argument) {
Cookie cookie = ((Cookie) argument);
return
",FALSE,I18nInterceptorTest.java
" cookie.getValue().equals(expected.getValue()));
}
public static Cookie eqCookie(Cookie ck) {
EasyMock.reportMatcher(new CookieMatcher(ck));
return null;
}
public void appendTo(StringBuffer buffer) {
buffer
"," cookie.getValue().equals(expected.getValue()));
}
public static Cookie eqCookie(Cookie ck) {
EasyMock.reportMatcher(new CookieMatcher(ck));
return null;
}
public void appendTo(StringBuffer buffer) {
buffer
",FALSE,I18nInterceptorTest.java
" .append(expected.getName())
.append(""/"")
.append(expected.getValue());
}
}
@Test
public void testCookieCreation() throws Exception {
params.put(I18nInterceptor.DEFAULT_COOKIE_PARAMETER, ""da_DK"");
final Cookie cookie = new Cookie(I18nInterceptor.DEFAULT_COOKIE_ATTRIBUTE, ""da_DK"");
"," .append(expected.getName())
.append(""/"")
.append(expected.getValue());
}
}
@Test
public void testCookieCreation() throws Exception {
params.put(I18nInterceptor.DEFAULT_COOKIE_PARAMETER, ""da_DK"");
final Cookie cookie = new Cookie(I18nInterceptor.DEFAULT_COOKIE_ATTRIBUTE, ""da_DK"");
",FALSE,I18nInterceptorTest.java
" HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
response.addCookie(CookieMatcher.eqCookie(cookie));
EasyMock.replay(response);
ac.put(StrutsStatics.HTTP_RESPONSE, response);
interceptor.intercept(mai);
EasyMock.verify(response);
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
response.addCookie(CookieMatcher.eqCookie(cookie));
EasyMock.replay(response);
ac.put(StrutsStatics.HTTP_RESPONSE, response);
interceptor.intercept(mai);
EasyMock.verify(response);
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" @Test
public void testNoSession() throws Exception {
ac.setSession(null);
interceptor.intercept(mai);
}
@Test
public void testDefaultLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""_""); // bad locale that would get us default locale instead
"," @Test
public void testNoSession() throws Exception {
ac.setSession(null);
interceptor.intercept(mai);
}
@Test
public void testDefaultLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""_""); // bad locale that would get us default locale instead
",FALSE,I18nInterceptorTest.java
"
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.getDefault(), session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
@Test
public void testDenmarkLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
","
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.getDefault(), session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
@Test
public void testDenmarkLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
",FALSE,I18nInterceptorTest.java
" assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
@Test
public void testDenmarkLocaleRequestOnly() throws Exception {
params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
"," assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
@Test
public void testDenmarkLocaleRequestOnly() throws Exception {
params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
",FALSE,I18nInterceptorTest.java
"
Locale denmark = new Locale(""da"", ""DK"");
assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, mai.getInvocationContext().getLocale()); // should create a locale object
}
@Test
public void testCountryOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""DK"");
interceptor.intercept(mai);
","
Locale denmark = new Locale(""da"", ""DK"");
assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, mai.getInvocationContext().getLocale()); // should create a locale object
}
@Test
public void testCountryOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""NL"");
interceptor.intercept(mai);
",TRUE,I18nInterceptorTest.java
"
Locale denmark = new Locale(""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
@Test
public void testLanguageOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
","
Locale denmark = new Locale(""NL"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
@Test
public void testLanguageOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
",TRUE,I18nInterceptorTest.java
" @Test
public void testWithVariant() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""fr_CA_xx"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale variant = new Locale(""fr"", ""CA"", ""xx"");
"," @Test
public void testWithVariant() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""ja_JP_JP"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale variant = new Locale(""ja"", ""JP"", ""JP"");
",TRUE,I18nInterceptorTest.java
" public void setUp() throws Exception {
interceptor = new I18nInterceptor();
interceptor.init();
params = new HashMap();
session = new HashMap();
Map ctx = new HashMap();
ctx.put(ActionContext.PARAMETERS, params);
ctx.put(ActionContext.SESSION, session);
ac = new ActionContext(ctx);
Action action = new Action() {
public String execute() throws Exception {
return SUCCESS;
}
};
mai = new MockActionInvocation();
((MockActionInvocation) mai).setAction(action);
((MockActionInvocation) mai).setInvocationContext(ac);
}
"," public void setUp() throws Exception {
interceptor = new I18nInterceptor();
interceptor.init();
params = new HashMap();
session = new HashMap();
Map ctx = new HashMap();
ctx.put(ActionContext.PARAMETERS, params);
ctx.put(ActionContext.SESSION, session);
ac = new ActionContext(ctx);
Action action = new Action() {
public String execute() throws Exception {
return SUCCESS;
}
};
mai = new MockActionInvocation();
((MockActionInvocation) mai).setAction(action);
((MockActionInvocation) mai).setInvocationContext(ac);
}
",FALSE,I18nInterceptorTest.java
" public void tearDown() throws Exception {
interceptor.destroy();
interceptor = null;
ac = null;
params = null;
session = null;
mai = null;
}
"," public void tearDown() throws Exception {
interceptor.destroy();
interceptor = null;
ac = null;
params = null;
session = null;
mai = null;
}
",FALSE,I18nInterceptorTest.java
" CookieMatcher(Cookie cookie) {
expected = cookie;
}
"," CookieMatcher(Cookie cookie) {
expected = cookie;
}
",FALSE,I18nInterceptorTest.java
" public boolean matches(Object argument) {
Cookie cookie = ((Cookie) argument);
return
(cookie.getName().equals(expected.getName()) &&
cookie.getValue().equals(expected.getValue()));
}
"," public boolean matches(Object argument) {
Cookie cookie = ((Cookie) argument);
return
(cookie.getName().equals(expected.getName()) &&
cookie.getValue().equals(expected.getValue()));
}
",FALSE,I18nInterceptorTest.java
" public static Cookie eqCookie(Cookie ck) {
EasyMock.reportMatcher(new CookieMatcher(ck));
return null;
}
"," public static Cookie eqCookie(Cookie ck) {
EasyMock.reportMatcher(new CookieMatcher(ck));
return null;
}
",FALSE,I18nInterceptorTest.java
" public void appendTo(StringBuffer buffer) {
buffer
.append(""Received"")
.append(expected.getName())
.append(""/"")
.append(expected.getValue());
}
"," public void appendTo(StringBuffer buffer) {
buffer
.append(""Received"")
.append(expected.getName())
.append(""/"")
.append(expected.getValue());
}
",FALSE,I18nInterceptorTest.java
" public void testCookieCreation() throws Exception {
params.put(I18nInterceptor.DEFAULT_COOKIE_PARAMETER, ""da_DK"");
final Cookie cookie = new Cookie(I18nInterceptor.DEFAULT_COOKIE_ATTRIBUTE, ""da_DK"");
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
response.addCookie(CookieMatcher.eqCookie(cookie));
EasyMock.replay(response);
ac.put(StrutsStatics.HTTP_RESPONSE, response);
interceptor.intercept(mai);
EasyMock.verify(response);
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," public void testCookieCreation() throws Exception {
params.put(I18nInterceptor.DEFAULT_COOKIE_PARAMETER, ""da_DK"");
final Cookie cookie = new Cookie(I18nInterceptor.DEFAULT_COOKIE_ATTRIBUTE, ""da_DK"");
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
response.addCookie(CookieMatcher.eqCookie(cookie));
EasyMock.replay(response);
ac.put(StrutsStatics.HTTP_RESPONSE, response);
interceptor.intercept(mai);
EasyMock.verify(response);
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" public void testNoSession() throws Exception {
ac.setSession(null);
interceptor.intercept(mai);
}
"," public void testNoSession() throws Exception {
ac.setSession(null);
interceptor.intercept(mai);
}
",FALSE,I18nInterceptorTest.java
" public void testDefaultLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""_""); // bad locale that would get us default locale instead
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.getDefault(), session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," public void testDefaultLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""_""); // bad locale that would get us default locale instead
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.getDefault(), session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" public void testDenmarkLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," public void testDenmarkLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"", ""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" public void testDenmarkLocaleRequestOnly() throws Exception {
params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"", ""DK"");
assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, mai.getInvocationContext().getLocale()); // should create a locale object
}
"," public void testDenmarkLocaleRequestOnly() throws Exception {
params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""da_DK"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"", ""DK"");
assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, mai.getInvocationContext().getLocale()); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" public void testCountryOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""DK"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""DK"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," public void testCountryOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""NL"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""NL"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",TRUE,I18nInterceptorTest.java
" public void testLanguageOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," public void testLanguageOnlyLocale() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""da_"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale denmark = new Locale(""da"");
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(denmark, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" public void testWithVariant() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""fr_CA_xx"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale variant = new Locale(""fr"", ""CA"", ""xx"");
Locale locale = (Locale) session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE);
assertNotNull(locale); // should be stored here
assertEquals(variant, locale);
assertEquals(""xx"", locale.getVariant());
}
"," public void testWithVariant() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, ""ja_JP_JP"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
Locale variant = new Locale(""ja"", ""JP"", ""JP"");
Locale locale = (Locale) session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE);
assertNotNull(locale); // should be stored here
assertEquals(variant, locale);
assertEquals(""JP"", locale.getVariant());
}
",TRUE,I18nInterceptorTest.java
" public void testWithVariantRequestOnly() throws Exception {
params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""fr_CA_xx"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE));
Locale variant = new Locale(""fr"", ""CA"", ""xx"");
Locale locale = mai.getInvocationContext().getLocale();
assertNotNull(locale); // should be stored here
assertEquals(variant, locale);
assertEquals(""xx"", locale.getVariant());
}
"," public void testWithVariantRequestOnly() throws Exception {
params.put(I18nInterceptor.DEFAULT_REQUESTONLY_PARAMETER, ""ja_JP_JP"");
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE));
Locale variant = new Locale(""ja"", ""JP"", ""JP"");
Locale locale = mai.getInvocationContext().getLocale();
assertNotNull(locale); // should be stored here
assertEquals(variant, locale);
assertEquals(""JP"", locale.getVariant());
}
",TRUE,I18nInterceptorTest.java
" public void testRealLocaleObjectInParams() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, Locale.CANADA_FRENCH);
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.CANADA_FRENCH, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
"," public void testRealLocaleObjectInParams() throws Exception {
params.put(I18nInterceptor.DEFAULT_PARAMETER, Locale.CANADA_FRENCH);
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.CANADA_FRENCH, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should create a locale object
}
",FALSE,I18nInterceptorTest.java
" public void testRealLocalesInParams() throws Exception {
Locale[] locales = new Locale[]{Locale.CANADA_FRENCH};
assertTrue(locales.getClass().isArray());
params.put(I18nInterceptor.DEFAULT_PARAMETER, locales);
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.CANADA_FRENCH, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE));
}
"," public void testRealLocalesInParams() throws Exception {
Locale[] locales = new Locale[]{Locale.CANADA_FRENCH};
assertTrue(locales.getClass().isArray());
params.put(I18nInterceptor.DEFAULT_PARAMETER, locales);
interceptor.intercept(mai);
assertNull(params.get(I18nInterceptor.DEFAULT_PARAMETER)); // should have been removed
assertNotNull(session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE)); // should be stored here
assertEquals(Locale.CANADA_FRENCH, session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE));
}
",FALSE,I18nInterceptorTest.java
" public void testSetParameterAndAttributeNames() throws Exception {
interceptor.setAttributeName(""hello"");
interceptor.setParameterName(""world"");
params.put(""world"", Locale.CHINA);
interceptor.intercept(mai);
assertNull(params.get(""world"")); // should have been removed
assertNotNull(session.get(""hello"")); // should be stored here
assertEquals(Locale.CHINA, session.get(""hello""));
}
"," public void testSetParameterAndAttributeNames() throws Exception {
interceptor.setAttributeName(""hello"");
interceptor.setParameterName(""world"");
params.put(""world"", Locale.CHINA);
interceptor.intercept(mai);
assertNull(params.get(""world"")); // should have been removed
assertNotNull(session.get(""hello"")); // should be stored here
assertEquals(Locale.CHINA, session.get(""hello""));
}
",FALSE,I18nInterceptorTest.java
" public XmlFactory() { this(null, null, null); }
"," public XmlFactory() { this(null, null, null); }
",FALSE,XmlFactory.java
" public XmlFactory(ObjectCodec oc) {
this(oc, null, null);
}
"," public XmlFactory(ObjectCodec oc) {
this(oc, null, null);
}
",FALSE,XmlFactory.java
" public XmlFactory(XMLInputFactory xmlIn) {
this(null, xmlIn, null);
}
"," public XmlFactory(XMLInputFactory xmlIn) {
this(null, xmlIn, null);
}
",FALSE,XmlFactory.java
" public XmlFactory(XMLInputFactory xmlIn, XMLOutputFactory xmlOut) {
this(null, xmlIn, xmlOut);
}
"," public XmlFactory(XMLInputFactory xmlIn, XMLOutputFactory xmlOut) {
this(null, xmlIn, xmlOut);
}
",FALSE,XmlFactory.java
" public XmlFactory(ObjectCodec oc, XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
this(oc, DEFAULT_XML_PARSER_FEATURE_FLAGS, DEFAULT_XML_GENERATOR_FEATURE_FLAGS,
xmlIn, xmlOut, null);
}
"," public XmlFactory(ObjectCodec oc, XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
this(oc, DEFAULT_XML_PARSER_FEATURE_FLAGS, DEFAULT_XML_GENERATOR_FEATURE_FLAGS,
xmlIn, xmlOut, null);
}
",FALSE,XmlFactory.java
" protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures,
XMLInputFactory xmlIn, XMLOutputFactory xmlOut,
String nameForTextElem)
{
super(oc);
_xmlParserFeatures = xpFeatures;
_xmlGeneratorFeatures = xgFeatures;
_cfgNameForTextElement = nameForTextElem;
if (xmlIn == null) {
xmlIn = XMLInputFactory.newInstance();
}
if (xmlOut == null) {
xmlOut = XMLOutputFactory.newInstance();
}
_initFactories(xmlIn, xmlOut);
_xmlInputFactory = xmlIn;
_xmlOutputFactory = xmlOut;
}
"," protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures,
XMLInputFactory xmlIn, XMLOutputFactory xmlOut,
String nameForTextElem)
{
super(oc);
_xmlParserFeatures = xpFeatures;
_xmlGeneratorFeatures = xgFeatures;
_cfgNameForTextElement = nameForTextElem;
if (xmlIn == null) {
xmlIn = XMLInputFactory.newInstance();
// as per [dataformat-xml#190], disable external entity expansion by default
xmlIn.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
}
if (xmlOut == null) {
xmlOut = XMLOutputFactory.newInstance();
}
_initFactories(xmlIn, xmlOut);
_xmlInputFactory = xmlIn;
_xmlOutputFactory = xmlOut;
}
",TRUE,XmlFactory.java
" protected XmlFactory(XmlFactory src, ObjectCodec oc)
{
super(src, oc);
_xmlParserFeatures = src._xmlParserFeatures;
_xmlGeneratorFeatures = src._xmlGeneratorFeatures;
_cfgNameForTextElement = src._cfgNameForTextElement;
_xmlInputFactory = src._xmlInputFactory;
_xmlOutputFactory = src._xmlOutputFactory;
}
"," protected XmlFactory(XmlFactory src, ObjectCodec oc)
{
super(src, oc);
_xmlParserFeatures = src._xmlParserFeatures;
_xmlGeneratorFeatures = src._xmlGeneratorFeatures;
_cfgNameForTextElement = src._cfgNameForTextElement;
_xmlInputFactory = src._xmlInputFactory;
_xmlOutputFactory = src._xmlOutputFactory;
}
",FALSE,XmlFactory.java
" protected void _initFactories(XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
// Better ensure namespaces get built properly, so:
xmlOut.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
// and for parser, force coalescing as well (much simpler to use)
xmlIn.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
}
"," protected void _initFactories(XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
// Better ensure namespaces get built properly, so:
xmlOut.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
// and for parser, force coalescing as well (much simpler to use)
xmlIn.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
}
",FALSE,XmlFactory.java
" public XmlFactory copy() {
_checkInvalidCopy(XmlFactory.class);
return new XmlFactory(this, null);
}
"," public XmlFactory copy() {
_checkInvalidCopy(XmlFactory.class);
return new XmlFactory(this, null);
}
",FALSE,XmlFactory.java
" public Version version() {
return PackageVersion.VERSION;
}
"," public Version version() {
return PackageVersion.VERSION;
}
",FALSE,XmlFactory.java
" protected Object readResolve() {
if (_jdkXmlInFactory == null) {
throw new IllegalStateException(""No XMLInputFactory class name read during JDK deserialization"");
}
if (_jdkXmlOutFactory == null) {
throw new IllegalStateException(""No XMLOutputFactory class name read during JDK deserialization"");
}
try {
XMLInputFactory inf = (XMLInputFactory) Class.forName(_jdkXmlInFactory).newInstance();
XMLOutputFactory outf = (XMLOutputFactory) Class.forName(_jdkXmlOutFactory).newInstance();
return new XmlFactory(_objectCodec, _xmlParserFeatures, _xmlGeneratorFeatures,
inf, outf, _cfgNameForTextElement);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
"," protected Object readResolve() {
if (_jdkXmlInFactory == null) {
throw new IllegalStateException(""No XMLInputFactory class name read during JDK deserialization"");
}
if (_jdkXmlOutFactory == null) {
throw new IllegalStateException(""No XMLOutputFactory class name read during JDK deserialization"");
}
try {
XMLInputFactory inf = (XMLInputFactory) Class.forName(_jdkXmlInFactory).newInstance();
XMLOutputFactory outf = (XMLOutputFactory) Class.forName(_jdkXmlOutFactory).newInstance();
return new XmlFactory(_objectCodec, _xmlParserFeatures, _xmlGeneratorFeatures,
inf, outf, _cfgNameForTextElement);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
",FALSE,XmlFactory.java
" private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_jdkXmlInFactory = in.readUTF();
_jdkXmlOutFactory = in.readUTF();
}
"," private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_jdkXmlInFactory = in.readUTF();
_jdkXmlOutFactory = in.readUTF();
}
",FALSE,XmlFactory.java
" private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeUTF(_xmlInputFactory.getClass().getName());
out.writeUTF(_xmlOutputFactory.getClass().getName());
}
"," private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeUTF(_xmlInputFactory.getClass().getName());
out.writeUTF(_xmlOutputFactory.getClass().getName());
}
",FALSE,XmlFactory.java
" public void setXMLTextElementName(String name) {
_cfgNameForTextElement = name;
}
"," public void setXMLTextElementName(String name) {
_cfgNameForTextElement = name;
}
",FALSE,XmlFactory.java
" public String getXMLTextElementName() {
return _cfgNameForTextElement;
}
"," public String getXMLTextElementName() {
return _cfgNameForTextElement;
}
",FALSE,XmlFactory.java
" public final XmlFactory configure(FromXmlParser.Feature f, boolean state)
{
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
"," public final XmlFactory configure(FromXmlParser.Feature f, boolean state)
{
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory enable(FromXmlParser.Feature f) {
_xmlParserFeatures |= f.getMask();
return this;
}
"," public XmlFactory enable(FromXmlParser.Feature f) {
_xmlParserFeatures |= f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory disable(FromXmlParser.Feature f) {
_xmlParserFeatures &= ~f.getMask();
return this;
}
"," public XmlFactory disable(FromXmlParser.Feature f) {
_xmlParserFeatures &= ~f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public final boolean isEnabled(FromXmlParser.Feature f) {
return (_xmlParserFeatures & f.getMask()) != 0;
}
"," public final boolean isEnabled(FromXmlParser.Feature f) {
return (_xmlParserFeatures & f.getMask()) != 0;
}
",FALSE,XmlFactory.java
" public final XmlFactory configure(ToXmlGenerator.Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
"," public final XmlFactory configure(ToXmlGenerator.Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory enable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures |= f.getMask();
return this;
}
"," public XmlFactory enable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures |= f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory disable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures &= ~f.getMask();
return this;
}
"," public XmlFactory disable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures &= ~f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public final boolean isEnabled(ToXmlGenerator.Feature f) {
return (_xmlGeneratorFeatures & f.getMask()) != 0;
}
"," public final boolean isEnabled(ToXmlGenerator.Feature f) {
return (_xmlGeneratorFeatures & f.getMask()) != 0;
}
",FALSE,XmlFactory.java
" public XMLInputFactory getXMLInputFactory() {
return _xmlInputFactory;
}
"," public XMLInputFactory getXMLInputFactory() {
return _xmlInputFactory;
}
",FALSE,XmlFactory.java
" public void setXMLInputFactory(XMLInputFactory f) {
_xmlInputFactory = f;
}
"," public void setXMLInputFactory(XMLInputFactory f) {
_xmlInputFactory = f;
}
",FALSE,XmlFactory.java
" public XMLOutputFactory getXMLOutputFactory() {
return _xmlOutputFactory;
}
"," public XMLOutputFactory getXMLOutputFactory() {
return _xmlOutputFactory;
}
",FALSE,XmlFactory.java
" public void setXMLOutputFactory(XMLOutputFactory f) {
_xmlOutputFactory = f;
}
"," public void setXMLOutputFactory(XMLOutputFactory f) {
_xmlOutputFactory = f;
}
",FALSE,XmlFactory.java
" public String getFormatName() {
return FORMAT_NAME_XML;
}
"," public String getFormatName() {
return FORMAT_NAME_XML;
}
",FALSE,XmlFactory.java
" public MatchStrength hasFormat(InputAccessor acc) throws IOException {
return hasXMLFormat(acc);
}
"," public MatchStrength hasFormat(InputAccessor acc) throws IOException {
return hasXMLFormat(acc);
}
",FALSE,XmlFactory.java
" public boolean requiresCustomCodec() { return true; }
"," public boolean requiresCustomCodec() { return true; }
",FALSE,XmlFactory.java
" public boolean canUseCharArrays() { return false; }
"," public boolean canUseCharArrays() { return false; }
",FALSE,XmlFactory.java
" public Class getFormatReadFeatureType() {
return FromXmlParser.Feature.class;
}
"," public Class getFormatReadFeatureType() {
return FromXmlParser.Feature.class;
}
",FALSE,XmlFactory.java
" public Class getFormatWriteFeatureType() {
return ToXmlGenerator.Feature.class;
}
"," public Class getFormatWriteFeatureType() {
return ToXmlGenerator.Feature.class;
}
",FALSE,XmlFactory.java
" public JsonParser createParser(String content) throws IOException {
Reader r = new StringReader(content);
IOContext ctxt = _createContext(r, true);
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
"," public JsonParser createParser(String content) throws IOException {
Reader r = new StringReader(content);
IOContext ctxt = _createContext(r, true);
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(OutputStream out) throws IOException {
return createGenerator(out, JsonEncoding.UTF8);
}
"," public ToXmlGenerator createGenerator(OutputStream out) throws IOException {
return createGenerator(out, JsonEncoding.UTF8);
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ctxt = _createContext(out, false);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt,
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
"," public ToXmlGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ctxt = _createContext(out, false);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt,
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(Writer out) throws IOException
{
return new ToXmlGenerator(_createContext(out, false),
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
"," public ToXmlGenerator createGenerator(Writer out) throws IOException
{
return new ToXmlGenerator(_createContext(out, false),
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(File f, JsonEncoding enc) throws IOException
{
OutputStream out = new FileOutputStream(f);
// true -> yes, we have to manage the stream since we created it
IOContext ctxt = _createContext(out, true);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
"," public ToXmlGenerator createGenerator(File f, JsonEncoding enc) throws IOException
{
OutputStream out = new FileOutputStream(f);
// true -> yes, we have to manage the stream since we created it
IOContext ctxt = _createContext(out, true);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
",FALSE,XmlFactory.java
" public FromXmlParser createParser(XMLStreamReader sr) throws IOException
{
// note: should NOT move parser if already pointing to START_ELEMENT
if (sr.getEventType() != XMLStreamConstants.START_ELEMENT) {
try {
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
// false -> not managed
FromXmlParser xp = new FromXmlParser(_createContext(sr, false),
_generatorFeatures, _xmlGeneratorFeatures, _objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," public FromXmlParser createParser(XMLStreamReader sr) throws IOException
{
// note: should NOT move parser if already pointing to START_ELEMENT
if (sr.getEventType() != XMLStreamConstants.START_ELEMENT) {
try {
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
// false -> not managed
FromXmlParser xp = new FromXmlParser(_createContext(sr, false),
_generatorFeatures, _xmlGeneratorFeatures, _objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(XMLStreamWriter sw) throws IOException
{
try {
sw = _initializeXmlWriter(sw);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
IOContext ctxt = _createContext(sw, false);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sw);
}
"," public ToXmlGenerator createGenerator(XMLStreamWriter sw) throws IOException
{
try {
sw = _initializeXmlWriter(sw);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
IOContext ctxt = _createContext(sw, false);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sw);
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(InputStream in, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(in);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(InputStream in, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(in);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(Reader r, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(r);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(Reader r, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(r);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(char[] data, int offset, int len, IOContext ctxt,
boolean recycleBuffer) throws IOException
{
// !!! TODO: add proper handling of 'recycleBuffer'; currently its handling
// is always same as if 'false' was passed
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2CharArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(char[] data, int offset, int len, IOContext ctxt,
boolean recycleBuffer) throws IOException
{
// !!! TODO: add proper handling of 'recycleBuffer'; currently its handling
// is always same as if 'false' was passed
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2CharArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2ByteArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2ByteArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
// this method should never get called here, so:
VersionUtil.throwInternal();
return null;
}
"," protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
// this method should never get called here, so:
VersionUtil.throwInternal();
return null;
}
",FALSE,XmlFactory.java
" protected XMLStreamWriter _createXmlWriter(OutputStream out) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(out, ""UTF-8""));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
"," protected XMLStreamWriter _createXmlWriter(OutputStream out) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(out, ""UTF-8""));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
",FALSE,XmlFactory.java
" protected XMLStreamWriter _createXmlWriter(Writer w) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(w));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
"," protected XMLStreamWriter _createXmlWriter(Writer w) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(w));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
",FALSE,XmlFactory.java
" protected final XMLStreamWriter _initializeXmlWriter(XMLStreamWriter sw) throws IOException, XMLStreamException
{
// And just for Sun Stax parser (JDK default), seems that we better define default namespace
// (Woodstox doesn't care) -- otherwise it'll add unnecessary odd declaration
sw.setDefaultNamespace("""");
return sw;
}
"," protected final XMLStreamWriter _initializeXmlWriter(XMLStreamWriter sw) throws IOException, XMLStreamException
{
// And just for Sun Stax parser (JDK default), seems that we better define default namespace
// (Woodstox doesn't care) -- otherwise it'll add unnecessary odd declaration
sw.setDefaultNamespace("""");
return sw;
}
",FALSE,XmlFactory.java
" protected final XMLStreamReader _initializeXmlReader(XMLStreamReader sr) throws IOException, XMLStreamException
{
// for now, nothing to do... except let's find the root element
while (sr.next() != XMLStreamConstants.START_ELEMENT) {
;
}
return sr;
}
"," protected final XMLStreamReader _initializeXmlReader(XMLStreamReader sr) throws IOException, XMLStreamException
{
// for now, nothing to do... except let's find the root element
while (sr.next() != XMLStreamConstants.START_ELEMENT) {
;
}
return sr;
}
",FALSE,XmlFactory.java
" public static MatchStrength hasXMLFormat(InputAccessor acc) throws IOException
{
/* Basically we just need to find "" or , since
* can NOT come outside of root
*/
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
b = acc.nextByte();
if (b == BYTE_HYPHEN) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() == BYTE_HYPHEN) {
return MatchStrength.SOLID_MATCH;
}
} else if (b == BYTE_D) {
return tryMatch(acc, ""OCTYPE"", MatchStrength.SOLID_MATCH);
}
} else {
// maybe root element? Just needs to match first char.
if (validXmlNameStartChar(acc, b)) {
return MatchStrength.SOLID_MATCH;
}
}
return MatchStrength.NO_MATCH;
}
"," public static MatchStrength hasXMLFormat(InputAccessor acc) throws IOException
{
/* Basically we just need to find "" or , since
* can NOT come outside of root
*/
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
b = acc.nextByte();
if (b == BYTE_HYPHEN) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() == BYTE_HYPHEN) {
return MatchStrength.SOLID_MATCH;
}
} else if (b == BYTE_D) {
return tryMatch(acc, ""OCTYPE"", MatchStrength.SOLID_MATCH);
}
} else {
// maybe root element? Just needs to match first char.
if (validXmlNameStartChar(acc, b)) {
return MatchStrength.SOLID_MATCH;
}
}
return MatchStrength.NO_MATCH;
}
",FALSE,XmlFactory.java
" private final static boolean validXmlNameStartChar(InputAccessor acc, byte b)
throws IOException
{
/* Can make it actual real XML check in future; for now we do just crude
* check for ASCII range
*/
int ch = (int) b & 0xFF;
if (ch >= 'A') { // in theory, colon could be; in practice it should never be valid (wrt namespace)
// This is where we'd check for multi-byte UTF-8 chars (or whatever encoding is in use)...
return true;
}
return false;
}
"," private final static boolean validXmlNameStartChar(InputAccessor acc, byte b)
throws IOException
{
/* Can make it actual real XML check in future; for now we do just crude
* check for ASCII range
*/
int ch = (int) b & 0xFF;
if (ch >= 'A') { // in theory, colon could be; in practice it should never be valid (wrt namespace)
// This is where we'd check for multi-byte UTF-8 chars (or whatever encoding is in use)...
return true;
}
return false;
}
",FALSE,XmlFactory.java
" private final static MatchStrength tryMatch(InputAccessor acc, String matchStr, MatchStrength fullMatchStrength)
throws IOException
{
for (int i = 0, len = matchStr.length(); i < len; ++i) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() != matchStr.charAt(i)) {
return MatchStrength.NO_MATCH;
}
}
return fullMatchStrength;
}
"," private final static MatchStrength tryMatch(InputAccessor acc, String matchStr, MatchStrength fullMatchStrength)
throws IOException
{
for (int i = 0, len = matchStr.length(); i < len; ++i) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() != matchStr.charAt(i)) {
return MatchStrength.NO_MATCH;
}
}
return fullMatchStrength;
}
",FALSE,XmlFactory.java
" private final static int skipSpace(InputAccessor acc, byte b) throws IOException
{
while (true) {
int ch = (int) b & 0xFF;
if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
return ch;
}
if (!acc.hasMoreBytes()) {
return -1;
}
b = acc.nextByte();
ch = (int) b & 0xFF;
}
}
"," private final static int skipSpace(InputAccessor acc, byte b) throws IOException
{
while (true) {
int ch = (int) b & 0xFF;
if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
return ch;
}
if (!acc.hasMoreBytes()) {
return -1;
}
b = acc.nextByte();
ch = (int) b & 0xFF;
}
}
",FALSE,XmlFactory.java
" public AddOperation(String path, Object value) {
super(""add"", path, value);
}
"," public AddOperation(String path, Object value) {
super(""add"", path, value);
}
",FALSE,AddOperation.java
" void perform(Object targetObject, Class type) {
addValue(targetObject, evaluateValueFromTarget(targetObject, type));
}
"," void perform(Object targetObject, Class type) {
addValue(targetObject, evaluateValueFromTarget(targetObject, type));
}
",FALSE,AddOperation.java
" protected Object evaluateValueFromTarget(Object targetObject, Class entityType) {
if (!path.endsWith(""-"")) {
return super.evaluateValueFromTarget(targetObject, entityType);
}
String pathSource = Arrays.stream(path.split(""/""))//
.filter(it -> !it.matches(""\\d"")) // no digits
.filter(it -> !it.equals(""-"")) // no ""last element""s
.filter(it -> !it.isEmpty()) //
.collect(Collectors.joining("".""));
PropertyPath propertyPath = PropertyPath.from(pathSource, entityType);
return value instanceof LateObjectEvaluator ? ((LateObjectEvaluator) value).evaluate(propertyPath.getType())
: value;
}
"," protected Object evaluateValueFromTarget(Object targetObject, Class entityType) {
if (!path.endsWith(""-"")) {
return super.evaluateValueFromTarget(targetObject, entityType);
}
return evaluate(verifyPath(entityType).> map(it -> it.getType()).orElse(entityType));
}
",TRUE,AddOperation.java
" public PatchOperation(String op, String path) {
this(op, path, null);
}
"," public PatchOperation(String op, String path) {
this(op, path, null);
}
",FALSE,PatchOperation.java
" public PatchOperation(String op, String path, Object value) {
this.op = op;
this.path = path;
this.value = value;
this.spelExpression = pathToExpression(path);
}
"," public PatchOperation(String op, String path, Object value) {
this.op = op;
this.path = path;
this.value = value;
this.spelExpression = pathToExpression(path);
}
",FALSE,PatchOperation.java
" public String getOp() {
return op;
}
"," public String getOp() {
return op;
}
",FALSE,PatchOperation.java
" public String getPath() {
return path;
}
"," public String getPath() {
return path;
}
",FALSE,PatchOperation.java
" public Object getValue() {
return value;
}
"," public Object getValue() {
return value;
}
",FALSE,PatchOperation.java
" protected Object popValueAtPath(Object target, String removePath) {
Integer listIndex = targetListIndex(removePath);
Expression expression = pathToExpression(removePath);
Object value = expression.getValue(target);
if (listIndex == null) {
try {
expression.setValue(target, null);
return value;
} catch (SpelEvaluationException o_O) {
throw new PatchException(""Path '"" + removePath + ""' is not nullable."", o_O);
}
} else {
Expression parentExpression = pathToParentExpression(removePath);
List> list = (List>) parentExpression.getValue(target);
list.remove(listIndex >= 0 ? listIndex.intValue() : list.size() - 1);
return value;
}
}
"," protected Object popValueAtPath(Object target, String removePath) {
Integer listIndex = targetListIndex(removePath);
Expression expression = pathToExpression(removePath);
Object value = expression.getValue(target);
if (listIndex == null) {
try {
expression.setValue(target, null);
return value;
} catch (SpelEvaluationException o_O) {
throw new PatchException(""Path '"" + removePath + ""' is not nullable."", o_O);
}
} else {
Expression parentExpression = pathToParentExpression(removePath);
List> list = (List>) parentExpression.getValue(target);
list.remove(listIndex >= 0 ? listIndex.intValue() : list.size() - 1);
return value;
}
}
",FALSE,PatchOperation.java
" protected void addValue(Object target, Object value) {
Expression parentExpression = pathToParentExpression(path);
Object parent = parentExpression != null ? parentExpression.getValue(target) : null;
Integer listIndex = targetListIndex(path);
if (parent == null || !(parent instanceof List) || listIndex == null) {
TypeDescriptor descriptor = parentExpression.getValueTypeDescriptor(target);
// Set as new collection if necessary
if (descriptor.isCollection() && !Collection.class.isInstance(value)) {
Collection collection = CollectionFactory.createCollection(descriptor.getType(), 1);
collection.add(value);
parentExpression.setValue(target, collection);
} else {
spelExpression.setValue(target, value);
}
} else {
List list = (List) parentExpression.getValue(target);
list.add(listIndex >= 0 ? listIndex.intValue() : list.size(), value);
}
}
"," protected void addValue(Object target, Object value) {
Expression parentExpression = pathToParentExpression(path);
Object parent = parentExpression != null ? parentExpression.getValue(target) : null;
Integer listIndex = targetListIndex(path);
if (parent == null || !(parent instanceof List) || listIndex == null) {
TypeDescriptor descriptor = parentExpression.getValueTypeDescriptor(target);
// Set as new collection if necessary
if (descriptor.isCollection() && !Collection.class.isInstance(value)) {
Collection collection = CollectionFactory.createCollection(descriptor.getType(), 1);
collection.add(value);
parentExpression.setValue(target, collection);
} else {
spelExpression.setValue(target, value);
}
} else {
List list = (List) parentExpression.getValue(target);
list.add(listIndex >= 0 ? listIndex.intValue() : list.size(), value);
}
}
",FALSE,PatchOperation.java
" protected void setValueOnTarget(Object target, Object value) {
spelExpression.setValue(target, value);
}
"," protected void setValueOnTarget(Object target, Object value) {
spelExpression.setValue(target, value);
}
",FALSE,PatchOperation.java
" protected Object getValueFromTarget(Object target) {
try {
return spelExpression.getValue(target);
} catch (ExpressionException e) {
throw new PatchException(""Unable to get value from target"", e);
}
}
"," protected Object getValueFromTarget(Object target) {
try {
return spelExpression.getValue(target);
} catch (ExpressionException e) {
throw new PatchException(""Unable to get value from target"", e);
}
}
",FALSE,PatchOperation.java
" protected Object evaluateValueFromTarget(Object targetObject, Class entityType) {
return value instanceof LateObjectEvaluator
? ((LateObjectEvaluator) value).evaluate(spelExpression.getValueType(targetObject)) : value;
}
"," protected Object evaluateValueFromTarget(Object targetObject, Class entityType) {
verifyPath(entityType);
return evaluate(spelExpression.getValueType(targetObject));
}
",TRUE,PatchOperation.java
" }
"," protected final Object evaluate(Class type) {
return value instanceof LateObjectEvaluator ? ((LateObjectEvaluator) value).evaluate(type) : value;
}
",TRUE,PatchOperation.java
" }
"," protected final Optional verifyPath(Class> type) {
String pathSource = Arrays.stream(path.split(""/""))//
.filter(it -> !it.matches(""\\d"")) // no digits
.filter(it -> !it.equals(""-"")) // no ""last element""s
.filter(it -> !it.isEmpty()) //
.collect(Collectors.joining("".""));
if (pathSource.isEmpty()) {
return Optional.empty();
}
try {
return Optional.of(PropertyPath.from(pathSource, type));
} catch (PropertyReferenceException o_O) {
throw new PatchException(String.format(INVALID_PATH_REFERENCE, pathSource, type, path), o_O);
}
}
",TRUE,PatchOperation.java
" private Integer targetListIndex(String path) {
String[] pathNodes = path.split(""\\/"");
String lastNode = pathNodes[pathNodes.length - 1];
if (APPEND_CHARACTERS.contains(lastNode)) {
return -1;
}
try {
return Integer.parseInt(lastNode);
} catch (NumberFormatException e) {
return null;
}
}
"," private Integer targetListIndex(String path) {
String[] pathNodes = path.split(""\\/"");
String lastNode = pathNodes[pathNodes.length - 1];
if (APPEND_CHARACTERS.contains(lastNode)) {
return -1;
}
try {
return Integer.parseInt(lastNode);
} catch (NumberFormatException e) {
return null;
}
}
",FALSE,PatchOperation.java
" public void manySuccessfulOperations() throws Exception {
List todos = new ArrayList();
todos.add(new Todo(1L, ""A"", true));
todos.add(new Todo(2L, ""B"", false));
todos.add(new Todo(3L, ""C"", false));
todos.add(new Todo(4L, ""D"", false));
todos.add(new Todo(5L, ""E"", false));
todos.add(new Todo(6L, ""F"", false));
Patch patch = readJsonPatch(""patch-many-successful-operations.json"");
assertEquals(6, patch.size());
List patchedTodos = patch.apply(todos, Todo.class);
assertEquals(6, todos.size());
assertTrue(patchedTodos.get(1).isComplete());
assertEquals(""C"", patchedTodos.get(3).getDescription());
assertEquals(""A"", patchedTodos.get(4).getDescription());
}
"," public void manySuccessfulOperations() throws Exception {
List todos = new ArrayList();
todos.add(new Todo(1L, ""A"", true));
todos.add(new Todo(2L, ""B"", false));
todos.add(new Todo(3L, ""C"", false));
todos.add(new Todo(4L, ""D"", false));
todos.add(new Todo(5L, ""E"", false));
todos.add(new Todo(6L, ""F"", false));
Patch patch = readJsonPatch(""patch-many-successful-operations.json"");
assertEquals(6, patch.size());
List patchedTodos = patch.apply(todos, Todo.class);
assertEquals(6, todos.size());
assertTrue(patchedTodos.get(1).isComplete());
assertEquals(""C"", patchedTodos.get(3).getDescription());
assertEquals(""A"", patchedTodos.get(4).getDescription());
}
",FALSE,JsonPatchTests.java
" public void failureAtBeginning() throws Exception {
List todos = new ArrayList();
todos.add(new Todo(1L, ""A"", true));
todos.add(new Todo(2L, ""B"", false));
todos.add(new Todo(3L, ""C"", false));
todos.add(new Todo(4L, ""D"", false));
todos.add(new Todo(5L, ""E"", false));
todos.add(new Todo(6L, ""F"", false));
Patch patch = readJsonPatch(""patch-failing-operation-first.json"");
try {
patch.apply(todos, Todo.class);
fail();
} catch (PatchException e) {
assertEquals(""Test against path '/5/description' failed."", e.getMessage());
}
assertEquals(6, todos.size());
assertFalse(todos.get(1).isComplete());
assertEquals(""D"", todos.get(3).getDescription());
assertEquals(""E"", todos.get(4).getDescription());
assertEquals(""F"", todos.get(5).getDescription());
}
"," public void failureAtBeginning() throws Exception {
List todos = new ArrayList();
todos.add(new Todo(1L, ""A"", true));
todos.add(new Todo(2L, ""B"", false));
todos.add(new Todo(3L, ""C"", false));
todos.add(new Todo(4L, ""D"", false));
todos.add(new Todo(5L, ""E"", false));
todos.add(new Todo(6L, ""F"", false));
Patch patch = readJsonPatch(""patch-failing-operation-first.json"");
try {
patch.apply(todos, Todo.class);
fail();
} catch (PatchException e) {
assertEquals(""Test against path '/5/description' failed."", e.getMessage());
}
assertEquals(6, todos.size());
assertFalse(todos.get(1).isComplete());
assertEquals(""D"", todos.get(3).getDescription());
assertEquals(""E"", todos.get(4).getDescription());
assertEquals(""F"", todos.get(5).getDescription());
}
",FALSE,JsonPatchTests.java
" public void failureInMiddle() throws Exception {
List todos = new ArrayList();
todos.add(new Todo(1L, ""A"", true));
todos.add(new Todo(2L, ""B"", false));
todos.add(new Todo(3L, ""C"", false));
todos.add(new Todo(4L, ""D"", false));
todos.add(new Todo(5L, ""E"", false));
todos.add(new Todo(6L, ""F"", false));
Patch patch = readJsonPatch(""patch-failing-operation-in-middle.json"");
try {
patch.apply(todos, Todo.class);
fail();
} catch (PatchException e) {
assertEquals(""Test against path '/5/description' failed."", e.getMessage());
}
assertEquals(6, todos.size());
assertFalse(todos.get(1).isComplete());
assertEquals(""D"", todos.get(3).getDescription());
assertEquals(""E"", todos.get(4).getDescription());
assertEquals(""F"", todos.get(5).getDescription());
}
"," public void failureInMiddle() throws Exception {
List todos = new ArrayList();
todos.add(new Todo(1L, ""A"", true));
todos.add(new Todo(2L, ""B"", false));
todos.add(new Todo(3L, ""C"", false));
todos.add(new Todo(4L, ""D"", false));
todos.add(new Todo(5L, ""E"", false));
todos.add(new Todo(6L, ""F"", false));
Patch patch = readJsonPatch(""patch-failing-operation-in-middle.json"");
try {
patch.apply(todos, Todo.class);
fail();
} catch (PatchException e) {
assertEquals(""Test against path '/5/description' failed."", e.getMessage());
}
assertEquals(6, todos.size());
assertFalse(todos.get(1).isComplete());
assertEquals(""D"", todos.get(3).getDescription());
assertEquals(""E"", todos.get(4).getDescription());
assertEquals(""F"", todos.get(5).getDescription());
}
",FALSE,JsonPatchTests.java
" public void patchArray() throws Exception {
Todo todo = new Todo(1L, ""F"", false);
Patch patch = readJsonPatch(""patch-array.json"");
assertEquals(1, patch.size());
Todo patchedTodo = patch.apply(todo, Todo.class);
assertEquals(Arrays.asList(""one"", ""two"", ""three""), patchedTodo.getItems());
}
"," public void patchArray() throws Exception {
Todo todo = new Todo(1L, ""F"", false);
Patch patch = readJsonPatch(""patch-array.json"");
assertEquals(1, patch.size());
Todo patchedTodo = patch.apply(todo, Todo.class);
assertEquals(Arrays.asList(""one"", ""two"", ""three""), patchedTodo.getItems());
}
",FALSE,JsonPatchTests.java
" public void patchUnknownType() throws Exception {
Todo todo = new Todo();
todo.setAmount(BigInteger.ONE);
exception.expect(PatchException.class);
exception.expectMessage(""/amount"");
exception.expectMessage(""18446744073709551616"");
readJsonPatch(""patch-biginteger.json"");
}
"," public void patchUnknownType() throws Exception {
Todo todo = new Todo();
todo.setAmount(BigInteger.ONE);
exception.expect(PatchException.class);
exception.expectMessage(""/amount"");
exception.expectMessage(""18446744073709551616"");
readJsonPatch(""patch-biginteger.json"");
}
",FALSE,JsonPatchTests.java
" public void failureWithInvalidPatchContent() throws Exception {
Todo todo = new Todo();
todo.setDescription(""Description"");
Patch patch = readJsonPatch(""patch-failing-with-invalid-content.json"");
exception.expect(PatchException.class);
exception.expectMessage(""content"");
exception.expectMessage(""blabla"");
exception.expectMessage(String.class.toString());
patch.apply(todo, Todo.class);
}
"," public void failureWithInvalidPatchContent() throws Exception {
Todo todo = new Todo();
todo.setDescription(""Description"");
Patch patch = readJsonPatch(""patch-failing-with-invalid-content.json"");
exception.expect(PatchException.class);
exception.expectMessage(""content"");
exception.expectMessage(""blabla"");
exception.expectMessage(String.class.toString());
patch.apply(todo, Todo.class);
}
",FALSE,JsonPatchTests.java
" }
"," public void rejectsInvalidPaths() throws Exception {
readJsonPatch(""patch-invalid-path.json"").apply(new Todo(), Todo.class);
}
",TRUE,JsonPatchTests.java
" private Patch readJsonPatch(String jsonPatchFile) throws IOException, JsonParseException, JsonMappingException {
ClassPathResource resource = new ClassPathResource(jsonPatchFile, getClass());
JsonNode node = new ObjectMapper().readValue(resource.getInputStream(), JsonNode.class);
Patch patch = new JsonPatchPatchConverter(new ObjectMapper()).convert(node);
return patch;
}
"," private Patch readJsonPatch(String jsonPatchFile) throws IOException, JsonParseException, JsonMappingException {
ClassPathResource resource = new ClassPathResource(jsonPatchFile, getClass());
JsonNode node = new ObjectMapper().readValue(resource.getInputStream(), JsonNode.class);
Patch patch = new JsonPatchPatchConverter(new ObjectMapper()).convert(node);
return patch;
}
",FALSE,JsonPatchTests.java
" public URIBuilder() {
super();
this.port = -1;
}
"," public URIBuilder() {
super();
this.port = -1;
}
",FALSE,URIBuilder.java
" public URIBuilder(final String string) throws URISyntaxException {
super();
digestURI(new URI(string));
}
"," public URIBuilder(final String string) throws URISyntaxException {
super();
digestURI(new URI(string));
}
",FALSE,URIBuilder.java
" public URIBuilder(final URI uri) {
super();
digestURI(uri);
}
"," public URIBuilder(final URI uri) {
super();
digestURI(uri);
}
",FALSE,URIBuilder.java
" public URIBuilder setCharset(final Charset charset) {
this.charset = charset;
return this;
}
"," public URIBuilder setCharset(final Charset charset) {
this.charset = charset;
return this;
}
",FALSE,URIBuilder.java
" public Charset getCharset() {
return charset;
}
"," public Charset getCharset() {
return charset;
}
",FALSE,URIBuilder.java
" private List parseQuery(final String query, final Charset charset) {
if (query != null && !query.isEmpty()) {
return URLEncodedUtils.parse(query, charset);
}
return null;
}
"," private List parseQuery(final String query, final Charset charset) {
if (query != null && !query.isEmpty()) {
return URLEncodedUtils.parse(query, charset);
}
return null;
}
",FALSE,URIBuilder.java
" public URI build() throws URISyntaxException {
return new URI(buildString());
}
"," public URI build() throws URISyntaxException {
return new URI(buildString());
}
",FALSE,URIBuilder.java
" private String buildString() {
final StringBuilder sb = new StringBuilder();
if (this.scheme != null) {
sb.append(this.scheme).append(':');
}
if (this.encodedSchemeSpecificPart != null) {
sb.append(this.encodedSchemeSpecificPart);
} else {
if (this.encodedAuthority != null) {
sb.append(""//"").append(this.encodedAuthority);
} else if (this.host != null) {
sb.append(""//"");
if (this.encodedUserInfo != null) {
sb.append(this.encodedUserInfo).append(""@"");
} else if (this.userInfo != null) {
sb.append(encodeUserInfo(this.userInfo)).append(""@"");
}
if (InetAddressUtils.isIPv6Address(this.host)) {
sb.append(""["").append(this.host).append(""]"");
} else {
sb.append(this.host);
}
if (this.port >= 0) {
sb.append("":"").append(this.port);
}
}
if (this.encodedPath != null) {
sb.append(normalizePath(this.encodedPath));
} else if (this.path != null) {
sb.append(encodePath(normalizePath(this.path)));
}
if (this.encodedQuery != null) {
sb.append(""?"").append(this.encodedQuery);
} else if (this.queryParams != null) {
sb.append(""?"").append(encodeUrlForm(this.queryParams));
} else if (this.query != null) {
sb.append(""?"").append(encodeUric(this.query));
}
}
if (this.encodedFragment != null) {
sb.append(""#"").append(this.encodedFragment);
} else if (this.fragment != null) {
sb.append(""#"").append(encodeUric(this.fragment));
}
return sb.toString();
}
"," private String buildString() {
final StringBuilder sb = new StringBuilder();
if (this.scheme != null) {
sb.append(this.scheme).append(':');
}
if (this.encodedSchemeSpecificPart != null) {
sb.append(this.encodedSchemeSpecificPart);
} else {
if (this.encodedAuthority != null) {
sb.append(""//"").append(this.encodedAuthority);
} else if (this.host != null) {
sb.append(""//"");
if (this.encodedUserInfo != null) {
sb.append(this.encodedUserInfo).append(""@"");
} else if (this.userInfo != null) {
sb.append(encodeUserInfo(this.userInfo)).append(""@"");
}
if (InetAddressUtils.isIPv6Address(this.host)) {
sb.append(""["").append(this.host).append(""]"");
} else {
sb.append(this.host);
}
if (this.port >= 0) {
sb.append("":"").append(this.port);
}
}
if (this.encodedPath != null) {
sb.append(normalizePath(this.encodedPath));
} else if (this.path != null) {
sb.append(encodePath(normalizePath(this.path)));
}
if (this.encodedQuery != null) {
sb.append(""?"").append(this.encodedQuery);
} else if (this.queryParams != null) {
sb.append(""?"").append(encodeUrlForm(this.queryParams));
} else if (this.query != null) {
sb.append(""?"").append(encodeUric(this.query));
}
}
if (this.encodedFragment != null) {
sb.append(""#"").append(this.encodedFragment);
} else if (this.fragment != null) {
sb.append(""#"").append(encodeUric(this.fragment));
}
return sb.toString();
}
",FALSE,URIBuilder.java
" private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
this.encodedAuthority = uri.getRawAuthority();
this.host = uri.getHost();
this.port = uri.getPort();
this.encodedUserInfo = uri.getRawUserInfo();
this.userInfo = uri.getUserInfo();
this.encodedPath = uri.getRawPath();
this.path = uri.getPath();
this.encodedQuery = uri.getRawQuery();
this.queryParams = parseQuery(uri.getRawQuery(), this.charset != null ? this.charset : Consts.UTF_8);
this.encodedFragment = uri.getRawFragment();
this.fragment = uri.getFragment();
}
"," private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
this.encodedAuthority = uri.getRawAuthority();
this.host = uri.getHost();
this.port = uri.getPort();
this.encodedUserInfo = uri.getRawUserInfo();
this.userInfo = uri.getUserInfo();
this.encodedPath = uri.getRawPath();
this.path = uri.getPath();
this.encodedQuery = uri.getRawQuery();
this.queryParams = parseQuery(uri.getRawQuery(), this.charset != null ? this.charset : Consts.UTF_8);
this.encodedFragment = uri.getRawFragment();
this.fragment = uri.getFragment();
}
",FALSE,URIBuilder.java
" private String encodeUserInfo(final String userInfo) {
return URLEncodedUtils.encUserInfo(userInfo, this.charset != null ? this.charset : Consts.UTF_8);
}
"," private String encodeUserInfo(final String userInfo) {
return URLEncodedUtils.encUserInfo(userInfo, this.charset != null ? this.charset : Consts.UTF_8);
}
",FALSE,URIBuilder.java
" private String encodePath(final String path) {
return URLEncodedUtils.encPath(path, this.charset != null ? this.charset : Consts.UTF_8);
}
"," private String encodePath(final String path) {
return URLEncodedUtils.encPath(path, this.charset != null ? this.charset : Consts.UTF_8);
}
",FALSE,URIBuilder.java
" private String encodeUrlForm(final List params) {
return URLEncodedUtils.format(params, this.charset != null ? this.charset : Consts.UTF_8);
}
"," private String encodeUrlForm(final List params) {
return URLEncodedUtils.format(params, this.charset != null ? this.charset : Consts.UTF_8);
}
",FALSE,URIBuilder.java
" private String encodeUric(final String fragment) {
return URLEncodedUtils.encUric(fragment, this.charset != null ? this.charset : Consts.UTF_8);
}
"," private String encodeUric(final String fragment) {
return URLEncodedUtils.encUric(fragment, this.charset != null ? this.charset : Consts.UTF_8);
}
",FALSE,URIBuilder.java
" public URIBuilder setScheme(final String scheme) {
this.scheme = scheme;
return this;
}
"," public URIBuilder setScheme(final String scheme) {
this.scheme = scheme;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setUserInfo(final String userInfo) {
this.userInfo = userInfo;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
this.encodedUserInfo = null;
return this;
}
"," public URIBuilder setUserInfo(final String userInfo) {
this.userInfo = userInfo;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
this.encodedUserInfo = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setUserInfo(final String username, final String password) {
return setUserInfo(username + ':' + password);
}
"," public URIBuilder setUserInfo(final String username, final String password) {
return setUserInfo(username + ':' + password);
}
",FALSE,URIBuilder.java
" public URIBuilder setHost(final String host) {
this.host = host;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
"," public URIBuilder setHost(final String host) {
this.host = host;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setPort(final int port) {
this.port = port < 0 ? -1 : port;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
"," public URIBuilder setPort(final int port) {
this.port = port < 0 ? -1 : port;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setPath(final String path) {
this.path = path;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
"," public URIBuilder setPath(final String path) {
this.path = path;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder removeQuery() {
this.queryParams = null;
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
"," public URIBuilder removeQuery() {
this.queryParams = null;
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setQuery(final String query) {
this.queryParams = parseQuery(query, this.charset != null ? this.charset : Consts.UTF_8);
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
"," public URIBuilder setQuery(final String query) {
this.queryParams = parseQuery(query, this.charset != null ? this.charset : Consts.UTF_8);
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setParameters(final List nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
} else {
this.queryParams.clear();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
"," public URIBuilder setParameters(final List nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
} else {
this.queryParams.clear();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder addParameters(final List nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
"," public URIBuilder addParameters(final List nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setParameters(final NameValuePair... nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
} else {
this.queryParams.clear();
}
for (final NameValuePair nvp: nvps) {
this.queryParams.add(nvp);
}
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
"," public URIBuilder setParameters(final NameValuePair... nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
} else {
this.queryParams.clear();
}
for (final NameValuePair nvp: nvps) {
this.queryParams.add(nvp);
}
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder addParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
"," public URIBuilder addParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
}
if (!this.queryParams.isEmpty()) {
for (final Iterator it = this.queryParams.iterator(); it.hasNext(); ) {
final NameValuePair nvp = it.next();
if (nvp.getName().equals(param)) {
it.remove();
}
}
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
"," public URIBuilder setParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList();
}
if (!this.queryParams.isEmpty()) {
for (final Iterator it = this.queryParams.iterator(); it.hasNext(); ) {
final NameValuePair nvp = it.next();
if (nvp.getName().equals(param)) {
it.remove();
}
}
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder clearParameters() {
this.queryParams = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
"," public URIBuilder clearParameters() {
this.queryParams = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setCustomQuery(final String query) {
this.query = query;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.queryParams = null;
return this;
}
"," public URIBuilder setCustomQuery(final String query) {
this.query = query;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.queryParams = null;
return this;
}
",FALSE,URIBuilder.java
" public URIBuilder setFragment(final String fragment) {
this.fragment = fragment;
this.encodedFragment = null;
return this;
}
"," public URIBuilder setFragment(final String fragment) {
this.fragment = fragment;
this.encodedFragment = null;
return this;
}
",FALSE,URIBuilder.java
" public boolean isAbsolute() {
return this.scheme != null;
}
"," public boolean isAbsolute() {
return this.scheme != null;
}
",FALSE,URIBuilder.java
" public boolean isOpaque() {
return this.path == null;
}
"," public boolean isOpaque() {
return this.path == null;
}
",FALSE,URIBuilder.java
" public String getScheme() {
return this.scheme;
}
"," public String getScheme() {
return this.scheme;
}
",FALSE,URIBuilder.java
" public String getUserInfo() {
return this.userInfo;
}
"," public String getUserInfo() {
return this.userInfo;
}
",FALSE,URIBuilder.java
" public String getHost() {
return this.host;
}
"," public String getHost() {
return this.host;
}
",FALSE,URIBuilder.java
" public int getPort() {
return this.port;
}
"," public int getPort() {
return this.port;
}
",FALSE,URIBuilder.java
" public String getPath() {
return this.path;
}
"," public String getPath() {
return this.path;
}
",FALSE,URIBuilder.java
" public List getQueryParams() {
if (this.queryParams != null) {
return new ArrayList(this.queryParams);
} else {
return new ArrayList();
}
}
"," public List getQueryParams() {
if (this.queryParams != null) {
return new ArrayList(this.queryParams);
} else {
return new ArrayList();
}
}
",FALSE,URIBuilder.java
" public String getFragment() {
return this.fragment;
}
"," public String getFragment() {
return this.fragment;
}
",FALSE,URIBuilder.java
" public String toString() {
return buildString();
}
"," public String toString() {
return buildString();
}
",FALSE,URIBuilder.java
" private static String normalizePath(final String path) {
String s = path;
if (s == null) {
return null;
}
int n = 0;
for (; n < s.length(); n++) {
if (s.charAt(n) != '/') {
break;
}
}
if (n > 1) {
s = s.substring(n - 1);
}
return s;
}
"," private static String normalizePath(final String path) {
String s = path;
if (s == null) {
return ""/"";
}
int n = 0;
for (; n < s.length(); n++) {
if (s.charAt(n) != '/') {
break;
}
}
if (n > 1) {
s = s.substring(n - 1);
}
if (!s.startsWith(""/"")) {
s = ""/"" + s;
}
return s;
}
",TRUE,URIBuilder.java
" public void testHierarchicalUri() throws Exception {
final URI uri = new URI(""http"", ""stuff"", ""localhost"", 80, ""/some stuff"", ""param=stuff"", ""fragment"");
final URIBuilder uribuilder = new URIBuilder(uri);
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://stuff@localhost:80/some%20stuff?param=stuff#fragment""), result);
}
"," public void testHierarchicalUri() throws Exception {
final URI uri = new URI(""http"", ""stuff"", ""localhost"", 80, ""/some stuff"", ""param=stuff"", ""fragment"");
final URIBuilder uribuilder = new URIBuilder(uri);
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://stuff@localhost:80/some%20stuff?param=stuff#fragment""), result);
}
",FALSE,TestURIBuilder.java
" public void testMutationToRelativeUri() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URIBuilder uribuilder = new URIBuilder(uri).setHost(null);
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http:///stuff?param=stuff#fragment""), result);
}
"," public void testMutationToRelativeUri() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URIBuilder uribuilder = new URIBuilder(uri).setHost(null);
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http:///stuff?param=stuff#fragment""), result);
}
",FALSE,TestURIBuilder.java
" public void testMutationRemoveFragment() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URI result = new URIBuilder(uri).setFragment(null).build();
Assert.assertEquals(new URI(""http://stuff@localhost:80/stuff?param=stuff""), result);
}
"," public void testMutationRemoveFragment() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URI result = new URIBuilder(uri).setFragment(null).build();
Assert.assertEquals(new URI(""http://stuff@localhost:80/stuff?param=stuff""), result);
}
",FALSE,TestURIBuilder.java
" public void testMutationRemoveUserInfo() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URI result = new URIBuilder(uri).setUserInfo(null).build();
Assert.assertEquals(new URI(""http://localhost:80/stuff?param=stuff#fragment""), result);
}
"," public void testMutationRemoveUserInfo() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URI result = new URIBuilder(uri).setUserInfo(null).build();
Assert.assertEquals(new URI(""http://localhost:80/stuff?param=stuff#fragment""), result);
}
",FALSE,TestURIBuilder.java
" public void testMutationRemovePort() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URI result = new URIBuilder(uri).setPort(-1).build();
Assert.assertEquals(new URI(""http://stuff@localhost/stuff?param=stuff#fragment""), result);
}
"," public void testMutationRemovePort() throws Exception {
final URI uri = new URI(""http://stuff@localhost:80/stuff?param=stuff#fragment"");
final URI result = new URIBuilder(uri).setPort(-1).build();
Assert.assertEquals(new URI(""http://stuff@localhost/stuff?param=stuff#fragment""), result);
}
",FALSE,TestURIBuilder.java
" public void testOpaqueUri() throws Exception {
final URI uri = new URI(""stuff"", ""some-stuff"", ""fragment"");
final URIBuilder uribuilder = new URIBuilder(uri);
final URI result = uribuilder.build();
Assert.assertEquals(uri, result);
}
"," public void testOpaqueUri() throws Exception {
final URI uri = new URI(""stuff"", ""some-stuff"", ""fragment"");
final URIBuilder uribuilder = new URIBuilder(uri);
final URI result = uribuilder.build();
Assert.assertEquals(uri, result);
}
",FALSE,TestURIBuilder.java
" public void testOpaqueUriMutation() throws Exception {
final URI uri = new URI(""stuff"", ""some-stuff"", ""fragment"");
final URIBuilder uribuilder = new URIBuilder(uri).setCustomQuery(""param1¶m2=stuff"").setFragment(null);
Assert.assertEquals(new URI(""stuff:?param1¶m2=stuff""), uribuilder.build());
}
"," public void testOpaqueUriMutation() throws Exception {
final URI uri = new URI(""stuff"", ""some-stuff"", ""fragment"");
final URIBuilder uribuilder = new URIBuilder(uri).setCustomQuery(""param1¶m2=stuff"").setFragment(null);
Assert.assertEquals(new URI(""stuff:?param1¶m2=stuff""), uribuilder.build());
}
",FALSE,TestURIBuilder.java
" public void testHierarchicalUriMutation() throws Exception {
final URIBuilder uribuilder = new URIBuilder(""/"").setScheme(""http"").setHost(""localhost"").setPort(80).setPath(""/stuff"");
Assert.assertEquals(new URI(""http://localhost:80/stuff""), uribuilder.build());
}
"," public void testHierarchicalUriMutation() throws Exception {
final URIBuilder uribuilder = new URIBuilder(""/"").setScheme(""http"").setHost(""localhost"").setPort(80).setPath(""/stuff"");
Assert.assertEquals(new URI(""http://localhost:80/stuff""), uribuilder.build());
}
",FALSE,TestURIBuilder.java
" public void testEmpty() throws Exception {
final URIBuilder uribuilder = new URIBuilder();
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""""), result);
}
"," public void testEmpty() throws Exception {
final URIBuilder uribuilder = new URIBuilder();
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""""), result);
}
",FALSE,TestURIBuilder.java
" public void testSetUserInfo() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff"", null);
final URIBuilder uribuilder = new URIBuilder(uri).setUserInfo(""user"", ""password"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://user:password@localhost:80/?param=stuff""), result);
}
"," public void testSetUserInfo() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff"", null);
final URIBuilder uribuilder = new URIBuilder(uri).setUserInfo(""user"", ""password"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://user:password@localhost:80/?param=stuff""), result);
}
",FALSE,TestURIBuilder.java
" public void testRemoveParameters() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff"", null);
final URIBuilder uribuilder = new URIBuilder(uri).removeQuery();
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/""), result);
}
"," public void testRemoveParameters() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff"", null);
final URIBuilder uribuilder = new URIBuilder(uri).removeQuery();
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/""), result);
}
",FALSE,TestURIBuilder.java
" public void testSetParameter() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff&blah&blah"", null);
final URIBuilder uribuilder = new URIBuilder(uri).setParameter(""param"", ""some other stuff"")
.setParameter(""blah"", ""blah"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/?param=some+other+stuff&blah=blah""), result);
}
"," public void testSetParameter() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff&blah&blah"", null);
final URIBuilder uribuilder = new URIBuilder(uri).setParameter(""param"", ""some other stuff"")
.setParameter(""blah"", ""blah"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/?param=some+other+stuff&blah=blah""), result);
}
",FALSE,TestURIBuilder.java
" public void testParameterWithSpecialChar() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff"", null);
final URIBuilder uribuilder = new URIBuilder(uri).addParameter(""param"", ""1 + 1 = 2"")
.addParameter(""param"", ""blah&blah"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/?param=stuff¶m=1+%2B+1+%3D+2&"" +
""param=blah%26blah""), result);
}
"," public void testParameterWithSpecialChar() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff"", null);
final URIBuilder uribuilder = new URIBuilder(uri).addParameter(""param"", ""1 + 1 = 2"")
.addParameter(""param"", ""blah&blah"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/?param=stuff¶m=1+%2B+1+%3D+2&"" +
""param=blah%26blah""), result);
}
",FALSE,TestURIBuilder.java
" public void testAddParameter() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff&blah&blah"", null);
final URIBuilder uribuilder = new URIBuilder(uri).addParameter(""param"", ""some other stuff"")
.addParameter(""blah"", ""blah"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/?param=stuff&blah&blah&"" +
""param=some+other+stuff&blah=blah""), result);
}
"," public void testAddParameter() throws Exception {
final URI uri = new URI(""http"", null, ""localhost"", 80, ""/"", ""param=stuff&blah&blah"", null);
final URIBuilder uribuilder = new URIBuilder(uri).addParameter(""param"", ""some other stuff"")
.addParameter(""blah"", ""blah"");
final URI result = uribuilder.build();
Assert.assertEquals(new URI(""http://localhost:80/?param=stuff&blah&blah&"" +
""param=some+other+stuff&blah=blah""), result);
}
",FALSE,TestURIBuilder.java
" public void testQueryEncoding() throws Exception {
final URI uri1 = new URI(""https://somehost.com/stuff?client_id=1234567890"" +
""&redirect_uri=https%3A%2F%2Fsomehost.com%2Fblah+blah%2F"");
final URI uri2 = new URIBuilder(""https://somehost.com/stuff"")
.addParameter(""client_id"",""1234567890"")
.addParameter(""redirect_uri"",""https://somehost.com/blah blah/"").build();
Assert.assertEquals(uri1, uri2);
}
"," public void testQueryEncoding() throws Exception {
final URI uri1 = new URI(""https://somehost.com/stuff?client_id=1234567890"" +
""&redirect_uri=https%3A%2F%2Fsomehost.com%2Fblah+blah%2F"");
final URI uri2 = new URIBuilder(""https://somehost.com/stuff"")
.addParameter(""client_id"",""1234567890"")
.addParameter(""redirect_uri"",""https://somehost.com/blah blah/"").build();
Assert.assertEquals(uri1, uri2);
}
",FALSE,TestURIBuilder.java
" public void testQueryAndParameterEncoding() throws Exception {
final URI uri1 = new URI(""https://somehost.com/stuff?param1=12345¶m2=67890"");
final URI uri2 = new URIBuilder(""https://somehost.com/stuff"")
.setCustomQuery(""this&that"")
.addParameter(""param1"",""12345"")
.addParameter(""param2"",""67890"").build();
Assert.assertEquals(uri1, uri2);
}
"," public void testQueryAndParameterEncoding() throws Exception {
final URI uri1 = new URI(""https://somehost.com/stuff?param1=12345¶m2=67890"");
final URI uri2 = new URIBuilder(""https://somehost.com/stuff"")
.setCustomQuery(""this&that"")
.addParameter(""param1"",""12345"")
.addParameter(""param2"",""67890"").build();
Assert.assertEquals(uri1, uri2);
}
",FALSE,TestURIBuilder.java
" public void testPathEncoding() throws Exception {
final URI uri1 = new URI(""https://somehost.com/some%20path%20with%20blanks/"");
final URI uri2 = new URIBuilder()
.setScheme(""https"")
.setHost(""somehost.com"")
.setPath(""/some path with blanks/"")
.build();
Assert.assertEquals(uri1, uri2);
}
"," public void testPathEncoding() throws Exception {
final URI uri1 = new URI(""https://somehost.com/some%20path%20with%20blanks/"");
final URI uri2 = new URIBuilder()
.setScheme(""https"")
.setHost(""somehost.com"")
.setPath(""/some path with blanks/"")
.build();
Assert.assertEquals(uri1, uri2);
}
",FALSE,TestURIBuilder.java
" public void testAgainstURI() throws Exception {
// Check that the URI generated by URI builder agrees with that generated by using URI directly
final String scheme=""https"";
final String host=""localhost"";
final String specials=""/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\""{}\\\u00a3`\u00ac\u00a6xyz""; // N.B. excludes space
final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
final URI bld = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setUserInfo(specials)
.setPath(specials)
.setCustomQuery(specials)
.setFragment(specials)
.build();
Assert.assertEquals(uri.getHost(), bld.getHost());
Assert.assertEquals(uri.getUserInfo(), bld.getUserInfo());
Assert.assertEquals(uri.getPath(), bld.getPath());
Assert.assertEquals(uri.getQuery(), bld.getQuery());
Assert.assertEquals(uri.getFragment(), bld.getFragment());
}
"," public void testAgainstURI() throws Exception {
// Check that the URI generated by URI builder agrees with that generated by using URI directly
final String scheme=""https"";
final String host=""localhost"";
final String specials=""/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\""{}\\\u00a3`\u00ac\u00a6xyz""; // N.B. excludes space
final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
final URI bld = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setUserInfo(specials)
.setPath(specials)
.setCustomQuery(specials)
.setFragment(specials)
.build();
Assert.assertEquals(uri.getHost(), bld.getHost());
Assert.assertEquals(uri.getUserInfo(), bld.getUserInfo());
Assert.assertEquals(uri.getPath(), bld.getPath());
Assert.assertEquals(uri.getQuery(), bld.getQuery());
Assert.assertEquals(uri.getFragment(), bld.getFragment());
}
",FALSE,TestURIBuilder.java
" public void testAgainstURIEncoded() throws Exception {
// Check that the encoded URI generated by URI builder agrees with that generated by using URI directly
final String scheme=""https"";
final String host=""localhost"";
final String specials=""/ abcd!$&*()_-+.,=:;'~<>/@[]|#^%\""{}\\`xyz""; // N.B. excludes \u00a3\u00ac\u00a6
final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
final URI bld = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setUserInfo(specials)
.setPath(specials)
.setCustomQuery(specials)
.setFragment(specials)
.build();
Assert.assertEquals(uri.getHost(), bld.getHost());
Assert.assertEquals(uri.getRawUserInfo(), bld.getRawUserInfo());
Assert.assertEquals(uri.getRawPath(), bld.getRawPath());
Assert.assertEquals(uri.getRawQuery(), bld.getRawQuery());
Assert.assertEquals(uri.getRawFragment(), bld.getRawFragment());
}
"," public void testAgainstURIEncoded() throws Exception {
// Check that the encoded URI generated by URI builder agrees with that generated by using URI directly
final String scheme=""https"";
final String host=""localhost"";
final String specials=""/ abcd!$&*()_-+.,=:;'~<>/@[]|#^%\""{}\\`xyz""; // N.B. excludes \u00a3\u00ac\u00a6
final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
final URI bld = new URIBuilder()
.setScheme(scheme)
.setHost(host)
.setUserInfo(specials)
.setPath(specials)
.setCustomQuery(specials)
.setFragment(specials)
.build();
Assert.assertEquals(uri.getHost(), bld.getHost());
Assert.assertEquals(uri.getRawUserInfo(), bld.getRawUserInfo());
Assert.assertEquals(uri.getRawPath(), bld.getRawPath());
Assert.assertEquals(uri.getRawQuery(), bld.getRawQuery());
Assert.assertEquals(uri.getRawFragment(), bld.getRawFragment());
}
",FALSE,TestURIBuilder.java
" public void testBuildAddParametersUTF8() throws Exception {
assertAddParameters(Consts.UTF_8);
}
"," public void testBuildAddParametersUTF8() throws Exception {
assertAddParameters(Consts.UTF_8);
}
",FALSE,TestURIBuilder.java
" public void testBuildAddParametersISO88591() throws Exception {
assertAddParameters(Consts.ISO_8859_1);
}
"," public void testBuildAddParametersISO88591() throws Exception {
assertAddParameters(Consts.ISO_8859_1);
}
",FALSE,TestURIBuilder.java
" public void assertAddParameters(final Charset charset) throws Exception {
final URI uri = new URIBuilder(""https://somehost.com/stuff"")
.setCharset(charset)
.addParameters(createParameters()).build();
assertBuild(charset, uri);
}
"," public void assertAddParameters(final Charset charset) throws Exception {
final URI uri = new URIBuilder(""https://somehost.com/stuff"")
.setCharset(charset)
.addParameters(createParameters()).build();
assertBuild(charset, uri);
}
",FALSE,TestURIBuilder.java
" public void testBuildSetParametersUTF8() throws Exception {
assertSetParameters(Consts.UTF_8);
}
"," public void testBuildSetParametersUTF8() throws Exception {
assertSetParameters(Consts.UTF_8);
}
",FALSE,TestURIBuilder.java
" public void testBuildSetParametersISO88591() throws Exception {
assertSetParameters(Consts.ISO_8859_1);
}
"," public void testBuildSetParametersISO88591() throws Exception {
assertSetParameters(Consts.ISO_8859_1);
}
",FALSE,TestURIBuilder.java
" public void assertSetParameters(final Charset charset) throws Exception {
final URI uri = new URIBuilder(""https://somehost.com/stuff"")
.setCharset(charset)
.setParameters(createParameters()).build();
assertBuild(charset, uri);
}
"," public void assertSetParameters(final Charset charset) throws Exception {
final URI uri = new URIBuilder(""https://somehost.com/stuff"")
.setCharset(charset)
.setParameters(createParameters()).build();
assertBuild(charset, uri);
}
",FALSE,TestURIBuilder.java
" public void assertBuild(final Charset charset, final URI uri) throws Exception {
final String encodedData1 = URLEncoder.encode(""\""1\u00aa position\"""", charset.displayName());
final String encodedData2 = URLEncoder.encode(""Jos\u00e9 Abra\u00e3o"", charset.displayName());
final String uriExpected = String.format(""https://somehost.com/stuff?parameter1=value1¶meter2=%s¶meter3=%s"", encodedData1, encodedData2);
Assert.assertEquals(uriExpected, uri.toString());
}
"," public void assertBuild(final Charset charset, final URI uri) throws Exception {
final String encodedData1 = URLEncoder.encode(""\""1\u00aa position\"""", charset.displayName());
final String encodedData2 = URLEncoder.encode(""Jos\u00e9 Abra\u00e3o"", charset.displayName());
final String uriExpected = String.format(""https://somehost.com/stuff?parameter1=value1¶meter2=%s¶meter3=%s"", encodedData1, encodedData2);
Assert.assertEquals(uriExpected, uri.toString());
}
",FALSE,TestURIBuilder.java
" private List createParameters() {
final List parameters = new ArrayList();
parameters.add(new BasicNameValuePair(""parameter1"", ""value1""));
parameters.add(new BasicNameValuePair(""parameter2"", ""\""1\u00aa position\""""));
parameters.add(new BasicNameValuePair(""parameter3"", ""Jos\u00e9 Abra\u00e3o""));
return parameters;
}
"," private List createParameters() {
final List parameters = new ArrayList();
parameters.add(new BasicNameValuePair(""parameter1"", ""value1""));
parameters.add(new BasicNameValuePair(""parameter2"", ""\""1\u00aa position\""""));
parameters.add(new BasicNameValuePair(""parameter3"", ""Jos\u00e9 Abra\u00e3o""));
return parameters;
}
",FALSE,TestURIBuilder.java
"
"," public void testMalformedPath() throws Exception {
final String path = ""@notexample.com/mypath"";
final URI uri = new URIBuilder(path).setHost(""example.com"").build();
Assert.assertEquals(""example.com"", uri.getHost());
}
",TRUE,TestURIBuilder.java
" public StandardSecurityHandler()
{
}
"," public StandardSecurityHandler()
{
}
",FALSE,StandardSecurityHandler.java
" public StandardSecurityHandler(StandardProtectionPolicy p)
{
policy = p;
keyLength = policy.getEncryptionKeyLength();
}
"," public StandardSecurityHandler(StandardProtectionPolicy p)
{
policy = p;
keyLength = policy.getEncryptionKeyLength();
}
",FALSE,StandardSecurityHandler.java
" private int computeVersionNumber()
{
if(keyLength == 40)
{
return DEFAULT_VERSION;
}
else if (keyLength == 128 && policy.isPreferAES())
{
return 4;
}
else if (keyLength == 256)
{
return 5;
}
return 2;
}
"," private int computeVersionNumber()
{
if(keyLength == 40)
{
return DEFAULT_VERSION;
}
else if (keyLength == 128 && policy.isPreferAES())
{
return 4;
}
else if (keyLength == 256)
{
return 5;
}
return 2;
}
",FALSE,StandardSecurityHandler.java
" private int computeRevisionNumber(int version)
{
if(version < 2 && !policy.getPermissions().hasAnyRevision3PermissionSet())
{
return 2;
}
if (version == 5)
{
// note about revision 5: ""Shall not be used. This value was used by a deprecated Adobe extension.""
return 6;
}
if (version == 4)
{
return 4;
}
if ( version == 2 || version == 3 || policy.getPermissions().hasAnyRevision3PermissionSet())
{
return 3;
}
return 4;
}
"," private int computeRevisionNumber(int version)
{
if(version < 2 && !policy.getPermissions().hasAnyRevision3PermissionSet())
{
return 2;
}
if (version == 5)
{
// note about revision 5: ""Shall not be used. This value was used by a deprecated Adobe extension.""
return 6;
}
if (version == 4)
{
return 4;
}
if ( version == 2 || version == 3 || policy.getPermissions().hasAnyRevision3PermissionSet())
{
return 3;
}
return 4;
}
",FALSE,StandardSecurityHandler.java
" public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray,
DecryptionMaterial decryptionMaterial)
throws IOException
{
if(!(decryptionMaterial instanceof StandardDecryptionMaterial))
{
throw new IOException(""Decryption material is not compatible with the document"");
}
setDecryptMetadata(encryption.isEncryptMetaData());
StandardDecryptionMaterial material = (StandardDecryptionMaterial)decryptionMaterial;
String password = material.getPassword();
if(password == null)
{
password = """";
}
int dicPermissions = encryption.getPermissions();
int dicRevision = encryption.getRevision();
int dicLength = encryption.getVersion() == 1 ? 5 : encryption.getLength() / 8;
byte[] documentIDBytes = getDocumentIDBytes(documentIDArray);
// we need to know whether the meta data was encrypted for password calculation
boolean encryptMetadata = encryption.isEncryptMetaData();
byte[] userKey = encryption.getUserKey();
byte[] ownerKey = encryption.getOwnerKey();
byte[] ue = null, oe = null;
Charset passwordCharset = Charsets.ISO_8859_1;
if (dicRevision == 6 || dicRevision == 5)
{
passwordCharset = Charsets.UTF_8;
ue = encryption.getUserEncryptionKey();
oe = encryption.getOwnerEncryptionKey();
}
AccessPermission currentAccessPermission;
if( isOwnerPassword(password.getBytes(passwordCharset), userKey, ownerKey,
dicPermissions, documentIDBytes, dicRevision,
dicLength, encryptMetadata) )
{
currentAccessPermission = AccessPermission.getOwnerAccessPermission();
setCurrentAccessPermission(currentAccessPermission);
byte[] computedPassword;
if (dicRevision == 6 || dicRevision == 5)
{
computedPassword = password.getBytes(passwordCharset);
}
else
{
computedPassword = getUserPassword(password.getBytes(passwordCharset),
ownerKey, dicRevision, dicLength );
}
encryptionKey =
computeEncryptedKey(
computedPassword,
ownerKey, userKey, oe, ue,
dicPermissions,
documentIDBytes,
dicRevision,
dicLength,
encryptMetadata, true );
}
else if( isUserPassword(password.getBytes(passwordCharset), userKey, ownerKey,
dicPermissions, documentIDBytes, dicRevision,
dicLength, encryptMetadata) )
{
currentAccessPermission = new AccessPermission(dicPermissions);
setCurrentAccessPermission(currentAccessPermission);
encryptionKey =
computeEncryptedKey(
password.getBytes(passwordCharset),
ownerKey, userKey, oe, ue,
dicPermissions,
documentIDBytes,
dicRevision,
dicLength,
encryptMetadata, false );
}
else
{
throw new InvalidPasswordException(""Cannot decrypt PDF, the password is incorrect"");
}
if (dicRevision == 6 || dicRevision == 5)
{
validatePerms(encryption, dicPermissions, encryptMetadata);
}
if (encryption.getVersion() == 4 || encryption.getVersion() == 5)
{
// detect whether AES encryption is used. This assumes that the encryption algo is
// stored in the PDCryptFilterDictionary
// However, crypt filters are used only when V is 4 or 5.
PDCryptFilterDictionary stdCryptFilterDictionary = encryption.getStdCryptFilterDictionary();
if (stdCryptFilterDictionary != null)
{
COSName cryptFilterMethod = stdCryptFilterDictionary.getCryptFilterMethod();
setAES(COSName.AESV2.equals(cryptFilterMethod) ||
COSName.AESV3.equals(cryptFilterMethod));
}
}
}
"," public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray,
DecryptionMaterial decryptionMaterial)
throws IOException
{
if(!(decryptionMaterial instanceof StandardDecryptionMaterial))
{
throw new IOException(""Decryption material is not compatible with the document"");
}
setDecryptMetadata(encryption.isEncryptMetaData());
StandardDecryptionMaterial material = (StandardDecryptionMaterial)decryptionMaterial;
String password = material.getPassword();
if(password == null)
{
password = """";
}
int dicPermissions = encryption.getPermissions();
int dicRevision = encryption.getRevision();
int dicLength = encryption.getVersion() == 1 ? 5 : encryption.getLength() / 8;
byte[] documentIDBytes = getDocumentIDBytes(documentIDArray);
// we need to know whether the meta data was encrypted for password calculation
boolean encryptMetadata = encryption.isEncryptMetaData();
byte[] userKey = encryption.getUserKey();
byte[] ownerKey = encryption.getOwnerKey();
byte[] ue = null, oe = null;
Charset passwordCharset = Charsets.ISO_8859_1;
if (dicRevision == 6 || dicRevision == 5)
{
passwordCharset = Charsets.UTF_8;
ue = encryption.getUserEncryptionKey();
oe = encryption.getOwnerEncryptionKey();
}
AccessPermission currentAccessPermission;
if( isOwnerPassword(password.getBytes(passwordCharset), userKey, ownerKey,
dicPermissions, documentIDBytes, dicRevision,
dicLength, encryptMetadata) )
{
currentAccessPermission = AccessPermission.getOwnerAccessPermission();
setCurrentAccessPermission(currentAccessPermission);
byte[] computedPassword;
if (dicRevision == 6 || dicRevision == 5)
{
computedPassword = password.getBytes(passwordCharset);
}
else
{
computedPassword = getUserPassword(password.getBytes(passwordCharset),
ownerKey, dicRevision, dicLength );
}
encryptionKey =
computeEncryptedKey(
computedPassword,
ownerKey, userKey, oe, ue,
dicPermissions,
documentIDBytes,
dicRevision,
dicLength,
encryptMetadata, true );
}
else if( isUserPassword(password.getBytes(passwordCharset), userKey, ownerKey,
dicPermissions, documentIDBytes, dicRevision,
dicLength, encryptMetadata) )
{
currentAccessPermission = new AccessPermission(dicPermissions);
currentAccessPermission.setReadOnly();
setCurrentAccessPermission(currentAccessPermission);
encryptionKey =
computeEncryptedKey(
password.getBytes(passwordCharset),
ownerKey, userKey, oe, ue,
dicPermissions,
documentIDBytes,
dicRevision,
dicLength,
encryptMetadata, false );
}
else
{
throw new InvalidPasswordException(""Cannot decrypt PDF, the password is incorrect"");
}
if (dicRevision == 6 || dicRevision == 5)
{
validatePerms(encryption, dicPermissions, encryptMetadata);
}
if (encryption.getVersion() == 4 || encryption.getVersion() == 5)
{
// detect whether AES encryption is used. This assumes that the encryption algo is
// stored in the PDCryptFilterDictionary
// However, crypt filters are used only when V is 4 or 5.
PDCryptFilterDictionary stdCryptFilterDictionary = encryption.getStdCryptFilterDictionary();
if (stdCryptFilterDictionary != null)
{
COSName cryptFilterMethod = stdCryptFilterDictionary.getCryptFilterMethod();
setAES(COSName.AESV2.equals(cryptFilterMethod) ||
COSName.AESV3.equals(cryptFilterMethod));
}
}
}
",TRUE,StandardSecurityHandler.java
" private byte[] getDocumentIDBytes(COSArray documentIDArray)
{
//some documents may not have document id, see
//test\encryption\encrypted_doc_no_id.pdf
byte[] documentIDBytes;
if( documentIDArray != null && documentIDArray.size() >= 1 )
{
COSString id = (COSString)documentIDArray.getObject( 0 );
documentIDBytes = id.getBytes();
}
else
{
documentIDBytes = new byte[0];
}
return documentIDBytes;
}
"," private byte[] getDocumentIDBytes(COSArray documentIDArray)
{
//some documents may not have document id, see
//test\encryption\encrypted_doc_no_id.pdf
byte[] documentIDBytes;
if( documentIDArray != null && documentIDArray.size() >= 1 )
{
COSString id = (COSString)documentIDArray.getObject( 0 );
documentIDBytes = id.getBytes();
}
else
{
documentIDBytes = new byte[0];
}
return documentIDBytes;
}
",FALSE,StandardSecurityHandler.java
" private void validatePerms(PDEncryption encryption, int dicPermissions, boolean encryptMetadata) throws IOException
{
try
{
// ""Decrypt the 16-byte Perms string using AES-256 in ECB mode with an
// initialization vector of zero and the file encryption key as the key.""
Cipher cipher = Cipher.getInstance(""AES/ECB/NoPadding"");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, ""AES""));
byte[] perms = cipher.doFinal(encryption.getPerms());
// ""Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’.""
if (perms[9] != 'a' || perms[10] != 'd' || perms[11] != 'b')
{
LOG.warn(""Verification of permissions failed (constant)"");
}
// ""Bytes 0-3 of the decrypted Perms entry, treated as a little-endian integer,
// are the user permissions. They should match the value in the P key.""
int permsP = perms[0] & 0xFF | (perms[1] & 0xFF) << 8 | (perms[2] & 0xFF) << 16 |
(perms[3] & 0xFF) << 24;
if (permsP != dicPermissions)
{
LOG.warn(""Verification of permissions failed ("" + String.format(""%08X"",permsP) +
"" != "" + String.format(""%08X"",dicPermissions) + "")"");
}
if (encryptMetadata && perms[8] != 'T' || !encryptMetadata && perms[8] != 'F')
{
LOG.warn(""Verification of permissions failed (EncryptMetadata)"");
}
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
"," private void validatePerms(PDEncryption encryption, int dicPermissions, boolean encryptMetadata) throws IOException
{
try
{
// ""Decrypt the 16-byte Perms string using AES-256 in ECB mode with an
// initialization vector of zero and the file encryption key as the key.""
Cipher cipher = Cipher.getInstance(""AES/ECB/NoPadding"");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, ""AES""));
byte[] perms = cipher.doFinal(encryption.getPerms());
// ""Verify that bytes 9-11 of the result are the characters ‘a’, ‘d’, ‘b’.""
if (perms[9] != 'a' || perms[10] != 'd' || perms[11] != 'b')
{
LOG.warn(""Verification of permissions failed (constant)"");
}
// ""Bytes 0-3 of the decrypted Perms entry, treated as a little-endian integer,
// are the user permissions. They should match the value in the P key.""
int permsP = perms[0] & 0xFF | (perms[1] & 0xFF) << 8 | (perms[2] & 0xFF) << 16 |
(perms[3] & 0xFF) << 24;
if (permsP != dicPermissions)
{
LOG.warn(""Verification of permissions failed ("" + String.format(""%08X"",permsP) +
"" != "" + String.format(""%08X"",dicPermissions) + "")"");
}
if (encryptMetadata && perms[8] != 'T' || !encryptMetadata && perms[8] != 'F')
{
LOG.warn(""Verification of permissions failed (EncryptMetadata)"");
}
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
",FALSE,StandardSecurityHandler.java
" public void prepareDocumentForEncryption(PDDocument document) throws IOException
{
PDEncryption encryptionDictionary = document.getEncryption();
if(encryptionDictionary == null)
{
encryptionDictionary = new PDEncryption();
}
int version = computeVersionNumber();
int revision = computeRevisionNumber(version);
encryptionDictionary.setFilter(FILTER);
encryptionDictionary.setVersion(version);
if (version != 4 && version != 5)
{
// remove CF, StmF, and StrF entries that may be left from a previous encryption
encryptionDictionary.removeV45filters();
}
encryptionDictionary.setRevision(revision);
encryptionDictionary.setLength(keyLength);
String ownerPassword = policy.getOwnerPassword();
String userPassword = policy.getUserPassword();
if( ownerPassword == null )
{
ownerPassword = """";
}
if( userPassword == null )
{
userPassword = """";
}
// If no owner password is set, use the user password instead.
if (ownerPassword.isEmpty())
{
ownerPassword = userPassword;
}
int permissionInt = policy.getPermissions().getPermissionBytes();
encryptionDictionary.setPermissions(permissionInt);
int length = keyLength/8;
if (revision == 6)
{
prepareEncryptionDictRev6(ownerPassword, userPassword, encryptionDictionary, permissionInt);
}
else
{
prepareEncryptionDictRev2345(ownerPassword, userPassword, encryptionDictionary, permissionInt,
document, revision, length);
}
document.setEncryptionDictionary( encryptionDictionary );
document.getDocument().setEncryptionDictionary(encryptionDictionary.getCOSDictionary());
}
"," public void prepareDocumentForEncryption(PDDocument document) throws IOException
{
PDEncryption encryptionDictionary = document.getEncryption();
if(encryptionDictionary == null)
{
encryptionDictionary = new PDEncryption();
}
int version = computeVersionNumber();
int revision = computeRevisionNumber(version);
encryptionDictionary.setFilter(FILTER);
encryptionDictionary.setVersion(version);
if (version != 4 && version != 5)
{
// remove CF, StmF, and StrF entries that may be left from a previous encryption
encryptionDictionary.removeV45filters();
}
encryptionDictionary.setRevision(revision);
encryptionDictionary.setLength(keyLength);
String ownerPassword = policy.getOwnerPassword();
String userPassword = policy.getUserPassword();
if( ownerPassword == null )
{
ownerPassword = """";
}
if( userPassword == null )
{
userPassword = """";
}
// If no owner password is set, use the user password instead.
if (ownerPassword.isEmpty())
{
ownerPassword = userPassword;
}
int permissionInt = policy.getPermissions().getPermissionBytes();
encryptionDictionary.setPermissions(permissionInt);
int length = keyLength/8;
if (revision == 6)
{
prepareEncryptionDictRev6(ownerPassword, userPassword, encryptionDictionary, permissionInt);
}
else
{
prepareEncryptionDictRev2345(ownerPassword, userPassword, encryptionDictionary, permissionInt,
document, revision, length);
}
document.setEncryptionDictionary( encryptionDictionary );
document.getDocument().setEncryptionDictionary(encryptionDictionary.getCOSDictionary());
}
",FALSE,StandardSecurityHandler.java
" private void prepareEncryptionDictRev6(String ownerPassword, String userPassword,
PDEncryption encryptionDictionary, int permissionInt)
throws IOException
{
try
{
SecureRandom rnd = new SecureRandom();
Cipher cipher = Cipher.getInstance(""AES/CBC/NoPadding"");
// make a random 256-bit file encryption key
encryptionKey = new byte[32];
rnd.nextBytes(encryptionKey);
// Algorithm 8a: Compute U
byte[] userPasswordBytes = truncate127(userPassword.getBytes(Charsets.UTF_8));
byte[] userValidationSalt = new byte[8];
byte[] userKeySalt = new byte[8];
rnd.nextBytes(userValidationSalt);
rnd.nextBytes(userKeySalt);
byte[] hashU = computeHash2B(concat(userPasswordBytes, userValidationSalt),
userPasswordBytes, null);
byte[] u = concat(hashU, userValidationSalt, userKeySalt);
// Algorithm 8b: Compute UE
byte[] hashUE = computeHash2B(concat(userPasswordBytes, userKeySalt),
userPasswordBytes, null);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashUE, ""AES""),
new IvParameterSpec(new byte[16]));
byte[] ue = cipher.doFinal(encryptionKey);
// Algorithm 9a: Compute O
byte[] ownerPasswordBytes = truncate127(ownerPassword.getBytes(Charsets.UTF_8));
byte[] ownerValidationSalt = new byte[8];
byte[] ownerKeySalt = new byte[8];
rnd.nextBytes(ownerValidationSalt);
rnd.nextBytes(ownerKeySalt);
byte[] hashO = computeHash2B(concat(ownerPasswordBytes, ownerValidationSalt, u),
ownerPasswordBytes, u);
byte[] o = concat(hashO, ownerValidationSalt, ownerKeySalt);
// Algorithm 9b: Compute OE
byte[] hashOE = computeHash2B(concat(ownerPasswordBytes, ownerKeySalt, u),
ownerPasswordBytes, u);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashOE, ""AES""),
new IvParameterSpec(new byte[16]));
byte[] oe = cipher.doFinal(encryptionKey);
// Set keys and other required constants in encryption dictionary
encryptionDictionary.setUserKey(u);
encryptionDictionary.setUserEncryptionKey(ue);
encryptionDictionary.setOwnerKey(o);
encryptionDictionary.setOwnerEncryptionKey(oe);
prepareEncryptionDictAES(encryptionDictionary, COSName.AESV3);
// Algorithm 10: compute ""Perms"" value
byte[] perms = new byte[16];
perms[0] = (byte) permissionInt;
perms[1] = (byte) (permissionInt >>> 8);
perms[2] = (byte) (permissionInt >>> 16);
perms[3] = (byte) (permissionInt >>> 24);
perms[4] = (byte) 0xFF;
perms[5] = (byte) 0xFF;
perms[6] = (byte) 0xFF;
perms[7] = (byte) 0xFF;
perms[8] = 'T'; // we always encrypt Metadata
perms[9] = 'a';
perms[10] = 'd';
perms[11] = 'b';
for (int i = 12; i <= 15; i++)
{
perms[i] = (byte) rnd.nextInt();
}
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, ""AES""),
new IvParameterSpec(new byte[16]));
byte[] permsEnc = cipher.doFinal(perms);
encryptionDictionary.setPerms(permsEnc);
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
"," private void prepareEncryptionDictRev6(String ownerPassword, String userPassword,
PDEncryption encryptionDictionary, int permissionInt)
throws IOException
{
try
{
SecureRandom rnd = new SecureRandom();
Cipher cipher = Cipher.getInstance(""AES/CBC/NoPadding"");
// make a random 256-bit file encryption key
encryptionKey = new byte[32];
rnd.nextBytes(encryptionKey);
// Algorithm 8a: Compute U
byte[] userPasswordBytes = truncate127(userPassword.getBytes(Charsets.UTF_8));
byte[] userValidationSalt = new byte[8];
byte[] userKeySalt = new byte[8];
rnd.nextBytes(userValidationSalt);
rnd.nextBytes(userKeySalt);
byte[] hashU = computeHash2B(concat(userPasswordBytes, userValidationSalt),
userPasswordBytes, null);
byte[] u = concat(hashU, userValidationSalt, userKeySalt);
// Algorithm 8b: Compute UE
byte[] hashUE = computeHash2B(concat(userPasswordBytes, userKeySalt),
userPasswordBytes, null);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashUE, ""AES""),
new IvParameterSpec(new byte[16]));
byte[] ue = cipher.doFinal(encryptionKey);
// Algorithm 9a: Compute O
byte[] ownerPasswordBytes = truncate127(ownerPassword.getBytes(Charsets.UTF_8));
byte[] ownerValidationSalt = new byte[8];
byte[] ownerKeySalt = new byte[8];
rnd.nextBytes(ownerValidationSalt);
rnd.nextBytes(ownerKeySalt);
byte[] hashO = computeHash2B(concat(ownerPasswordBytes, ownerValidationSalt, u),
ownerPasswordBytes, u);
byte[] o = concat(hashO, ownerValidationSalt, ownerKeySalt);
// Algorithm 9b: Compute OE
byte[] hashOE = computeHash2B(concat(ownerPasswordBytes, ownerKeySalt, u),
ownerPasswordBytes, u);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashOE, ""AES""),
new IvParameterSpec(new byte[16]));
byte[] oe = cipher.doFinal(encryptionKey);
// Set keys and other required constants in encryption dictionary
encryptionDictionary.setUserKey(u);
encryptionDictionary.setUserEncryptionKey(ue);
encryptionDictionary.setOwnerKey(o);
encryptionDictionary.setOwnerEncryptionKey(oe);
prepareEncryptionDictAES(encryptionDictionary, COSName.AESV3);
// Algorithm 10: compute ""Perms"" value
byte[] perms = new byte[16];
perms[0] = (byte) permissionInt;
perms[1] = (byte) (permissionInt >>> 8);
perms[2] = (byte) (permissionInt >>> 16);
perms[3] = (byte) (permissionInt >>> 24);
perms[4] = (byte) 0xFF;
perms[5] = (byte) 0xFF;
perms[6] = (byte) 0xFF;
perms[7] = (byte) 0xFF;
perms[8] = 'T'; // we always encrypt Metadata
perms[9] = 'a';
perms[10] = 'd';
perms[11] = 'b';
for (int i = 12; i <= 15; i++)
{
perms[i] = (byte) rnd.nextInt();
}
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, ""AES""),
new IvParameterSpec(new byte[16]));
byte[] permsEnc = cipher.doFinal(perms);
encryptionDictionary.setPerms(permsEnc);
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
",FALSE,StandardSecurityHandler.java
" private void prepareEncryptionDictRev2345(String ownerPassword, String userPassword,
PDEncryption encryptionDictionary, int permissionInt, PDDocument document,
int revision, int length)
throws IOException
{
COSArray idArray = document.getDocument().getDocumentID();
//check if the document has an id yet. If it does not then generate one
if (idArray == null || idArray.size() < 2)
{
MessageDigest md = MessageDigests.getMD5();
BigInteger time = BigInteger.valueOf(System.currentTimeMillis());
md.update(time.toByteArray());
md.update(ownerPassword.getBytes(Charsets.ISO_8859_1));
md.update(userPassword.getBytes(Charsets.ISO_8859_1));
md.update(document.getDocument().toString().getBytes(Charsets.ISO_8859_1));
byte[] id = md.digest(this.toString().getBytes(Charsets.ISO_8859_1));
COSString idString = new COSString(id);
idArray = new COSArray();
idArray.add(idString);
idArray.add(idString);
document.getDocument().setDocumentID(idArray);
}
COSString id = (COSString) idArray.getObject(0);
byte[] ownerBytes = computeOwnerPassword(
ownerPassword.getBytes(Charsets.ISO_8859_1),
userPassword.getBytes(Charsets.ISO_8859_1), revision, length);
byte[] userBytes = computeUserPassword(
userPassword.getBytes(Charsets.ISO_8859_1),
ownerBytes, permissionInt, id.getBytes(), revision, length, true);
encryptionKey = computeEncryptedKey(userPassword.getBytes(Charsets.ISO_8859_1), ownerBytes,
null, null, null, permissionInt, id.getBytes(), revision, length, true, false);
encryptionDictionary.setOwnerKey(ownerBytes);
encryptionDictionary.setUserKey(userBytes);
if (revision == 4)
{
prepareEncryptionDictAES(encryptionDictionary, COSName.AESV2);
}
}
"," private void prepareEncryptionDictRev2345(String ownerPassword, String userPassword,
PDEncryption encryptionDictionary, int permissionInt, PDDocument document,
int revision, int length)
throws IOException
{
COSArray idArray = document.getDocument().getDocumentID();
//check if the document has an id yet. If it does not then generate one
if (idArray == null || idArray.size() < 2)
{
MessageDigest md = MessageDigests.getMD5();
BigInteger time = BigInteger.valueOf(System.currentTimeMillis());
md.update(time.toByteArray());
md.update(ownerPassword.getBytes(Charsets.ISO_8859_1));
md.update(userPassword.getBytes(Charsets.ISO_8859_1));
md.update(document.getDocument().toString().getBytes(Charsets.ISO_8859_1));
byte[] id = md.digest(this.toString().getBytes(Charsets.ISO_8859_1));
COSString idString = new COSString(id);
idArray = new COSArray();
idArray.add(idString);
idArray.add(idString);
document.getDocument().setDocumentID(idArray);
}
COSString id = (COSString) idArray.getObject(0);
byte[] ownerBytes = computeOwnerPassword(
ownerPassword.getBytes(Charsets.ISO_8859_1),
userPassword.getBytes(Charsets.ISO_8859_1), revision, length);
byte[] userBytes = computeUserPassword(
userPassword.getBytes(Charsets.ISO_8859_1),
ownerBytes, permissionInt, id.getBytes(), revision, length, true);
encryptionKey = computeEncryptedKey(userPassword.getBytes(Charsets.ISO_8859_1), ownerBytes,
null, null, null, permissionInt, id.getBytes(), revision, length, true, false);
encryptionDictionary.setOwnerKey(ownerBytes);
encryptionDictionary.setUserKey(userBytes);
if (revision == 4)
{
prepareEncryptionDictAES(encryptionDictionary, COSName.AESV2);
}
}
",FALSE,StandardSecurityHandler.java
" private void prepareEncryptionDictAES(PDEncryption encryptionDictionary, COSName aesVName)
{
PDCryptFilterDictionary cryptFilterDictionary = new PDCryptFilterDictionary();
cryptFilterDictionary.setCryptFilterMethod(aesVName);
cryptFilterDictionary.setLength(keyLength);
encryptionDictionary.setStdCryptFilterDictionary(cryptFilterDictionary);
encryptionDictionary.setStreamFilterName(COSName.STD_CF);
encryptionDictionary.setStringFilterName(COSName.STD_CF);
setAES(true);
}
"," private void prepareEncryptionDictAES(PDEncryption encryptionDictionary, COSName aesVName)
{
PDCryptFilterDictionary cryptFilterDictionary = new PDCryptFilterDictionary();
cryptFilterDictionary.setCryptFilterMethod(aesVName);
cryptFilterDictionary.setLength(keyLength);
encryptionDictionary.setStdCryptFilterDictionary(cryptFilterDictionary);
encryptionDictionary.setStreamFilterName(COSName.STD_CF);
encryptionDictionary.setStringFilterName(COSName.STD_CF);
setAES(true);
}
",FALSE,StandardSecurityHandler.java
" public boolean isOwnerPassword(byte[] ownerPassword, byte[] user, byte[] owner,
int permissions, byte[] id, int encRevision, int length,
boolean encryptMetadata) throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
byte[] truncatedOwnerPassword = truncate127(ownerPassword);
byte[] oHash = new byte[32];
byte[] oValidationSalt = new byte[8];
System.arraycopy(owner, 0, oHash, 0, 32);
System.arraycopy(owner, 32, oValidationSalt, 0, 8);
byte[] hash;
if (encRevision == 5)
{
hash = computeSHA256(truncatedOwnerPassword, oValidationSalt, user);
}
else
{
hash = computeHash2A(truncatedOwnerPassword, oValidationSalt, user);
}
return Arrays.equals(hash, oHash);
}
else
{
byte[] userPassword = getUserPassword( ownerPassword, owner, encRevision, length );
return isUserPassword( userPassword, user, owner, permissions, id, encRevision, length,
encryptMetadata );
}
}
"," public boolean isOwnerPassword(byte[] ownerPassword, byte[] user, byte[] owner,
int permissions, byte[] id, int encRevision, int length,
boolean encryptMetadata) throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
byte[] truncatedOwnerPassword = truncate127(ownerPassword);
byte[] oHash = new byte[32];
byte[] oValidationSalt = new byte[8];
System.arraycopy(owner, 0, oHash, 0, 32);
System.arraycopy(owner, 32, oValidationSalt, 0, 8);
byte[] hash;
if (encRevision == 5)
{
hash = computeSHA256(truncatedOwnerPassword, oValidationSalt, user);
}
else
{
hash = computeHash2A(truncatedOwnerPassword, oValidationSalt, user);
}
return Arrays.equals(hash, oHash);
}
else
{
byte[] userPassword = getUserPassword( ownerPassword, owner, encRevision, length );
return isUserPassword( userPassword, user, owner, permissions, id, encRevision, length,
encryptMetadata );
}
}
",FALSE,StandardSecurityHandler.java
" public byte[] getUserPassword( byte[] ownerPassword, byte[] owner, int encRevision,
int length ) throws IOException
{
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] rc4Key = computeRC4key(ownerPassword, encRevision, length);
if( encRevision == 2 )
{
encryptDataRC4(rc4Key, owner, result);
}
else if( encRevision == 3 || encRevision == 4)
{
byte[] iterationKey = new byte[ rc4Key.length ];
byte[] otemp = new byte[ owner.length ];
System.arraycopy( owner, 0, otemp, 0, owner.length );
for( int i=19; i>=0; i-- )
{
System.arraycopy( rc4Key, 0, iterationKey, 0, rc4Key.length );
for( int j=0; j< iterationKey.length; j++ )
{
iterationKey[j] = (byte)(iterationKey[j] ^ (byte)i);
}
result.reset();
encryptDataRC4(iterationKey, otemp, result);
otemp = result.toByteArray();
}
}
return result.toByteArray();
}
"," public byte[] getUserPassword( byte[] ownerPassword, byte[] owner, int encRevision,
int length ) throws IOException
{
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] rc4Key = computeRC4key(ownerPassword, encRevision, length);
if( encRevision == 2 )
{
encryptDataRC4(rc4Key, owner, result);
}
else if( encRevision == 3 || encRevision == 4)
{
byte[] iterationKey = new byte[ rc4Key.length ];
byte[] otemp = new byte[ owner.length ];
System.arraycopy( owner, 0, otemp, 0, owner.length );
for( int i=19; i>=0; i-- )
{
System.arraycopy( rc4Key, 0, iterationKey, 0, rc4Key.length );
for( int j=0; j< iterationKey.length; j++ )
{
iterationKey[j] = (byte)(iterationKey[j] ^ (byte)i);
}
result.reset();
encryptDataRC4(iterationKey, otemp, result);
otemp = result.toByteArray();
}
}
return result.toByteArray();
}
",FALSE,StandardSecurityHandler.java
" public byte[] computeEncryptedKey(byte[] password, byte[] o, byte[] u, byte[] oe, byte[] ue,
int permissions, byte[] id, int encRevision, int length,
boolean encryptMetadata, boolean isOwnerPassword)
throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
return computeEncryptedKeyRev56(password, isOwnerPassword, o, u, oe, ue, encRevision);
}
else
{
return computeEncryptedKeyRev234(password, o, permissions, id, encryptMetadata, length, encRevision);
}
}
"," public byte[] computeEncryptedKey(byte[] password, byte[] o, byte[] u, byte[] oe, byte[] ue,
int permissions, byte[] id, int encRevision, int length,
boolean encryptMetadata, boolean isOwnerPassword)
throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
return computeEncryptedKeyRev56(password, isOwnerPassword, o, u, oe, ue, encRevision);
}
else
{
return computeEncryptedKeyRev234(password, o, permissions, id, encryptMetadata, length, encRevision);
}
}
",FALSE,StandardSecurityHandler.java
" private byte[] computeEncryptedKeyRev234(byte[] password, byte[] o, int permissions,
byte[] id, boolean encryptMetadata, int length, int encRevision)
{
//Algorithm 2, based on MD5
//PDFReference 1.4 pg 78
byte[] padded = truncateOrPad(password);
MessageDigest md = MessageDigests.getMD5();
md.update(padded);
md.update(o);
md.update((byte) permissions);
md.update((byte) (permissions >>> 8));
md.update((byte) (permissions >>> 16));
md.update((byte) (permissions >>> 24));
md.update(id);
//(Security handlers of revision 4 or greater) If document metadata is not being
// encrypted, pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.
//see 7.6.3.3 Algorithm 2 Step f of PDF 32000-1:2008
if (encRevision == 4 && !encryptMetadata)
{
md.update(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
}
byte[] digest = md.digest();
if (encRevision == 3 || encRevision == 4)
{
for (int i = 0; i < 50; i++)
{
md.update(digest, 0, length);
digest = md.digest();
}
}
byte[] result = new byte[length];
System.arraycopy(digest, 0, result, 0, length);
return result;
}
"," private byte[] computeEncryptedKeyRev234(byte[] password, byte[] o, int permissions,
byte[] id, boolean encryptMetadata, int length, int encRevision)
{
//Algorithm 2, based on MD5
//PDFReference 1.4 pg 78
byte[] padded = truncateOrPad(password);
MessageDigest md = MessageDigests.getMD5();
md.update(padded);
md.update(o);
md.update((byte) permissions);
md.update((byte) (permissions >>> 8));
md.update((byte) (permissions >>> 16));
md.update((byte) (permissions >>> 24));
md.update(id);
//(Security handlers of revision 4 or greater) If document metadata is not being
// encrypted, pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.
//see 7.6.3.3 Algorithm 2 Step f of PDF 32000-1:2008
if (encRevision == 4 && !encryptMetadata)
{
md.update(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
}
byte[] digest = md.digest();
if (encRevision == 3 || encRevision == 4)
{
for (int i = 0; i < 50; i++)
{
md.update(digest, 0, length);
digest = md.digest();
}
}
byte[] result = new byte[length];
System.arraycopy(digest, 0, result, 0, length);
return result;
}
",FALSE,StandardSecurityHandler.java
" private byte[] computeEncryptedKeyRev56(byte[] password, boolean isOwnerPassword,
byte[] o, byte[] u, byte[] oe, byte[] ue, int encRevision)
throws IOException
{
byte[] hash, fileKeyEnc;
if (isOwnerPassword)
{
byte[] oKeySalt = new byte[8];
System.arraycopy(o, 40, oKeySalt, 0, 8);
if (encRevision == 5)
{
hash = computeSHA256(password, oKeySalt, u);
}
else
{
hash = computeHash2A(password, oKeySalt, u);
}
fileKeyEnc = oe;
}
else
{
byte[] uKeySalt = new byte[8];
System.arraycopy(u, 40, uKeySalt, 0, 8);
if (encRevision == 5)
{
hash = computeSHA256(password, uKeySalt, null);
}
else
{
hash = computeHash2A(password, uKeySalt, null);
}
fileKeyEnc = ue;
}
try
{
Cipher cipher = Cipher.getInstance(""AES/CBC/NoPadding"");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hash, ""AES""), new IvParameterSpec(new byte[16]));
return cipher.doFinal(fileKeyEnc);
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
"," private byte[] computeEncryptedKeyRev56(byte[] password, boolean isOwnerPassword,
byte[] o, byte[] u, byte[] oe, byte[] ue, int encRevision)
throws IOException
{
byte[] hash, fileKeyEnc;
if (isOwnerPassword)
{
byte[] oKeySalt = new byte[8];
System.arraycopy(o, 40, oKeySalt, 0, 8);
if (encRevision == 5)
{
hash = computeSHA256(password, oKeySalt, u);
}
else
{
hash = computeHash2A(password, oKeySalt, u);
}
fileKeyEnc = oe;
}
else
{
byte[] uKeySalt = new byte[8];
System.arraycopy(u, 40, uKeySalt, 0, 8);
if (encRevision == 5)
{
hash = computeSHA256(password, uKeySalt, null);
}
else
{
hash = computeHash2A(password, uKeySalt, null);
}
fileKeyEnc = ue;
}
try
{
Cipher cipher = Cipher.getInstance(""AES/CBC/NoPadding"");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hash, ""AES""), new IvParameterSpec(new byte[16]));
return cipher.doFinal(fileKeyEnc);
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
",FALSE,StandardSecurityHandler.java
" public byte[] computeUserPassword(byte[] password, byte[] owner, int permissions,
byte[] id, int encRevision, int length,
boolean encryptMetadata) throws IOException
{
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] encKey = computeEncryptedKey( password, owner, null, null, null, permissions,
id, encRevision, length, encryptMetadata, true );
if( encRevision == 2 )
{
encryptDataRC4(encKey, ENCRYPT_PADDING, result );
}
else if( encRevision == 3 || encRevision == 4 )
{
MessageDigest md = MessageDigests.getMD5();
md.update( ENCRYPT_PADDING );
md.update( id );
result.write( md.digest() );
byte[] iterationKey = new byte[ encKey.length ];
for( int i=0; i<20; i++ )
{
System.arraycopy( encKey, 0, iterationKey, 0, iterationKey.length );
for( int j=0; j< iterationKey.length; j++ )
{
iterationKey[j] = (byte)(iterationKey[j] ^ i);
}
ByteArrayInputStream input = new ByteArrayInputStream(result.toByteArray());
result.reset();
encryptDataRC4(iterationKey, input, result);
}
byte[] finalResult = new byte[32];
System.arraycopy( result.toByteArray(), 0, finalResult, 0, 16 );
System.arraycopy( ENCRYPT_PADDING, 0, finalResult, 16, 16 );
result.reset();
result.write( finalResult );
}
return result.toByteArray();
}
"," public byte[] computeUserPassword(byte[] password, byte[] owner, int permissions,
byte[] id, int encRevision, int length,
boolean encryptMetadata) throws IOException
{
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] encKey = computeEncryptedKey( password, owner, null, null, null, permissions,
id, encRevision, length, encryptMetadata, true );
if( encRevision == 2 )
{
encryptDataRC4(encKey, ENCRYPT_PADDING, result );
}
else if( encRevision == 3 || encRevision == 4 )
{
MessageDigest md = MessageDigests.getMD5();
md.update( ENCRYPT_PADDING );
md.update( id );
result.write( md.digest() );
byte[] iterationKey = new byte[ encKey.length ];
for( int i=0; i<20; i++ )
{
System.arraycopy( encKey, 0, iterationKey, 0, iterationKey.length );
for( int j=0; j< iterationKey.length; j++ )
{
iterationKey[j] = (byte)(iterationKey[j] ^ i);
}
ByteArrayInputStream input = new ByteArrayInputStream(result.toByteArray());
result.reset();
encryptDataRC4(iterationKey, input, result);
}
byte[] finalResult = new byte[32];
System.arraycopy( result.toByteArray(), 0, finalResult, 0, 16 );
System.arraycopy( ENCRYPT_PADDING, 0, finalResult, 16, 16 );
result.reset();
result.write( finalResult );
}
return result.toByteArray();
}
",FALSE,StandardSecurityHandler.java
" public byte[] computeOwnerPassword(byte[] ownerPassword, byte[] userPassword,
int encRevision, int length ) throws IOException
{
if( encRevision == 2 && length != 5 )
{
throw new IOException(""Expected length=5 actual="" + length );
}
byte[] rc4Key = computeRC4key(ownerPassword, encRevision, length);
byte[] paddedUser = truncateOrPad( userPassword );
ByteArrayOutputStream encrypted = new ByteArrayOutputStream();
encryptDataRC4(rc4Key, new ByteArrayInputStream(paddedUser), encrypted);
if( encRevision == 3 || encRevision == 4 )
{
byte[] iterationKey = new byte[ rc4Key.length ];
for( int i=1; i<20; i++ )
{
System.arraycopy( rc4Key, 0, iterationKey, 0, rc4Key.length );
for( int j=0; j< iterationKey.length; j++ )
{
iterationKey[j] = (byte)(iterationKey[j] ^ (byte)i);
}
ByteArrayInputStream input = new ByteArrayInputStream( encrypted.toByteArray() );
encrypted.reset();
encryptDataRC4(iterationKey, input, encrypted );
}
}
return encrypted.toByteArray();
}
"," public byte[] computeOwnerPassword(byte[] ownerPassword, byte[] userPassword,
int encRevision, int length ) throws IOException
{
if( encRevision == 2 && length != 5 )
{
throw new IOException(""Expected length=5 actual="" + length );
}
byte[] rc4Key = computeRC4key(ownerPassword, encRevision, length);
byte[] paddedUser = truncateOrPad( userPassword );
ByteArrayOutputStream encrypted = new ByteArrayOutputStream();
encryptDataRC4(rc4Key, new ByteArrayInputStream(paddedUser), encrypted);
if( encRevision == 3 || encRevision == 4 )
{
byte[] iterationKey = new byte[ rc4Key.length ];
for( int i=1; i<20; i++ )
{
System.arraycopy( rc4Key, 0, iterationKey, 0, rc4Key.length );
for( int j=0; j< iterationKey.length; j++ )
{
iterationKey[j] = (byte)(iterationKey[j] ^ (byte)i);
}
ByteArrayInputStream input = new ByteArrayInputStream( encrypted.toByteArray() );
encrypted.reset();
encryptDataRC4(iterationKey, input, encrypted );
}
}
return encrypted.toByteArray();
}
",FALSE,StandardSecurityHandler.java
" private byte[] computeRC4key(byte[] ownerPassword, int encRevision, int length)
{
MessageDigest md = MessageDigests.getMD5();
byte[] digest = md.digest(truncateOrPad(ownerPassword));
if (encRevision == 3 || encRevision == 4)
{
for (int i = 0; i < 50; i++)
{
// this deviates from the spec - however, omitting the length
// parameter prevents the file to be opened in Adobe Reader
// with the owner password when the key length is 40 bit (= 5 bytes)
md.update(digest, 0, length);
digest = md.digest();
}
}
byte[] rc4Key = new byte[length];
System.arraycopy(digest, 0, rc4Key, 0, length);
return rc4Key;
}
"," private byte[] computeRC4key(byte[] ownerPassword, int encRevision, int length)
{
MessageDigest md = MessageDigests.getMD5();
byte[] digest = md.digest(truncateOrPad(ownerPassword));
if (encRevision == 3 || encRevision == 4)
{
for (int i = 0; i < 50; i++)
{
// this deviates from the spec - however, omitting the length
// parameter prevents the file to be opened in Adobe Reader
// with the owner password when the key length is 40 bit (= 5 bytes)
md.update(digest, 0, length);
digest = md.digest();
}
}
byte[] rc4Key = new byte[length];
System.arraycopy(digest, 0, rc4Key, 0, length);
return rc4Key;
}
",FALSE,StandardSecurityHandler.java
" private byte[] truncateOrPad( byte[] password )
{
byte[] padded = new byte[ ENCRYPT_PADDING.length ];
int bytesBeforePad = Math.min( password.length, padded.length );
System.arraycopy( password, 0, padded, 0, bytesBeforePad );
System.arraycopy( ENCRYPT_PADDING, 0, padded, bytesBeforePad,
ENCRYPT_PADDING.length-bytesBeforePad );
return padded;
}
"," private byte[] truncateOrPad( byte[] password )
{
byte[] padded = new byte[ ENCRYPT_PADDING.length ];
int bytesBeforePad = Math.min( password.length, padded.length );
System.arraycopy( password, 0, padded, 0, bytesBeforePad );
System.arraycopy( ENCRYPT_PADDING, 0, padded, bytesBeforePad,
ENCRYPT_PADDING.length-bytesBeforePad );
return padded;
}
",FALSE,StandardSecurityHandler.java
" public boolean isUserPassword(byte[] password, byte[] user, byte[] owner, int permissions,
byte[] id, int encRevision, int length, boolean encryptMetadata)
throws IOException
{
if( encRevision == 2 )
{
byte[] passwordBytes = computeUserPassword( password, owner, permissions, id, encRevision,
length, encryptMetadata );
return Arrays.equals(user, passwordBytes);
}
else if( encRevision == 3 || encRevision == 4 )
{
byte[] passwordBytes = computeUserPassword( password, owner, permissions, id, encRevision,
length, encryptMetadata );
// compare first 16 bytes only
return Arrays.equals(Arrays.copyOf(user, 16), Arrays.copyOf(passwordBytes, 16));
}
else if (encRevision == 6 || encRevision == 5)
{
byte[] truncatedPassword = truncate127(password);
byte[] uHash = new byte[32];
byte[] uValidationSalt = new byte[8];
System.arraycopy(user, 0, uHash, 0, 32);
System.arraycopy(user, 32, uValidationSalt, 0, 8);
byte[] hash;
if (encRevision == 5)
{
hash = computeSHA256(truncatedPassword, uValidationSalt, null);
}
else
{
hash = computeHash2A(truncatedPassword, uValidationSalt, null);
}
return Arrays.equals(hash, uHash);
}
else
{
throw new IOException( ""Unknown Encryption Revision "" + encRevision );
}
}
"," public boolean isUserPassword(byte[] password, byte[] user, byte[] owner, int permissions,
byte[] id, int encRevision, int length, boolean encryptMetadata)
throws IOException
{
if( encRevision == 2 )
{
byte[] passwordBytes = computeUserPassword( password, owner, permissions, id, encRevision,
length, encryptMetadata );
return Arrays.equals(user, passwordBytes);
}
else if( encRevision == 3 || encRevision == 4 )
{
byte[] passwordBytes = computeUserPassword( password, owner, permissions, id, encRevision,
length, encryptMetadata );
// compare first 16 bytes only
return Arrays.equals(Arrays.copyOf(user, 16), Arrays.copyOf(passwordBytes, 16));
}
else if (encRevision == 6 || encRevision == 5)
{
byte[] truncatedPassword = truncate127(password);
byte[] uHash = new byte[32];
byte[] uValidationSalt = new byte[8];
System.arraycopy(user, 0, uHash, 0, 32);
System.arraycopy(user, 32, uValidationSalt, 0, 8);
byte[] hash;
if (encRevision == 5)
{
hash = computeSHA256(truncatedPassword, uValidationSalt, null);
}
else
{
hash = computeHash2A(truncatedPassword, uValidationSalt, null);
}
return Arrays.equals(hash, uHash);
}
else
{
throw new IOException( ""Unknown Encryption Revision "" + encRevision );
}
}
",FALSE,StandardSecurityHandler.java
" public boolean isUserPassword(String password, byte[] user, byte[] owner, int permissions,
byte[] id, int encRevision, int length, boolean encryptMetadata)
throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
return isUserPassword(password.getBytes(Charsets.UTF_8), user, owner, permissions, id,
encRevision, length, encryptMetadata);
}
else
{
return isUserPassword(password.getBytes(Charsets.ISO_8859_1), user, owner, permissions, id,
encRevision, length, encryptMetadata);
}
}
"," public boolean isUserPassword(String password, byte[] user, byte[] owner, int permissions,
byte[] id, int encRevision, int length, boolean encryptMetadata)
throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
return isUserPassword(password.getBytes(Charsets.UTF_8), user, owner, permissions, id,
encRevision, length, encryptMetadata);
}
else
{
return isUserPassword(password.getBytes(Charsets.ISO_8859_1), user, owner, permissions, id,
encRevision, length, encryptMetadata);
}
}
",FALSE,StandardSecurityHandler.java
" public boolean isOwnerPassword(String password, byte[] user, byte[] owner, int permissions,
byte[] id, int encRevision, int length, boolean encryptMetadata)
throws IOException
{
return isOwnerPassword(password.getBytes(Charsets.ISO_8859_1), user,owner,permissions, id,
encRevision, length, encryptMetadata);
}
"," public boolean isOwnerPassword(String password, byte[] user, byte[] owner, int permissions,
byte[] id, int encRevision, int length, boolean encryptMetadata)
throws IOException
{
return isOwnerPassword(password.getBytes(Charsets.ISO_8859_1), user,owner,permissions, id,
encRevision, length, encryptMetadata);
}
",FALSE,StandardSecurityHandler.java
" private byte[] computeHash2A(byte[] password, byte[] salt, byte[] u) throws IOException
{
byte[] userKey;
if (u == null)
{
userKey = new byte[0];
}
else if (u.length < 48)
{
throw new IOException(""Bad U length"");
}
else if (u.length > 48)
{
// must truncate
userKey = new byte[48];
System.arraycopy(u, 0, userKey, 0, 48);
}
else
{
userKey = u;
}
byte[] truncatedPassword = truncate127(password);
byte[] input = concat(truncatedPassword, salt, userKey);
return computeHash2B(input, truncatedPassword, userKey);
}
"," private byte[] computeHash2A(byte[] password, byte[] salt, byte[] u) throws IOException
{
byte[] userKey;
if (u == null)
{
userKey = new byte[0];
}
else if (u.length < 48)
{
throw new IOException(""Bad U length"");
}
else if (u.length > 48)
{
// must truncate
userKey = new byte[48];
System.arraycopy(u, 0, userKey, 0, 48);
}
else
{
userKey = u;
}
byte[] truncatedPassword = truncate127(password);
byte[] input = concat(truncatedPassword, salt, userKey);
return computeHash2B(input, truncatedPassword, userKey);
}
",FALSE,StandardSecurityHandler.java
" private static byte[] computeHash2B(byte[] input, byte[] password, byte[] userKey)
throws IOException
{
try
{
MessageDigest md = MessageDigest.getInstance(""SHA-256"");
byte[] k = md.digest(input);
byte[] e = null;
for (int round = 0; round < 64 || ((int)e[e.length-1] & 0xFF) > round - 32; round++)
{
byte[] k1;
if (userKey != null && userKey.length >= 48)
{
k1 = new byte[64*(password.length + k.length + 48)];
}
else
{
k1 = new byte[64*(password.length + k.length)];
}
int pos = 0;
for (int i = 0; i < 64; i++)
{
System.arraycopy(password, 0, k1, pos, password.length);
pos += password.length;
System.arraycopy(k, 0, k1, pos, k.length);
pos += k.length;
if (userKey != null && userKey.length >= 48)
{
System.arraycopy(userKey, 0, k1, pos, 48);
pos += 48;
}
}
byte[] kFirst = new byte[16];
byte[] kSecond = new byte[16];
System.arraycopy(k, 0, kFirst, 0, 16);
System.arraycopy(k, 16, kSecond, 0, 16);
Cipher cipher = Cipher.getInstance(""AES/CBC/NoPadding"");
SecretKeySpec keySpec = new SecretKeySpec(kFirst, ""AES"");
IvParameterSpec ivSpec = new IvParameterSpec(kSecond);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
e = cipher.doFinal(k1);
byte[] eFirst = new byte[16];
System.arraycopy(e, 0, eFirst, 0, 16);
BigInteger bi = new BigInteger(1, eFirst);
BigInteger remainder = bi.mod(new BigInteger(""3""));
String nextHash = HASHES_2B[remainder.intValue()];
md = MessageDigest.getInstance(nextHash);
k = md.digest(e);
}
if (k.length > 32)
{
byte[] kTrunc = new byte[32];
System.arraycopy(k, 0, kTrunc, 0, 32);
return kTrunc;
}
else
{
return k;
}
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
"," private static byte[] computeHash2B(byte[] input, byte[] password, byte[] userKey)
throws IOException
{
try
{
MessageDigest md = MessageDigest.getInstance(""SHA-256"");
byte[] k = md.digest(input);
byte[] e = null;
for (int round = 0; round < 64 || ((int)e[e.length-1] & 0xFF) > round - 32; round++)
{
byte[] k1;
if (userKey != null && userKey.length >= 48)
{
k1 = new byte[64*(password.length + k.length + 48)];
}
else
{
k1 = new byte[64*(password.length + k.length)];
}
int pos = 0;
for (int i = 0; i < 64; i++)
{
System.arraycopy(password, 0, k1, pos, password.length);
pos += password.length;
System.arraycopy(k, 0, k1, pos, k.length);
pos += k.length;
if (userKey != null && userKey.length >= 48)
{
System.arraycopy(userKey, 0, k1, pos, 48);
pos += 48;
}
}
byte[] kFirst = new byte[16];
byte[] kSecond = new byte[16];
System.arraycopy(k, 0, kFirst, 0, 16);
System.arraycopy(k, 16, kSecond, 0, 16);
Cipher cipher = Cipher.getInstance(""AES/CBC/NoPadding"");
SecretKeySpec keySpec = new SecretKeySpec(kFirst, ""AES"");
IvParameterSpec ivSpec = new IvParameterSpec(kSecond);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
e = cipher.doFinal(k1);
byte[] eFirst = new byte[16];
System.arraycopy(e, 0, eFirst, 0, 16);
BigInteger bi = new BigInteger(1, eFirst);
BigInteger remainder = bi.mod(new BigInteger(""3""));
String nextHash = HASHES_2B[remainder.intValue()];
md = MessageDigest.getInstance(nextHash);
k = md.digest(e);
}
if (k.length > 32)
{
byte[] kTrunc = new byte[32];
System.arraycopy(k, 0, kTrunc, 0, 32);
return kTrunc;
}
else
{
return k;
}
}
catch (GeneralSecurityException e)
{
logIfStrongEncryptionMissing();
throw new IOException(e);
}
}
",FALSE,StandardSecurityHandler.java
" private static byte[] computeSHA256(byte[] input, byte[] password, byte[] userKey)
throws IOException
{
try
{
MessageDigest md = MessageDigest.getInstance(""SHA-256"");
md.update(input);
md.update(password);
return userKey == null ? md.digest() : md.digest(userKey);
}
catch (NoSuchAlgorithmException e)
{
throw new IOException(e);
}
}
"," private static byte[] computeSHA256(byte[] input, byte[] password, byte[] userKey)
throws IOException
{
try
{
MessageDigest md = MessageDigest.getInstance(""SHA-256"");
md.update(input);
md.update(password);
return userKey == null ? md.digest() : md.digest(userKey);
}
catch (NoSuchAlgorithmException e)
{
throw new IOException(e);
}
}
",FALSE,StandardSecurityHandler.java
" private static byte[] concat(byte[] a, byte[] b)
{
byte[] o = new byte[a.length + b.length];
System.arraycopy(a, 0, o, 0, a.length);
System.arraycopy(b, 0, o, a.length, b.length);
return o;
}
"," private static byte[] concat(byte[] a, byte[] b)
{
byte[] o = new byte[a.length + b.length];
System.arraycopy(a, 0, o, 0, a.length);
System.arraycopy(b, 0, o, a.length, b.length);
return o;
}
",FALSE,StandardSecurityHandler.java
" private static byte[] concat(byte[] a, byte[] b, byte[] c)
{
byte[] o = new byte[a.length + b.length + c.length];
System.arraycopy(a, 0, o, 0, a.length);
System.arraycopy(b, 0, o, a.length, b.length);
System.arraycopy(c, 0, o, a.length + b.length, c.length);
return o;
}
"," private static byte[] concat(byte[] a, byte[] b, byte[] c)
{
byte[] o = new byte[a.length + b.length + c.length];
System.arraycopy(a, 0, o, 0, a.length);
System.arraycopy(b, 0, o, a.length, b.length);
System.arraycopy(c, 0, o, a.length + b.length, c.length);
return o;
}
",FALSE,StandardSecurityHandler.java
" private static byte[] truncate127(byte[] in)
{
if (in.length <= 127)
{
return in;
}
byte[] trunc = new byte[127];
System.arraycopy(in, 0, trunc, 0, 127);
return trunc;
}
"," private static byte[] truncate127(byte[] in)
{
if (in.length <= 127)
{
return in;
}
byte[] trunc = new byte[127];
System.arraycopy(in, 0, trunc, 0, 127);
return trunc;
}
",FALSE,StandardSecurityHandler.java
" private static void logIfStrongEncryptionMissing()
{
try
{
if (Cipher.getMaxAllowedKeyLength(""AES"") != Integer.MAX_VALUE)
{
LOG.warn(""JCE unlimited strength jurisdiction policy files are not installed"");
}
}
catch (NoSuchAlgorithmException ex)
{
}
}
"," private static void logIfStrongEncryptionMissing()
{
try
{
if (Cipher.getMaxAllowedKeyLength(""AES"") != Integer.MAX_VALUE)
{
LOG.warn(""JCE unlimited strength jurisdiction policy files are not installed"");
}
}
catch (NoSuchAlgorithmException ex)
{
}
}
",FALSE,StandardSecurityHandler.java
" public boolean hasProtectionPolicy()
{
return policy != null;
}
"," public boolean hasProtectionPolicy()
{
return policy != null;
}
",FALSE,StandardSecurityHandler.java
" public void expand(File archive, File targetDirectory) throws IOException, ArchiveException {
String format = null;
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
format = new ArchiveStreamFactory().detect(i);
}
expand(format, archive, targetDirectory);
}
"," public void expand(File archive, File targetDirectory) throws IOException, ArchiveException {
String format = null;
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
format = new ArchiveStreamFactory().detect(i);
}
expand(format, archive, targetDirectory);
}
",FALSE,Expander.java
" public void expand(String format, File archive, File targetDirectory) throws IOException, ArchiveException {
if (prefersSeekableByteChannel(format)) {
try (SeekableByteChannel c = FileChannel.open(archive.toPath(), StandardOpenOption.READ)) {
expand(format, c, targetDirectory);
}
return;
}
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
expand(format, i, targetDirectory);
}
}
"," public void expand(String format, File archive, File targetDirectory) throws IOException, ArchiveException {
if (prefersSeekableByteChannel(format)) {
try (SeekableByteChannel c = FileChannel.open(archive.toPath(), StandardOpenOption.READ)) {
expand(format, c, targetDirectory);
}
return;
}
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
expand(format, i, targetDirectory);
}
}
",FALSE,Expander.java
" public void expand(InputStream archive, File targetDirectory) throws IOException, ArchiveException {
expand(new ArchiveStreamFactory().createArchiveInputStream(archive), targetDirectory);
}
"," public void expand(InputStream archive, File targetDirectory) throws IOException, ArchiveException {
expand(new ArchiveStreamFactory().createArchiveInputStream(archive), targetDirectory);
}
",FALSE,Expander.java
" public void expand(String format, InputStream archive, File targetDirectory)
throws IOException, ArchiveException {
expand(new ArchiveStreamFactory().createArchiveInputStream(format, archive), targetDirectory);
}
"," public void expand(String format, InputStream archive, File targetDirectory)
throws IOException, ArchiveException {
expand(new ArchiveStreamFactory().createArchiveInputStream(format, archive), targetDirectory);
}
",FALSE,Expander.java
" public void expand(String format, SeekableByteChannel archive, File targetDirectory)
throws IOException, ArchiveException {
if (!prefersSeekableByteChannel(format)) {
expand(format, Channels.newInputStream(archive), targetDirectory);
} else if (ArchiveStreamFactory.ZIP.equalsIgnoreCase(format)) {
expand(new ZipFile(archive), targetDirectory);
} else if (ArchiveStreamFactory.SEVEN_Z.equalsIgnoreCase(format)) {
expand(new SevenZFile(archive), targetDirectory);
} else {
// never reached as prefersSeekableByteChannel only returns true for ZIP and 7z
throw new ArchiveException(""don't know how to handle format "" + format);
}
}
"," public void expand(String format, SeekableByteChannel archive, File targetDirectory)
throws IOException, ArchiveException {
if (!prefersSeekableByteChannel(format)) {
expand(format, Channels.newInputStream(archive), targetDirectory);
} else if (ArchiveStreamFactory.ZIP.equalsIgnoreCase(format)) {
expand(new ZipFile(archive), targetDirectory);
} else if (ArchiveStreamFactory.SEVEN_Z.equalsIgnoreCase(format)) {
expand(new SevenZFile(archive), targetDirectory);
} else {
// never reached as prefersSeekableByteChannel only returns true for ZIP and 7z
throw new ArchiveException(""don't know how to handle format "" + format);
}
}
",FALSE,Expander.java
" public void expand(final ArchiveInputStream archive, File targetDirectory)
throws IOException, ArchiveException {
expand(new ArchiveEntrySupplier() {
@Override
public ArchiveEntry getNextReadableEntry() throws IOException {
ArchiveEntry next = archive.getNextEntry();
while (next != null && !archive.canReadEntryData(next)) {
next = archive.getNextEntry();
}
return next;
}
}, new EntryWriter() {
@Override
public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
IOUtils.copy(archive, out);
}
}, targetDirectory);
}
"," public void expand(final ArchiveInputStream archive, File targetDirectory)
throws IOException, ArchiveException {
expand(new ArchiveEntrySupplier() {
@Override
public ArchiveEntry getNextReadableEntry() throws IOException {
ArchiveEntry next = archive.getNextEntry();
while (next != null && !archive.canReadEntryData(next)) {
next = archive.getNextEntry();
}
return next;
}
}, new EntryWriter() {
@Override
public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
IOUtils.copy(archive, out);
}
}, targetDirectory);
}
",FALSE,Expander.java
" public void expand(final ZipFile archive, File targetDirectory)
throws IOException, ArchiveException {
final Enumeration entries = archive.getEntries();
expand(new ArchiveEntrySupplier() {
@Override
public ArchiveEntry getNextReadableEntry() throws IOException {
ZipArchiveEntry next = entries.hasMoreElements() ? entries.nextElement() : null;
while (next != null && !archive.canReadEntryData(next)) {
next = entries.hasMoreElements() ? entries.nextElement() : null;
}
return next;
}
}, new EntryWriter() {
@Override
public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
try (InputStream in = archive.getInputStream((ZipArchiveEntry) entry)) {
IOUtils.copy(in, out);
}
}
}, targetDirectory);
}
"," public void expand(final ZipFile archive, File targetDirectory)
throws IOException, ArchiveException {
final Enumeration entries = archive.getEntries();
expand(new ArchiveEntrySupplier() {
@Override
public ArchiveEntry getNextReadableEntry() throws IOException {
ZipArchiveEntry next = entries.hasMoreElements() ? entries.nextElement() : null;
while (next != null && !archive.canReadEntryData(next)) {
next = entries.hasMoreElements() ? entries.nextElement() : null;
}
return next;
}
}, new EntryWriter() {
@Override
public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
try (InputStream in = archive.getInputStream((ZipArchiveEntry) entry)) {
IOUtils.copy(in, out);
}
}
}, targetDirectory);
}
",FALSE,Expander.java
" public void expand(final SevenZFile archive, File targetDirectory)
throws IOException, ArchiveException {
expand(new ArchiveEntrySupplier() {
@Override
public ArchiveEntry getNextReadableEntry() throws IOException {
return archive.getNextEntry();
}
}, new EntryWriter() {
@Override
public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
final byte[] buffer = new byte[8024];
int n = 0;
long count = 0;
while (-1 != (n = archive.read(buffer))) {
out.write(buffer, 0, n);
count += n;
}
}
}, targetDirectory);
}
"," public void expand(final SevenZFile archive, File targetDirectory)
throws IOException, ArchiveException {
expand(new ArchiveEntrySupplier() {
@Override
public ArchiveEntry getNextReadableEntry() throws IOException {
return archive.getNextEntry();
}
}, new EntryWriter() {
@Override
public void writeEntryDataTo(ArchiveEntry entry, OutputStream out) throws IOException {
final byte[] buffer = new byte[8024];
int n = 0;
long count = 0;
while (-1 != (n = archive.read(buffer))) {
out.write(buffer, 0, n);
count += n;
}
}
}, targetDirectory);
}
",FALSE,Expander.java
" private boolean prefersSeekableByteChannel(String format) {
return ArchiveStreamFactory.ZIP.equalsIgnoreCase(format) || ArchiveStreamFactory.SEVEN_Z.equalsIgnoreCase(format);
}
"," private boolean prefersSeekableByteChannel(String format) {
return ArchiveStreamFactory.ZIP.equalsIgnoreCase(format) || ArchiveStreamFactory.SEVEN_Z.equalsIgnoreCase(format);
}
",FALSE,Expander.java
" private void expand(ArchiveEntrySupplier supplier, EntryWriter writer, File targetDirectory)
throws IOException {
String targetDirPath = targetDirectory.getCanonicalPath();
ArchiveEntry nextEntry = supplier.getNextReadableEntry();
while (nextEntry != null) {
File f = new File(targetDirectory, nextEntry.getName());
if (!f.getCanonicalPath().startsWith(targetDirPath)) {
throw new IOException(""expanding "" + nextEntry.getName()
+ "" would create file outside of "" + targetDirectory);
}
if (nextEntry.isDirectory()) {
if (!f.isDirectory() && !f.mkdirs()) {
throw new IOException(""failed to create directory "" + f);
}
} else {
File parent = f.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException(""failed to create directory "" + parent);
}
try (OutputStream o = Files.newOutputStream(f.toPath())) {
writer.writeEntryDataTo(nextEntry, o);
}
}
nextEntry = supplier.getNextReadableEntry();
}
}
"," private void expand(ArchiveEntrySupplier supplier, EntryWriter writer, File targetDirectory)
throws IOException {
String targetDirPath = targetDirectory.getCanonicalPath() + File.separatorChar;
ArchiveEntry nextEntry = supplier.getNextReadableEntry();
while (nextEntry != null) {
File f = new File(targetDirectory, nextEntry.getName());
if (!f.getCanonicalPath().startsWith(targetDirPath)) {
throw new IOException(""expanding "" + nextEntry.getName()
+ "" would create file outside of "" + targetDirectory);
}
if (nextEntry.isDirectory()) {
if (!f.isDirectory() && !f.mkdirs()) {
throw new IOException(""failed to create directory "" + f);
}
} else {
File parent = f.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException(""failed to create directory "" + parent);
}
try (OutputStream o = Files.newOutputStream(f.toPath())) {
writer.writeEntryDataTo(nextEntry, o);
}
}
nextEntry = supplier.getNextReadableEntry();
}
}
",TRUE,Expander.java
" public void sevenZTwoFileVersion() throws IOException, ArchiveException {
setup7z();
new Expander().expand(""7z"", archive, resultDir);
verifyTargetDir();
}
"," public void sevenZTwoFileVersion() throws IOException, ArchiveException {
setup7z();
new Expander().expand(""7z"", archive, resultDir);
verifyTargetDir();
}
",FALSE,ExpanderTest.java
" public void sevenZTwoFileVersionWithAutoDetection() throws IOException, ArchiveException {
setup7z();
new Expander().expand(archive, resultDir);
verifyTargetDir();
}
"," public void sevenZTwoFileVersionWithAutoDetection() throws IOException, ArchiveException {
setup7z();
new Expander().expand(archive, resultDir);
verifyTargetDir();
}
",FALSE,ExpanderTest.java
" public void sevenZInputStreamVersion() throws IOException, ArchiveException {
setup7z();
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
new Expander().expand(""7z"", i, resultDir);
}
}
"," public void sevenZInputStreamVersion() throws IOException, ArchiveException {
setup7z();
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
new Expander().expand(""7z"", i, resultDir);
}
}
",FALSE,ExpanderTest.java
" public void sevenZInputStreamVersionWithAutoDetection() throws IOException, ArchiveException {
setup7z();
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
new Expander().expand(i, resultDir);
}
}
"," public void sevenZInputStreamVersionWithAutoDetection() throws IOException, ArchiveException {
setup7z();
try (InputStream i = new BufferedInputStream(Files.newInputStream(archive.toPath()))) {
new Expander().expand(i, resultDir);
}
}
",FALSE,ExpanderTest.java
" public void sevenZChannelVersion() throws IOException, ArchiveException {
setup7z();
try (SeekableByteChannel c = FileChannel.open(archive.toPath(), StandardOpenOption.READ)) {
new Expander().expand(""7z"", c, resultDir);
}
verifyTargetDir();
}
"," public void sevenZChannelVersion() throws IOException, ArchiveException {
setup7z();
try (SeekableByteChannel c = FileChannel.open(archive.toPath(), StandardOpenOption.READ)) {
new Expander().expand(""7z"", c, resultDir);
}
verifyTargetDir();
}
",FALSE,ExpanderTest.java
" public void sevenZFileVersion() throws IOException, ArchiveException {
setup7z();
try (SevenZFile f = new SevenZFile(archive)) {
new Expander().expand(f, resultDir);
}
verifyTargetDir();
}
"," public void sevenZFileVersion() throws IOException, ArchiveException {
setup7z();
try (SevenZFile f = new SevenZFile(archive)) {
new Expander().expand(f, resultDir);
}
verifyTargetDir();
}
",FALSE,ExpanderTest.java
" public void zipFileVersion() throws IOException, ArchiveException {
setupZip();
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
verifyTargetDir();
}
"," public void zipFileVersion() throws IOException, ArchiveException {
setupZip();
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
verifyTargetDir();
}
",FALSE,ExpanderTest.java
" public void fileCantEscapeViaAbsolutePath() throws IOException, ArchiveException {
setupZip(""/tmp/foo"");
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
assertHelloWorld(""tmp/foo"", ""1"");
}
"," public void fileCantEscapeViaAbsolutePath() throws IOException, ArchiveException {
setupZip(""/tmp/foo"");
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
assertHelloWorld(""tmp/foo"", ""1"");
}
",FALSE,ExpanderTest.java
" public void fileCantEscapeDoubleDotPath() throws IOException, ArchiveException {
thrown.expect(IOException.class);
thrown.expectMessage(""expanding ../foo would create file outside of"");
setupZip(""../foo"");
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
}
"," public void fileCantEscapeDoubleDotPath() throws IOException, ArchiveException {
thrown.expect(IOException.class);
thrown.expectMessage(""expanding ../foo would create file outside of"");
setupZip(""../foo"");
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
}
",FALSE,ExpanderTest.java
"
"," public void fileCantEscapeDoubleDotPathWithSimilarSibling() throws IOException, ArchiveException {
String sibling = resultDir.getName() + ""x"";
File s = new File(resultDir.getParentFile(), sibling);
Assume.assumeFalse(s.exists());
s.mkdirs();
Assume.assumeTrue(s.exists());
s.deleteOnExit();
try {
thrown.expect(IOException.class);
thrown.expectMessage(""expanding ../"" + sibling + ""/a would create file outside of"");
setupZip(""../"" + sibling + ""/a"");
try (ZipFile f = new ZipFile(archive)) {
new Expander().expand(f, resultDir);
}
} finally {
tryHardToDelete(s);
}
}
",TRUE,ExpanderTest.java
" private void setup7z() throws IOException, ArchiveException {
archive = new File(dir, ""test.7z"");
File dummy = new File(dir, ""x"");
try (OutputStream o = Files.newOutputStream(dummy.toPath())) {
o.write(new byte[14]);
}
try (SevenZOutputFile aos = new SevenZOutputFile(archive)) {
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b/c""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/d.txt""));
aos.write(""Hello, world 1"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/c/e.txt""));
aos.write(""Hello, world 2"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.finish();
}
}
"," private void setup7z() throws IOException, ArchiveException {
archive = new File(dir, ""test.7z"");
File dummy = new File(dir, ""x"");
try (OutputStream o = Files.newOutputStream(dummy.toPath())) {
o.write(new byte[14]);
}
try (SevenZOutputFile aos = new SevenZOutputFile(archive)) {
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b/c""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/d.txt""));
aos.write(""Hello, world 1"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/c/e.txt""));
aos.write(""Hello, world 2"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.finish();
}
}
",FALSE,ExpanderTest.java
" private void setupZip() throws IOException, ArchiveException {
archive = new File(dir, ""test.zip"");
File dummy = new File(dir, ""x"");
try (OutputStream o = Files.newOutputStream(dummy.toPath())) {
o.write(new byte[14]);
}
try (ArchiveOutputStream aos = new ArchiveStreamFactory()
.createArchiveOutputStream(""zip"", Files.newOutputStream(archive.toPath()))) {
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b/c""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/d.txt""));
aos.write(""Hello, world 1"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/c/e.txt""));
aos.write(""Hello, world 2"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.finish();
}
}
"," private void setupZip() throws IOException, ArchiveException {
archive = new File(dir, ""test.zip"");
File dummy = new File(dir, ""x"");
try (OutputStream o = Files.newOutputStream(dummy.toPath())) {
o.write(new byte[14]);
}
try (ArchiveOutputStream aos = new ArchiveStreamFactory()
.createArchiveOutputStream(""zip"", Files.newOutputStream(archive.toPath()))) {
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dir, ""a/b/c""));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/d.txt""));
aos.write(""Hello, world 1"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.putArchiveEntry(aos.createArchiveEntry(dummy, ""a/b/c/e.txt""));
aos.write(""Hello, world 2"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.finish();
}
}
",FALSE,ExpanderTest.java
" private void setupZip(String entry) throws IOException, ArchiveException {
archive = new File(dir, ""test.zip"");
File dummy = new File(dir, ""x"");
try (OutputStream o = Files.newOutputStream(dummy.toPath())) {
o.write(new byte[14]);
}
try (ArchiveOutputStream aos = new ArchiveStreamFactory()
.createArchiveOutputStream(""zip"", Files.newOutputStream(archive.toPath()))) {
aos.putArchiveEntry(aos.createArchiveEntry(dummy, entry));
aos.write(""Hello, world 1"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.finish();
}
}
"," private void setupZip(String entry) throws IOException, ArchiveException {
archive = new File(dir, ""test.zip"");
File dummy = new File(dir, ""x"");
try (OutputStream o = Files.newOutputStream(dummy.toPath())) {
o.write(new byte[14]);
}
try (ArchiveOutputStream aos = new ArchiveStreamFactory()
.createArchiveOutputStream(""zip"", Files.newOutputStream(archive.toPath()))) {
aos.putArchiveEntry(aos.createArchiveEntry(dummy, entry));
aos.write(""Hello, world 1"".getBytes(StandardCharsets.UTF_8));
aos.closeArchiveEntry();
aos.finish();
}
}
",FALSE,ExpanderTest.java
" private void verifyTargetDir() throws IOException {
Assert.assertTrue(""a has not been created"", new File(resultDir, ""a"").isDirectory());
Assert.assertTrue(""a/b has not been created"", new File(resultDir, ""a/b"").isDirectory());
Assert.assertTrue(""a/b/c has not been created"", new File(resultDir, ""a/b/c"").isDirectory());
assertHelloWorld(""a/b/d.txt"", ""1"");
assertHelloWorld(""a/b/c/e.txt"", ""2"");
}
"," private void verifyTargetDir() throws IOException {
Assert.assertTrue(""a has not been created"", new File(resultDir, ""a"").isDirectory());
Assert.assertTrue(""a/b has not been created"", new File(resultDir, ""a/b"").isDirectory());
Assert.assertTrue(""a/b/c has not been created"", new File(resultDir, ""a/b/c"").isDirectory());
assertHelloWorld(""a/b/d.txt"", ""1"");
assertHelloWorld(""a/b/c/e.txt"", ""2"");
}
",FALSE,ExpanderTest.java
" private void assertHelloWorld(String fileName, String suffix) throws IOException {
Assert.assertTrue(fileName + "" does not exist"", new File(resultDir, fileName).isFile());
byte[] expected = (""Hello, world "" + suffix).getBytes(StandardCharsets.UTF_8);
try (InputStream is = Files.newInputStream(new File(resultDir, fileName).toPath())) {
byte[] actual = IOUtils.toByteArray(is);
Assert.assertArrayEquals(expected, actual);
}
}
"," private void assertHelloWorld(String fileName, String suffix) throws IOException {
Assert.assertTrue(fileName + "" does not exist"", new File(resultDir, fileName).isFile());
byte[] expected = (""Hello, world "" + suffix).getBytes(StandardCharsets.UTF_8);
try (InputStream is = Files.newInputStream(new File(resultDir, fileName).toPath())) {
byte[] actual = IOUtils.toByteArray(is);
Assert.assertArrayEquals(expected, actual);
}
}
",FALSE,ExpanderTest.java
" private VersionUtil() {
}
"," private VersionUtil() {
}
",FALSE,VersionUtil.java
" public static void versionMatch(String version) {
if (!version.matches(FORMAT)) {
throw new IllegalArgumentException(""<"" + version
+ ""> does not match format "" + FORMAT);
}
}
"," public static void versionMatch(String version) {
if (!version.matches(FORMAT)) {
throw new IllegalArgumentException(""<"" + version
+ ""> does not match format "" + FORMAT);
}
}
",FALSE,VersionUtil.java
" public static int versionCompare(String fromVersion, String toVersion) {
String[] fromArr = fromVersion.split(""\\."");
String[] toArr = toVersion.split(""\\."");
int fromFirst = Integer.parseInt(fromArr[0]);
int fromMiddle = Integer.parseInt(fromArr[1]);
int fromEnd = Integer.parseInt(fromArr[2]);
int toFirst = Integer.parseInt(toArr[0]);
int toMiddle = Integer.parseInt(toArr[1]);
int toEnd = Integer.parseInt(toArr[2]);
if (fromFirst - toFirst != 0) {
return fromFirst - toFirst;
} else if (fromMiddle - toMiddle != 0) {
return fromMiddle - toMiddle;
} else {
return fromEnd - toEnd;
}
}
"," public static int versionCompare(String fromVersion, String toVersion) {
if (fromVersion == null || toVersion == null) {
return -1;
}
String[] fromArr = fromVersion.split(""\\."");
String[] toArr = toVersion.split(""\\."");
if (fromArr.length != 3 || toArr.length != 3) {
return -1;
}
try {
int fromFirst = Integer.parseInt(fromArr[0]);
int fromMiddle = Integer.parseInt(fromArr[1]);
int fromEnd = Integer.parseInt(fromArr[2]);
int toFirst = Integer.parseInt(toArr[0]);
int toMiddle = Integer.parseInt(toArr[1]);
int toEnd = Integer.parseInt(toArr[2]);
if (fromFirst - toFirst != 0) {
return fromFirst - toFirst;
} else if (fromMiddle - toMiddle != 0) {
return fromMiddle - toMiddle;
} else {
return fromEnd - toEnd;
}
} catch (NumberFormatException nfe) {
return -1;
}
}
",TRUE,VersionUtil.java
" public XmlFactory() { this(null, null, null); }
"," public XmlFactory() { this(null, null, null); }
",FALSE,XmlFactory.java
" public XmlFactory(ObjectCodec oc) {
this(oc, null, null);
}
"," public XmlFactory(ObjectCodec oc) {
this(oc, null, null);
}
",FALSE,XmlFactory.java
" public XmlFactory(XMLInputFactory xmlIn) {
this(null, xmlIn, null);
}
"," public XmlFactory(XMLInputFactory xmlIn) {
this(null, xmlIn, null);
}
",FALSE,XmlFactory.java
" public XmlFactory(XMLInputFactory xmlIn, XMLOutputFactory xmlOut) {
this(null, xmlIn, xmlOut);
}
"," public XmlFactory(XMLInputFactory xmlIn, XMLOutputFactory xmlOut) {
this(null, xmlIn, xmlOut);
}
",FALSE,XmlFactory.java
" public XmlFactory(ObjectCodec oc, XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
this(oc, DEFAULT_XML_PARSER_FEATURE_FLAGS, DEFAULT_XML_GENERATOR_FEATURE_FLAGS,
xmlIn, xmlOut, null);
}
"," public XmlFactory(ObjectCodec oc, XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
this(oc, DEFAULT_XML_PARSER_FEATURE_FLAGS, DEFAULT_XML_GENERATOR_FEATURE_FLAGS,
xmlIn, xmlOut, null);
}
",FALSE,XmlFactory.java
" protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures,
XMLInputFactory xmlIn, XMLOutputFactory xmlOut,
String nameForTextElem)
{
super(oc);
_xmlParserFeatures = xpFeatures;
_xmlGeneratorFeatures = xgFeatures;
_cfgNameForTextElement = nameForTextElem;
if (xmlIn == null) {
xmlIn = XMLInputFactory.newInstance();
// as per [dataformat-xml#190], disable external entity expansion by default
xmlIn.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
}
if (xmlOut == null) {
xmlOut = XMLOutputFactory.newInstance();
}
_initFactories(xmlIn, xmlOut);
_xmlInputFactory = xmlIn;
_xmlOutputFactory = xmlOut;
}
"," protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures,
XMLInputFactory xmlIn, XMLOutputFactory xmlOut,
String nameForTextElem)
{
super(oc);
_xmlParserFeatures = xpFeatures;
_xmlGeneratorFeatures = xgFeatures;
_cfgNameForTextElement = nameForTextElem;
if (xmlIn == null) {
xmlIn = XMLInputFactory.newInstance();
// as per [dataformat-xml#190], disable external entity expansion by default
xmlIn.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
// and ditto wrt [dataformat-xml#211], SUPPORT_DTD
xmlIn.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
}
if (xmlOut == null) {
xmlOut = XMLOutputFactory.newInstance();
}
_initFactories(xmlIn, xmlOut);
_xmlInputFactory = xmlIn;
_xmlOutputFactory = xmlOut;
}
",TRUE,XmlFactory.java
" protected XmlFactory(XmlFactory src, ObjectCodec oc)
{
super(src, oc);
_xmlParserFeatures = src._xmlParserFeatures;
_xmlGeneratorFeatures = src._xmlGeneratorFeatures;
_cfgNameForTextElement = src._cfgNameForTextElement;
_xmlInputFactory = src._xmlInputFactory;
_xmlOutputFactory = src._xmlOutputFactory;
}
"," protected XmlFactory(XmlFactory src, ObjectCodec oc)
{
super(src, oc);
_xmlParserFeatures = src._xmlParserFeatures;
_xmlGeneratorFeatures = src._xmlGeneratorFeatures;
_cfgNameForTextElement = src._cfgNameForTextElement;
_xmlInputFactory = src._xmlInputFactory;
_xmlOutputFactory = src._xmlOutputFactory;
}
",FALSE,XmlFactory.java
" protected void _initFactories(XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
// Better ensure namespaces get built properly, so:
xmlOut.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
// and for parser, force coalescing as well (much simpler to use)
xmlIn.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
}
"," protected void _initFactories(XMLInputFactory xmlIn, XMLOutputFactory xmlOut)
{
// Better ensure namespaces get built properly, so:
xmlOut.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
// and for parser, force coalescing as well (much simpler to use)
xmlIn.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
}
",FALSE,XmlFactory.java
" public XmlFactory copy() {
_checkInvalidCopy(XmlFactory.class);
return new XmlFactory(this, null);
}
"," public XmlFactory copy() {
_checkInvalidCopy(XmlFactory.class);
return new XmlFactory(this, null);
}
",FALSE,XmlFactory.java
" public Version version() {
return PackageVersion.VERSION;
}
"," public Version version() {
return PackageVersion.VERSION;
}
",FALSE,XmlFactory.java
" protected Object readResolve() {
if (_jdkXmlInFactory == null) {
throw new IllegalStateException(""No XMLInputFactory class name read during JDK deserialization"");
}
if (_jdkXmlOutFactory == null) {
throw new IllegalStateException(""No XMLOutputFactory class name read during JDK deserialization"");
}
try {
XMLInputFactory inf = (XMLInputFactory) Class.forName(_jdkXmlInFactory).newInstance();
XMLOutputFactory outf = (XMLOutputFactory) Class.forName(_jdkXmlOutFactory).newInstance();
return new XmlFactory(_objectCodec, _xmlParserFeatures, _xmlGeneratorFeatures,
inf, outf, _cfgNameForTextElement);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
"," protected Object readResolve() {
if (_jdkXmlInFactory == null) {
throw new IllegalStateException(""No XMLInputFactory class name read during JDK deserialization"");
}
if (_jdkXmlOutFactory == null) {
throw new IllegalStateException(""No XMLOutputFactory class name read during JDK deserialization"");
}
try {
XMLInputFactory inf = (XMLInputFactory) Class.forName(_jdkXmlInFactory).newInstance();
XMLOutputFactory outf = (XMLOutputFactory) Class.forName(_jdkXmlOutFactory).newInstance();
return new XmlFactory(_objectCodec, _xmlParserFeatures, _xmlGeneratorFeatures,
inf, outf, _cfgNameForTextElement);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
",FALSE,XmlFactory.java
" private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_jdkXmlInFactory = in.readUTF();
_jdkXmlOutFactory = in.readUTF();
}
"," private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
_jdkXmlInFactory = in.readUTF();
_jdkXmlOutFactory = in.readUTF();
}
",FALSE,XmlFactory.java
" private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeUTF(_xmlInputFactory.getClass().getName());
out.writeUTF(_xmlOutputFactory.getClass().getName());
}
"," private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeUTF(_xmlInputFactory.getClass().getName());
out.writeUTF(_xmlOutputFactory.getClass().getName());
}
",FALSE,XmlFactory.java
" public void setXMLTextElementName(String name) {
_cfgNameForTextElement = name;
}
"," public void setXMLTextElementName(String name) {
_cfgNameForTextElement = name;
}
",FALSE,XmlFactory.java
" public String getXMLTextElementName() {
return _cfgNameForTextElement;
}
"," public String getXMLTextElementName() {
return _cfgNameForTextElement;
}
",FALSE,XmlFactory.java
" public final XmlFactory configure(FromXmlParser.Feature f, boolean state)
{
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
"," public final XmlFactory configure(FromXmlParser.Feature f, boolean state)
{
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory enable(FromXmlParser.Feature f) {
_xmlParserFeatures |= f.getMask();
return this;
}
"," public XmlFactory enable(FromXmlParser.Feature f) {
_xmlParserFeatures |= f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory disable(FromXmlParser.Feature f) {
_xmlParserFeatures &= ~f.getMask();
return this;
}
"," public XmlFactory disable(FromXmlParser.Feature f) {
_xmlParserFeatures &= ~f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public final boolean isEnabled(FromXmlParser.Feature f) {
return (_xmlParserFeatures & f.getMask()) != 0;
}
"," public final boolean isEnabled(FromXmlParser.Feature f) {
return (_xmlParserFeatures & f.getMask()) != 0;
}
",FALSE,XmlFactory.java
" public final XmlFactory configure(ToXmlGenerator.Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
"," public final XmlFactory configure(ToXmlGenerator.Feature f, boolean state) {
if (state) {
enable(f);
} else {
disable(f);
}
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory enable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures |= f.getMask();
return this;
}
"," public XmlFactory enable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures |= f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public XmlFactory disable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures &= ~f.getMask();
return this;
}
"," public XmlFactory disable(ToXmlGenerator.Feature f) {
_xmlGeneratorFeatures &= ~f.getMask();
return this;
}
",FALSE,XmlFactory.java
" public final boolean isEnabled(ToXmlGenerator.Feature f) {
return (_xmlGeneratorFeatures & f.getMask()) != 0;
}
"," public final boolean isEnabled(ToXmlGenerator.Feature f) {
return (_xmlGeneratorFeatures & f.getMask()) != 0;
}
",FALSE,XmlFactory.java
" public XMLInputFactory getXMLInputFactory() {
return _xmlInputFactory;
}
"," public XMLInputFactory getXMLInputFactory() {
return _xmlInputFactory;
}
",FALSE,XmlFactory.java
" public void setXMLInputFactory(XMLInputFactory f) {
_xmlInputFactory = f;
}
"," public void setXMLInputFactory(XMLInputFactory f) {
_xmlInputFactory = f;
}
",FALSE,XmlFactory.java
" public XMLOutputFactory getXMLOutputFactory() {
return _xmlOutputFactory;
}
"," public XMLOutputFactory getXMLOutputFactory() {
return _xmlOutputFactory;
}
",FALSE,XmlFactory.java
" public void setXMLOutputFactory(XMLOutputFactory f) {
_xmlOutputFactory = f;
}
"," public void setXMLOutputFactory(XMLOutputFactory f) {
_xmlOutputFactory = f;
}
",FALSE,XmlFactory.java
" public String getFormatName() {
return FORMAT_NAME_XML;
}
"," public String getFormatName() {
return FORMAT_NAME_XML;
}
",FALSE,XmlFactory.java
" public MatchStrength hasFormat(InputAccessor acc) throws IOException {
return hasXMLFormat(acc);
}
"," public MatchStrength hasFormat(InputAccessor acc) throws IOException {
return hasXMLFormat(acc);
}
",FALSE,XmlFactory.java
" public boolean requiresCustomCodec() { return true; }
"," public boolean requiresCustomCodec() { return true; }
",FALSE,XmlFactory.java
" public boolean canUseCharArrays() { return false; }
"," public boolean canUseCharArrays() { return false; }
",FALSE,XmlFactory.java
" public Class getFormatReadFeatureType() {
return FromXmlParser.Feature.class;
}
"," public Class getFormatReadFeatureType() {
return FromXmlParser.Feature.class;
}
",FALSE,XmlFactory.java
" public Class getFormatWriteFeatureType() {
return ToXmlGenerator.Feature.class;
}
"," public Class getFormatWriteFeatureType() {
return ToXmlGenerator.Feature.class;
}
",FALSE,XmlFactory.java
" public JsonParser createParser(String content) throws IOException {
Reader r = new StringReader(content);
IOContext ctxt = _createContext(r, true);
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
"," public JsonParser createParser(String content) throws IOException {
Reader r = new StringReader(content);
IOContext ctxt = _createContext(r, true);
if (_inputDecorator != null) {
r = _inputDecorator.decorate(ctxt, r);
}
return _createParser(r, ctxt);
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(OutputStream out) throws IOException {
return createGenerator(out, JsonEncoding.UTF8);
}
"," public ToXmlGenerator createGenerator(OutputStream out) throws IOException {
return createGenerator(out, JsonEncoding.UTF8);
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ctxt = _createContext(out, false);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt,
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
"," public ToXmlGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException
{
// false -> we won't manage the stream unless explicitly directed to
IOContext ctxt = _createContext(out, false);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt,
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(Writer out) throws IOException
{
return new ToXmlGenerator(_createContext(out, false),
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
"," public ToXmlGenerator createGenerator(Writer out) throws IOException
{
return new ToXmlGenerator(_createContext(out, false),
_generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(File f, JsonEncoding enc) throws IOException
{
OutputStream out = new FileOutputStream(f);
// true -> yes, we have to manage the stream since we created it
IOContext ctxt = _createContext(out, true);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
"," public ToXmlGenerator createGenerator(File f, JsonEncoding enc) throws IOException
{
OutputStream out = new FileOutputStream(f);
// true -> yes, we have to manage the stream since we created it
IOContext ctxt = _createContext(out, true);
ctxt.setEncoding(enc);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, _createXmlWriter(out));
}
",FALSE,XmlFactory.java
" public FromXmlParser createParser(XMLStreamReader sr) throws IOException
{
// note: should NOT move parser if already pointing to START_ELEMENT
if (sr.getEventType() != XMLStreamConstants.START_ELEMENT) {
try {
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
// false -> not managed
FromXmlParser xp = new FromXmlParser(_createContext(sr, false),
_generatorFeatures, _xmlGeneratorFeatures, _objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," public FromXmlParser createParser(XMLStreamReader sr) throws IOException
{
// note: should NOT move parser if already pointing to START_ELEMENT
if (sr.getEventType() != XMLStreamConstants.START_ELEMENT) {
try {
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
// false -> not managed
FromXmlParser xp = new FromXmlParser(_createContext(sr, false),
_generatorFeatures, _xmlGeneratorFeatures, _objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" public ToXmlGenerator createGenerator(XMLStreamWriter sw) throws IOException
{
try {
sw = _initializeXmlWriter(sw);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
IOContext ctxt = _createContext(sw, false);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sw);
}
"," public ToXmlGenerator createGenerator(XMLStreamWriter sw) throws IOException
{
try {
sw = _initializeXmlWriter(sw);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
IOContext ctxt = _createContext(sw, false);
return new ToXmlGenerator(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sw);
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(InputStream in, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(in);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(InputStream in, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(in);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(Reader r, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(r);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(Reader r, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(r);
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(char[] data, int offset, int len, IOContext ctxt,
boolean recycleBuffer) throws IOException
{
// !!! TODO: add proper handling of 'recycleBuffer'; currently its handling
// is always same as if 'false' was passed
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2CharArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(char[] data, int offset, int len, IOContext ctxt,
boolean recycleBuffer) throws IOException
{
// !!! TODO: add proper handling of 'recycleBuffer'; currently its handling
// is always same as if 'false' was passed
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2CharArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected FromXmlParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2ByteArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
"," protected FromXmlParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException
{
XMLStreamReader sr;
try {
sr = _xmlInputFactory.createXMLStreamReader(new Stax2ByteArraySource(data, offset, len));
sr = _initializeXmlReader(sr);
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
FromXmlParser xp = new FromXmlParser(ctxt, _generatorFeatures, _xmlGeneratorFeatures,
_objectCodec, sr);
if (_cfgNameForTextElement != null) {
xp.setXMLTextElementName(_cfgNameForTextElement);
}
return xp;
}
",FALSE,XmlFactory.java
" protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
// this method should never get called here, so:
VersionUtil.throwInternal();
return null;
}
"," protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
// this method should never get called here, so:
VersionUtil.throwInternal();
return null;
}
",FALSE,XmlFactory.java
" protected XMLStreamWriter _createXmlWriter(OutputStream out) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(out, ""UTF-8""));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
"," protected XMLStreamWriter _createXmlWriter(OutputStream out) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(out, ""UTF-8""));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
",FALSE,XmlFactory.java
" protected XMLStreamWriter _createXmlWriter(Writer w) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(w));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
"," protected XMLStreamWriter _createXmlWriter(Writer w) throws IOException
{
try {
return _initializeXmlWriter(_xmlOutputFactory.createXMLStreamWriter(w));
} catch (XMLStreamException e) {
return StaxUtil.throwXmlAsIOException(e);
}
}
",FALSE,XmlFactory.java
" protected final XMLStreamWriter _initializeXmlWriter(XMLStreamWriter sw) throws IOException, XMLStreamException
{
// And just for Sun Stax parser (JDK default), seems that we better define default namespace
// (Woodstox doesn't care) -- otherwise it'll add unnecessary odd declaration
sw.setDefaultNamespace("""");
return sw;
}
"," protected final XMLStreamWriter _initializeXmlWriter(XMLStreamWriter sw) throws IOException, XMLStreamException
{
// And just for Sun Stax parser (JDK default), seems that we better define default namespace
// (Woodstox doesn't care) -- otherwise it'll add unnecessary odd declaration
sw.setDefaultNamespace("""");
return sw;
}
",FALSE,XmlFactory.java
" protected final XMLStreamReader _initializeXmlReader(XMLStreamReader sr) throws IOException, XMLStreamException
{
// for now, nothing to do... except let's find the root element
while (sr.next() != XMLStreamConstants.START_ELEMENT) {
;
}
return sr;
}
"," protected final XMLStreamReader _initializeXmlReader(XMLStreamReader sr) throws IOException, XMLStreamException
{
// for now, nothing to do... except let's find the root element
while (sr.next() != XMLStreamConstants.START_ELEMENT) {
;
}
return sr;
}
",FALSE,XmlFactory.java
" public static MatchStrength hasXMLFormat(InputAccessor acc) throws IOException
{
/* Basically we just need to find "" or , since
* can NOT come outside of root
*/
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
b = acc.nextByte();
if (b == BYTE_HYPHEN) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() == BYTE_HYPHEN) {
return MatchStrength.SOLID_MATCH;
}
} else if (b == BYTE_D) {
return tryMatch(acc, ""OCTYPE"", MatchStrength.SOLID_MATCH);
}
} else {
// maybe root element? Just needs to match first char.
if (validXmlNameStartChar(acc, b)) {
return MatchStrength.SOLID_MATCH;
}
}
return MatchStrength.NO_MATCH;
}
"," public static MatchStrength hasXMLFormat(InputAccessor acc) throws IOException
{
/* Basically we just need to find "" or , since
* can NOT come outside of root
*/
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
b = acc.nextByte();
if (b == BYTE_HYPHEN) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() == BYTE_HYPHEN) {
return MatchStrength.SOLID_MATCH;
}
} else if (b == BYTE_D) {
return tryMatch(acc, ""OCTYPE"", MatchStrength.SOLID_MATCH);
}
} else {
// maybe root element? Just needs to match first char.
if (validXmlNameStartChar(acc, b)) {
return MatchStrength.SOLID_MATCH;
}
}
return MatchStrength.NO_MATCH;
}
",FALSE,XmlFactory.java
" private final static boolean validXmlNameStartChar(InputAccessor acc, byte b)
throws IOException
{
/* Can make it actual real XML check in future; for now we do just crude
* check for ASCII range
*/
int ch = (int) b & 0xFF;
if (ch >= 'A') { // in theory, colon could be; in practice it should never be valid (wrt namespace)
// This is where we'd check for multi-byte UTF-8 chars (or whatever encoding is in use)...
return true;
}
return false;
}
"," private final static boolean validXmlNameStartChar(InputAccessor acc, byte b)
throws IOException
{
/* Can make it actual real XML check in future; for now we do just crude
* check for ASCII range
*/
int ch = (int) b & 0xFF;
if (ch >= 'A') { // in theory, colon could be; in practice it should never be valid (wrt namespace)
// This is where we'd check for multi-byte UTF-8 chars (or whatever encoding is in use)...
return true;
}
return false;
}
",FALSE,XmlFactory.java
" private final static MatchStrength tryMatch(InputAccessor acc, String matchStr, MatchStrength fullMatchStrength)
throws IOException
{
for (int i = 0, len = matchStr.length(); i < len; ++i) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() != matchStr.charAt(i)) {
return MatchStrength.NO_MATCH;
}
}
return fullMatchStrength;
}
"," private final static MatchStrength tryMatch(InputAccessor acc, String matchStr, MatchStrength fullMatchStrength)
throws IOException
{
for (int i = 0, len = matchStr.length(); i < len; ++i) {
if (!acc.hasMoreBytes()) {
return MatchStrength.INCONCLUSIVE;
}
if (acc.nextByte() != matchStr.charAt(i)) {
return MatchStrength.NO_MATCH;
}
}
return fullMatchStrength;
}
",FALSE,XmlFactory.java
" private final static int skipSpace(InputAccessor acc, byte b) throws IOException
{
while (true) {
int ch = (int) b & 0xFF;
if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
return ch;
}
if (!acc.hasMoreBytes()) {
return -1;
}
b = acc.nextByte();
ch = (int) b & 0xFF;
}
}
"," private final static int skipSpace(InputAccessor acc, byte b) throws IOException
{
while (true) {
int ch = (int) b & 0xFF;
if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
return ch;
}
if (!acc.hasMoreBytes()) {
return -1;
}
b = acc.nextByte();
ch = (int) b & 0xFF;
}
}
",FALSE,XmlFactory.java
" public boolean start() throws Exception {
String job = step.getJob();
Item item = Jenkins.getActiveInstance().getItem(job, invokingRun.getParent(), Item.class);
if (item == null) {
throw new AbortException(""No item named "" + job + "" found"");
}
if (step.getWait() && !(item instanceof Job)) {
// TODO find some way of allowing ComputedFolders to hook into the listener code
throw new AbortException(""Waiting for non-job items is not supported"");
}
if (item instanceof ParameterizedJobMixIn.ParameterizedJob) {
final ParameterizedJobMixIn.ParameterizedJob project = (ParameterizedJobMixIn.ParameterizedJob) item;
listener.getLogger().println(""Scheduling project: "" + ModelHyperlinkNote.encodeTo(project));
node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(project.getFullDisplayName())));
List actions = new ArrayList<>();
if (step.getWait()) {
StepContext context = getContext();
actions.add(new BuildTriggerAction(context, step.isPropagate()));
LOGGER.log(Level.FINER, ""scheduling a build of {0} from {1}"", new Object[]{project, context});
}
actions.add(new CauseAction(new Cause.UpstreamCause(invokingRun)));
List parameters = step.getParameters();
if (parameters != null) {
parameters = completeDefaultParameters(parameters, (Job) project);
actions.add(new ParametersAction(parameters));
}
Integer quietPeriod = step.getQuietPeriod();
// TODO use new convenience method in 1.621
if (quietPeriod == null) {
quietPeriod = project.getQuietPeriod();
}
QueueTaskFuture> f = new ParameterizedJobMixIn() {
@Override
protected Job asJob() {
return (Job) project;
}
}.scheduleBuild2(quietPeriod, actions.toArray(new Action[actions.size()]));
if (f == null) {
throw new AbortException(""Failed to trigger build of "" + project.getFullName());
}
} else if (item instanceof Queue.Task){
if (step.getParameters() != null && !step.getParameters().isEmpty()) {
throw new AbortException(""Item type does not support parameters"");
}
Queue.Task task = (Queue.Task) item;
listener.getLogger().println(""Scheduling item: "" + ModelHyperlinkNote.encodeTo(item));
node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(task.getFullDisplayName())));
List actions = new ArrayList<>();
if (step.getWait()) {
StepContext context = getContext();
actions.add(new BuildTriggerAction(context, step.isPropagate()));
LOGGER.log(Level.FINER, ""scheduling a build of {0} from {1}"", new Object[]{task, context});
}
actions.add(new CauseAction(new Cause.UpstreamCause(invokingRun)));
Integer quietPeriod = step.getQuietPeriod();
if (quietPeriod == null) {
try {
Method getQuietPeriod = task.getClass().getMethod(""getQuietPeriod"");
if (getQuietPeriod.getReturnType().equals(int.class)) {
quietPeriod = (Integer) getQuietPeriod.invoke(task);
}
} catch (NoSuchMethodException e) {
// ignore, best effort only
} catch (IllegalAccessError | IllegalArgumentException | InvocationTargetException e) {
LOGGER.log(Level.WARNING, ""Could not determine quiet period of "" + item.getFullName(), e);
}
}
if (quietPeriod == null) {
quietPeriod = Jenkins.getActiveInstance().getQuietPeriod();
}
ScheduleResult scheduleResult = Jenkins.getActiveInstance().getQueue().schedule2(task, quietPeriod,actions);
if (scheduleResult.isRefused()) {
throw new AbortException(""Failed to trigger build of "" + item.getFullName());
}
} else {
throw new AbortException(""The item named "" + job + "" is a ""
+ (item instanceof Describable
? ((Describable) item).getDescriptor().getDisplayName()
: item.getClass().getName())
+ "" which is not something that can be built"");
}
if (step.getWait()) {
return false;
} else {
getContext().onSuccess(null);
return true;
}
}
"," public boolean start() throws Exception {
String job = step.getJob();
Item item = Jenkins.getActiveInstance().getItem(job, invokingRun.getParent(), Item.class);
if (item == null) {
throw new AbortException(""No item named "" + job + "" found"");
}
item.checkPermission(Item.BUILD);
if (step.getWait() && !(item instanceof Job)) {
// TODO find some way of allowing ComputedFolders to hook into the listener code
throw new AbortException(""Waiting for non-job items is not supported"");
}
if (item instanceof ParameterizedJobMixIn.ParameterizedJob) {
final ParameterizedJobMixIn.ParameterizedJob project = (ParameterizedJobMixIn.ParameterizedJob) item;
listener.getLogger().println(""Scheduling project: "" + ModelHyperlinkNote.encodeTo(project));
node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(project.getFullDisplayName())));
List actions = new ArrayList<>();
if (step.getWait()) {
StepContext context = getContext();
actions.add(new BuildTriggerAction(context, step.isPropagate()));
LOGGER.log(Level.FINER, ""scheduling a build of {0} from {1}"", new Object[]{project, context});
}
actions.add(new CauseAction(new Cause.UpstreamCause(invokingRun)));
List parameters = step.getParameters();
if (parameters != null) {
parameters = completeDefaultParameters(parameters, (Job) project);
actions.add(new ParametersAction(parameters));
}
Integer quietPeriod = step.getQuietPeriod();
// TODO use new convenience method in 1.621
if (quietPeriod == null) {
quietPeriod = project.getQuietPeriod();
}
QueueTaskFuture> f = new ParameterizedJobMixIn() {
@Override
protected Job asJob() {
return (Job) project;
}
}.scheduleBuild2(quietPeriod, actions.toArray(new Action[actions.size()]));
if (f == null) {
throw new AbortException(""Failed to trigger build of "" + project.getFullName());
}
} else if (item instanceof Queue.Task){
if (step.getParameters() != null && !step.getParameters().isEmpty()) {
throw new AbortException(""Item type does not support parameters"");
}
Queue.Task task = (Queue.Task) item;
listener.getLogger().println(""Scheduling item: "" + ModelHyperlinkNote.encodeTo(item));
node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(task.getFullDisplayName())));
List actions = new ArrayList<>();
if (step.getWait()) {
StepContext context = getContext();
actions.add(new BuildTriggerAction(context, step.isPropagate()));
LOGGER.log(Level.FINER, ""scheduling a build of {0} from {1}"", new Object[]{task, context});
}
actions.add(new CauseAction(new Cause.UpstreamCause(invokingRun)));
Integer quietPeriod = step.getQuietPeriod();
if (quietPeriod == null) {
try {
Method getQuietPeriod = task.getClass().getMethod(""getQuietPeriod"");
if (getQuietPeriod.getReturnType().equals(int.class)) {
quietPeriod = (Integer) getQuietPeriod.invoke(task);
}
} catch (NoSuchMethodException e) {
// ignore, best effort only
} catch (IllegalAccessError | IllegalArgumentException | InvocationTargetException e) {
LOGGER.log(Level.WARNING, ""Could not determine quiet period of "" + item.getFullName(), e);
}
}
if (quietPeriod == null) {
quietPeriod = Jenkins.getActiveInstance().getQuietPeriod();
}
ScheduleResult scheduleResult = Jenkins.getActiveInstance().getQueue().schedule2(task, quietPeriod,actions);
if (scheduleResult.isRefused()) {
throw new AbortException(""Failed to trigger build of "" + item.getFullName());
}
} else {
throw new AbortException(""The item named "" + job + "" is a ""
+ (item instanceof Describable
? ((Describable) item).getDescriptor().getDisplayName()
: item.getClass().getName())
+ "" which is not something that can be built"");
}
if (step.getWait()) {
return false;
} else {
getContext().onSuccess(null);
return true;
}
}
",TRUE,BuildTriggerStepExecution.java
" private List completeDefaultParameters(List parameters, Job,?> project) {
List completeListOfParameters = Lists.newArrayList(parameters);
List names = Lists.transform(parameters, new Function() {
@Override public String apply(ParameterValue input) {
return input.getName();
}
});
if (project != null) {
ParametersDefinitionProperty pdp = project.getProperty(ParametersDefinitionProperty.class);
if (pdp != null) {
for (ParameterDefinition pDef : pdp.getParameterDefinitions()) {
if (!names.contains(pDef.getName())) {
ParameterValue defaultP = pDef.getDefaultParameterValue();
if (defaultP != null) {
completeListOfParameters.add(defaultP);
}
}
}
}
}
return completeListOfParameters;
}
"," private List completeDefaultParameters(List parameters, Job,?> project) {
List completeListOfParameters = Lists.newArrayList(parameters);
List names = Lists.transform(parameters, new Function() {
@Override public String apply(ParameterValue input) {
return input.getName();
}
});
if (project != null) {
ParametersDefinitionProperty pdp = project.getProperty(ParametersDefinitionProperty.class);
if (pdp != null) {
for (ParameterDefinition pDef : pdp.getParameterDefinitions()) {
if (!names.contains(pDef.getName())) {
ParameterValue defaultP = pDef.getDefaultParameterValue();
if (defaultP != null) {
completeListOfParameters.add(defaultP);
}
}
}
}
}
return completeListOfParameters;
}
",FALSE,BuildTriggerStepExecution.java
" public void stop(Throwable cause) {
StepContext context = getContext();
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
context.onFailure(cause);
return;
}
boolean interrupted = false;
Queue q = jenkins.getQueue();
// if the build is still in the queue, abort it.
// BuildQueueListener will report the failure, so this method shouldn't call getContext().onFailure()
for (Queue.Item i : q.getItems()) {
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor(i)) {
if (trigger.context.equals(context)) {
// Note that it is a little questionable to cancel the queue item in case it has other causes,
// but in the common case that this is the only cause, it is most intuitive to do so.
// The same applies to aborting the actual build once started.
q.cancel(i);
interrupted = true;
}
}
}
// if there's any in-progress build already, abort that.
// when the build is actually aborted, BuildTriggerListener will take notice and report the failure,
// so this method shouldn't call getContext().onFailure()
for (Computer c : jenkins.getComputers()) {
for (Executor e : c.getExecutors()) {
interrupted |= maybeInterrupt(e, cause, context);
}
for (Executor e : c.getOneOffExecutors()) {
interrupted |= maybeInterrupt(e, cause, context);
}
}
if (!interrupted) {
context.onFailure(cause);
}
}
"," public void stop(Throwable cause) {
StepContext context = getContext();
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
context.onFailure(cause);
return;
}
boolean interrupted = false;
Queue q = jenkins.getQueue();
// if the build is still in the queue, abort it.
// BuildQueueListener will report the failure, so this method shouldn't call getContext().onFailure()
for (Queue.Item i : q.getItems()) {
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor(i)) {
if (trigger.context.equals(context)) {
// Note that it is a little questionable to cancel the queue item in case it has other causes,
// but in the common case that this is the only cause, it is most intuitive to do so.
// The same applies to aborting the actual build once started.
q.cancel(i);
interrupted = true;
}
}
}
// if there's any in-progress build already, abort that.
// when the build is actually aborted, BuildTriggerListener will take notice and report the failure,
// so this method shouldn't call getContext().onFailure()
for (Computer c : jenkins.getComputers()) {
for (Executor e : c.getExecutors()) {
interrupted |= maybeInterrupt(e, cause, context);
}
for (Executor e : c.getOneOffExecutors()) {
interrupted |= maybeInterrupt(e, cause, context);
}
}
if (!interrupted) {
context.onFailure(cause);
}
}
",FALSE,BuildTriggerStepExecution.java
" private static boolean maybeInterrupt(Executor e, Throwable cause, StepContext context) {
boolean interrupted = false;
Queue.Executable exec = e.getCurrentExecutable();
if (exec instanceof Run) {
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor((Run) exec)) {
if (trigger.context.equals(context)) {
e.interrupt(Result.ABORTED, new BuildTriggerCancelledCause(cause));
trigger.interruption = cause;
try {
((Run) exec).save();
} catch (IOException x) {
LOGGER.log(Level.WARNING, ""failed to save interrupt cause on "" + exec, x);
}
interrupted = true;
}
}
}
return interrupted;
}
"," private static boolean maybeInterrupt(Executor e, Throwable cause, StepContext context) {
boolean interrupted = false;
Queue.Executable exec = e.getCurrentExecutable();
if (exec instanceof Run) {
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor((Run) exec)) {
if (trigger.context.equals(context)) {
e.interrupt(Result.ABORTED, new BuildTriggerCancelledCause(cause));
trigger.interruption = cause;
try {
((Run) exec).save();
} catch (IOException x) {
LOGGER.log(Level.WARNING, ""failed to save interrupt cause on "" + exec, x);
}
interrupted = true;
}
}
}
return interrupted;
}
",FALSE,BuildTriggerStepExecution.java
" @Override public String getStatus() {
for (Queue.Item i : Queue.getInstance().getItems()) {
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor(i)) {
if (trigger.context.equals(getContext())) {
return ""waiting to schedule "" + i.task.getFullDisplayName() + ""; blocked: "" + i.getWhy();
}
}
}
for (Computer c : Jenkins.getActiveInstance().getComputers()) {
for (Executor e : c.getExecutors()) {
String r = running(e);
if (r != null) {
return r;
}
}
for (Executor e : c.getOneOffExecutors()) {
String r = running(e);
if (r != null) {
return r;
}
}
}
// TODO QueueTaskFuture does not allow us to record the queue item ID
return ""unsure what happened to downstream build"";
}
"," @Override public String getStatus() {
for (Queue.Item i : Queue.getInstance().getItems()) {
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor(i)) {
if (trigger.context.equals(getContext())) {
return ""waiting to schedule "" + i.task.getFullDisplayName() + ""; blocked: "" + i.getWhy();
}
}
}
for (Computer c : Jenkins.getActiveInstance().getComputers()) {
for (Executor e : c.getExecutors()) {
String r = running(e);
if (r != null) {
return r;
}
}
for (Executor e : c.getOneOffExecutors()) {
String r = running(e);
if (r != null) {
return r;
}
}
}
// TODO QueueTaskFuture does not allow us to record the queue item ID
return ""unsure what happened to downstream build"";
}
",FALSE,BuildTriggerStepExecution.java
" private @CheckForNull String running(@Nonnull Executor e) {
Queue.Executable exec = e.getCurrentExecutable();
if (exec instanceof Run) {
Run,?> run = (Run) exec;
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor(run)) {
if (trigger.context.equals(getContext())) {
return ""running "" + run;
}
}
}
return null;
}
"," private @CheckForNull String running(@Nonnull Executor e) {
Queue.Executable exec = e.getCurrentExecutable();
if (exec instanceof Run) {
Run,?> run = (Run) exec;
for (BuildTriggerAction.Trigger trigger : BuildTriggerAction.triggersFor(run)) {
if (trigger.context.equals(getContext())) {
return ""running "" + run;
}
}
}
return null;
}
",FALSE,BuildTriggerStepExecution.java
" @Before public void runQuickly() throws IOException {
j.jenkins.setQuietPeriod(0);
}
"," @Before public void runQuickly() throws IOException {
j.jenkins.setQuietPeriod(0);
}
",FALSE,BuildTriggerStepTest.java
" @Test public void buildTopLevelProject() throws Exception {
FreeStyleProject ds = j.createFreeStyleProject(""ds"");
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(
""def ds = build 'ds'\n"" +
""echo \""ds.result=${ds.result} ds.number=${ds.number}\"""", true));
j.assertLogContains(""ds.result=SUCCESS ds.number=1"", j.buildAndAssertSuccess(us));
// TODO JENKINS-28673 assert no warnings, as in StartupTest.noWarnings
// (but first need to deal with `WARNING: Failed to instantiate optional component org.jenkinsci.plugins.workflow.steps.scm.SubversionStep$DescriptorImpl; skipping`)
ds.getBuildByNumber(1).delete();
}
"," @Test public void buildTopLevelProject() throws Exception {
FreeStyleProject ds = j.createFreeStyleProject(""ds"");
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(
""def ds = build 'ds'\n"" +
""echo \""ds.result=${ds.result} ds.number=${ds.number}\"""", true));
j.assertLogContains(""ds.result=SUCCESS ds.number=1"", j.buildAndAssertSuccess(us));
// TODO JENKINS-28673 assert no warnings, as in StartupTest.noWarnings
// (but first need to deal with `WARNING: Failed to instantiate optional component org.jenkinsci.plugins.workflow.steps.scm.SubversionStep$DescriptorImpl; skipping`)
ds.getBuildByNumber(1).delete();
}
",FALSE,BuildTriggerStepTest.java
" @Test public void failingBuild() throws Exception {
j.createFreeStyleProject(""ds"").getBuildersList().add(new FailureBuilder());
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'"", true));
j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0));
us.setDefinition(new CpsFlowDefinition(""echo \""ds.result=${build(job: 'ds', propagate: false).result}\"""", true));
j.assertLogContains(""ds.result=FAILURE"", j.buildAndAssertSuccess(us));
}
"," @Test public void failingBuild() throws Exception {
j.createFreeStyleProject(""ds"").getBuildersList().add(new FailureBuilder());
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'"", true));
j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0));
us.setDefinition(new CpsFlowDefinition(""echo \""ds.result=${build(job: 'ds', propagate: false).result}\"""", true));
j.assertLogContains(""ds.result=FAILURE"", j.buildAndAssertSuccess(us));
}
",FALSE,BuildTriggerStepTest.java
" public void buildFolderProject() throws Exception {
MockFolder dir1 = j.createFolder(""dir1"");
FreeStyleProject downstream = dir1.createProject(FreeStyleProject.class, ""downstream"");
downstream.getBuildersList().add(new SleepBuilder(1));
MockFolder dir2 = j.createFolder(""dir2"");
WorkflowJob upstream = dir2.createProject(WorkflowJob.class, ""upstream"");
upstream.setDefinition(new CpsFlowDefinition(""build '../dir1/downstream'""));
j.buildAndAssertSuccess(upstream);
assertEquals(1, downstream.getBuilds().size());
}
"," public void buildFolderProject() throws Exception {
MockFolder dir1 = j.createFolder(""dir1"");
FreeStyleProject downstream = dir1.createProject(FreeStyleProject.class, ""downstream"");
downstream.getBuildersList().add(new SleepBuilder(1));
MockFolder dir2 = j.createFolder(""dir2"");
WorkflowJob upstream = dir2.createProject(WorkflowJob.class, ""upstream"");
upstream.setDefinition(new CpsFlowDefinition(""build '../dir1/downstream'""));
j.buildAndAssertSuccess(upstream);
assertEquals(1, downstream.getBuilds().size());
}
",FALSE,BuildTriggerStepTest.java
" public void buildParallelTests() throws Exception {
FreeStyleProject p1 = j.createFreeStyleProject(""test1"");
p1.getBuildersList().add(new SleepBuilder(1));
FreeStyleProject p2 = j.createFreeStyleProject(""test2"");
p2.getBuildersList().add(new SleepBuilder(1));
WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, ""foo"");
foo.setDefinition(new CpsFlowDefinition(StringUtils.join(Arrays.asList(""parallel(test1: {\n"" +
"" build('test1');\n"" +
"" }, test2: {\n"" +
"" build('test2');\n"" +
"" })""), ""\n""), true));
j.buildAndAssertSuccess(foo);
}
"," public void buildParallelTests() throws Exception {
FreeStyleProject p1 = j.createFreeStyleProject(""test1"");
p1.getBuildersList().add(new SleepBuilder(1));
FreeStyleProject p2 = j.createFreeStyleProject(""test2"");
p2.getBuildersList().add(new SleepBuilder(1));
WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, ""foo"");
foo.setDefinition(new CpsFlowDefinition(StringUtils.join(Arrays.asList(""parallel(test1: {\n"" +
"" build('test1');\n"" +
"" }, test2: {\n"" +
"" build('test2');\n"" +
"" })""), ""\n""), true));
j.buildAndAssertSuccess(foo);
}
",FALSE,BuildTriggerStepTest.java
" public void abortBuild() throws Exception {
FreeStyleProject p = j.createFreeStyleProject(""test1"");
p.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, ""foo"");
foo.setDefinition(new CpsFlowDefinition(StringUtils.join(Arrays.asList(""build('test1');""), ""\n"")));
QueueTaskFuture q = foo.scheduleBuild2(0);
WorkflowRun b = q.getStartCondition().get();
CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();
e.waitForSuspension();
FreeStyleBuild fb=null;
while (fb==null) {
fb = p.getBuildByNumber(1);
Thread.sleep(10);
}
fb.getExecutor().interrupt();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(fb));
j.assertBuildStatus(Result.FAILURE,q.get());
}
"," public void abortBuild() throws Exception {
FreeStyleProject p = j.createFreeStyleProject(""test1"");
p.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, ""foo"");
foo.setDefinition(new CpsFlowDefinition(StringUtils.join(Arrays.asList(""build('test1');""), ""\n"")));
QueueTaskFuture q = foo.scheduleBuild2(0);
WorkflowRun b = q.getStartCondition().get();
CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();
e.waitForSuspension();
FreeStyleBuild fb=null;
while (fb==null) {
fb = p.getBuildByNumber(1);
Thread.sleep(10);
}
fb.getExecutor().interrupt();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(fb));
j.assertBuildStatus(Result.FAILURE,q.get());
}
",FALSE,BuildTriggerStepTest.java
" public void cancelBuildQueue() throws Exception {
FreeStyleProject p = j.createFreeStyleProject(""test1"");
p.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, ""foo"");
foo.setDefinition(new CpsFlowDefinition(StringUtils.join(Arrays.asList(""build('test1');""), ""\n"")));
j.jenkins.setNumExecutors(0); //should force freestyle build to remain in the queue?
QueueTaskFuture q = foo.scheduleBuild2(0);
WorkflowRun b = q.getStartCondition().get();
CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();
e.waitForSuspension();
Queue.Item[] items = j.jenkins.getQueue().getItems();
assertEquals(1, items.length);
j.jenkins.getQueue().cancel(items[0]);
j.assertBuildStatus(Result.FAILURE,q.get());
}
"," public void cancelBuildQueue() throws Exception {
FreeStyleProject p = j.createFreeStyleProject(""test1"");
p.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, ""foo"");
foo.setDefinition(new CpsFlowDefinition(StringUtils.join(Arrays.asList(""build('test1');""), ""\n"")));
j.jenkins.setNumExecutors(0); //should force freestyle build to remain in the queue?
QueueTaskFuture q = foo.scheduleBuild2(0);
WorkflowRun b = q.getStartCondition().get();
CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();
e.waitForSuspension();
Queue.Item[] items = j.jenkins.getQueue().getItems();
assertEquals(1, items.length);
j.jenkins.getQueue().cancel(items[0]);
j.assertBuildStatus(Result.FAILURE,q.get());
}
",FALSE,BuildTriggerStepTest.java
" @Test public void interruptFlow() throws Exception {
FreeStyleProject ds1 = j.createFreeStyleProject(""ds1"");
ds1.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
FreeStyleProject ds2 = j.createFreeStyleProject(""ds2"");
ds2.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
FreeStyleProject ds3 = j.createFreeStyleProject(""ds3"");
ds3.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""parallel ds1: {build 'ds1'}, ds23: {parallel ds2: {build 'ds2'}, ds3: {build 'ds3'}}"", true));
j.jenkins.setNumExecutors(3);
j.jenkins.setNodes(j.jenkins.getNodes()); // TODO https://github.com/jenkinsci/jenkins/pull/1596 renders this workaround unnecessary
WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
assertEquals(1, usb.getNumber());
FreeStyleBuild ds1b, ds2b, ds3b;
while ((ds1b = ds1.getLastBuild()) == null || (ds2b = ds2.getLastBuild()) == null || (ds3b = ds3.getLastBuild()) == null) {
Thread.sleep(100);
}
assertEquals(1, ds1b.getNumber());
assertEquals(1, ds2b.getNumber());
assertEquals(1, ds3b.getNumber());
// Same as X button in UI.
// Should be the same as, e.g., GerritTrigger.RunningJobs.cancelJob, which calls Executor.interrupt directly.
// (Not if the Executor.currentExecutable is an AfterRestartTask.Body, though in that case probably the FreeStyleBuild would have been killed by restart anyway!)
usb.doStop();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds1b));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds2b));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds3b));
}
"," @Test public void interruptFlow() throws Exception {
FreeStyleProject ds1 = j.createFreeStyleProject(""ds1"");
ds1.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
FreeStyleProject ds2 = j.createFreeStyleProject(""ds2"");
ds2.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
FreeStyleProject ds3 = j.createFreeStyleProject(""ds3"");
ds3.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""parallel ds1: {build 'ds1'}, ds23: {parallel ds2: {build 'ds2'}, ds3: {build 'ds3'}}"", true));
j.jenkins.setNumExecutors(3);
j.jenkins.setNodes(j.jenkins.getNodes()); // TODO https://github.com/jenkinsci/jenkins/pull/1596 renders this workaround unnecessary
WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
assertEquals(1, usb.getNumber());
FreeStyleBuild ds1b, ds2b, ds3b;
while ((ds1b = ds1.getLastBuild()) == null || (ds2b = ds2.getLastBuild()) == null || (ds3b = ds3.getLastBuild()) == null) {
Thread.sleep(100);
}
assertEquals(1, ds1b.getNumber());
assertEquals(1, ds2b.getNumber());
assertEquals(1, ds3b.getNumber());
// Same as X button in UI.
// Should be the same as, e.g., GerritTrigger.RunningJobs.cancelJob, which calls Executor.interrupt directly.
// (Not if the Executor.currentExecutable is an AfterRestartTask.Body, though in that case probably the FreeStyleBuild would have been killed by restart anyway!)
usb.doStop();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds1b));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds2b));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds3b));
}
",FALSE,BuildTriggerStepTest.java
" @Test public void interruptFlowDownstreamFlow() throws Exception {
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""semaphore 'ds'"", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'"", true));
WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
assertEquals(1, usb.getNumber());
SemaphoreStep.waitForStart(""ds/1"", null);
WorkflowRun dsb = ds.getLastBuild();
assertEquals(1, dsb.getNumber());
usb.doStop();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(dsb));
}
"," @Test public void interruptFlowDownstreamFlow() throws Exception {
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""semaphore 'ds'"", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'"", true));
WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
assertEquals(1, usb.getNumber());
SemaphoreStep.waitForStart(""ds/1"", null);
WorkflowRun dsb = ds.getLastBuild();
assertEquals(1, dsb.getNumber());
usb.doStop();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(dsb));
}
",FALSE,BuildTriggerStepTest.java
" @Test public void interruptFlowNonPropagate() throws Exception {
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""semaphore 'ds'"", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""while (true) {build job: 'ds', propagate: false}"", true));
WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
assertEquals(1, usb.getNumber());
SemaphoreStep.waitForStart(""ds/1"", null);
WorkflowRun dsb = ds.getLastBuild();
assertEquals(1, dsb.getNumber());
usb.doStop();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(dsb));
}
"," @Test public void interruptFlowNonPropagate() throws Exception {
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""semaphore 'ds'"", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""while (true) {build job: 'ds', propagate: false}"", true));
WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
assertEquals(1, usb.getNumber());
SemaphoreStep.waitForStart(""ds/1"", null);
WorkflowRun dsb = ds.getLastBuild();
assertEquals(1, dsb.getNumber());
usb.doStop();
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(dsb));
}
",FALSE,BuildTriggerStepTest.java
" @Test public void triggerWorkflow() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'""));
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""echo 'OK'""));
j.buildAndAssertSuccess(us);
assertEquals(1, ds.getBuilds().size());
}
"," @Test public void triggerWorkflow() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'""));
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""echo 'OK'""));
j.buildAndAssertSuccess(us);
assertEquals(1, ds.getBuilds().size());
}
",FALSE,BuildTriggerStepTest.java
" @Test public void parameters() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
FreeStyleProject ds = j.jenkins.createProject(FreeStyleProject.class, ""ds"");
ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""branch"", ""master""), new BooleanParameterDefinition(""extra"", false, null)));
CaptureEnvironmentBuilder env = new CaptureEnvironmentBuilder();
ds.getBuildersList().add(env);
us.setDefinition(new CpsFlowDefinition(""build 'ds'""));
WorkflowRun us1 = j.buildAndAssertSuccess(us);
assertEquals(""1"", env.getEnvVars().get(""BUILD_NUMBER""));
assertEquals(""master"", env.getEnvVars().get(""branch""));
assertEquals(""false"", env.getEnvVars().get(""extra""));
Cause.UpstreamCause cause = ds.getBuildByNumber(1).getCause(Cause.UpstreamCause.class);
assertNotNull(cause);
assertEquals(us1, cause.getUpstreamRun());
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'branch', value: 'release']]"", true));
j.buildAndAssertSuccess(us);
assertEquals(""2"", env.getEnvVars().get(""BUILD_NUMBER""));
assertEquals(""release"", env.getEnvVars().get(""branch""));
assertEquals(""false"", env.getEnvVars().get(""extra"")); //
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'branch', value: 'release'], [$class: 'BooleanParameterValue', name: 'extra', value: true]]"", true));
j.buildAndAssertSuccess(us);
assertEquals(""3"", env.getEnvVars().get(""BUILD_NUMBER""));
assertEquals(""release"", env.getEnvVars().get(""branch""));
assertEquals(""true"", env.getEnvVars().get(""extra""));
}
"," @Test public void parameters() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
FreeStyleProject ds = j.jenkins.createProject(FreeStyleProject.class, ""ds"");
ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""branch"", ""master""), new BooleanParameterDefinition(""extra"", false, null)));
CaptureEnvironmentBuilder env = new CaptureEnvironmentBuilder();
ds.getBuildersList().add(env);
us.setDefinition(new CpsFlowDefinition(""build 'ds'""));
WorkflowRun us1 = j.buildAndAssertSuccess(us);
assertEquals(""1"", env.getEnvVars().get(""BUILD_NUMBER""));
assertEquals(""master"", env.getEnvVars().get(""branch""));
assertEquals(""false"", env.getEnvVars().get(""extra""));
Cause.UpstreamCause cause = ds.getBuildByNumber(1).getCause(Cause.UpstreamCause.class);
assertNotNull(cause);
assertEquals(us1, cause.getUpstreamRun());
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'branch', value: 'release']]"", true));
j.buildAndAssertSuccess(us);
assertEquals(""2"", env.getEnvVars().get(""BUILD_NUMBER""));
assertEquals(""release"", env.getEnvVars().get(""branch""));
assertEquals(""false"", env.getEnvVars().get(""extra"")); //
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'branch', value: 'release'], [$class: 'BooleanParameterValue', name: 'extra', value: true]]"", true));
j.buildAndAssertSuccess(us);
assertEquals(""3"", env.getEnvVars().get(""BUILD_NUMBER""));
assertEquals(""release"", env.getEnvVars().get(""branch""));
assertEquals(""true"", env.getEnvVars().get(""extra""));
}
",FALSE,BuildTriggerStepTest.java
" @Test public void noWait() throws Exception {
j.createFreeStyleProject(""ds"").setAssignedLabel(Label.get(""nonexistent""));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', wait: false""));
j.buildAndAssertSuccess(us);
}
"," @Test public void noWait() throws Exception {
j.createFreeStyleProject(""ds"").setAssignedLabel(Label.get(""nonexistent""));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', wait: false""));
j.buildAndAssertSuccess(us);
}
",FALSE,BuildTriggerStepTest.java
" @Test public void rejectedStart() throws Exception {
j.createFreeStyleProject(""ds"");
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
// wait: true also fails as expected w/o fix, just more slowly (test timeout):
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', wait: false""));
j.assertLogContains(""Failed to trigger build of ds"", j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0)));
}
"," @Test public void rejectedStart() throws Exception {
j.createFreeStyleProject(""ds"");
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
// wait: true also fails as expected w/o fix, just more slowly (test timeout):
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', wait: false""));
j.assertLogContains(""Failed to trigger build of ds"", j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0)));
}
",FALSE,BuildTriggerStepTest.java
" @Override public boolean shouldSchedule(Queue.Task p, List actions) {
return p instanceof WorkflowJob; // i.e., refuse FreestyleProject
}
"," @Override public boolean shouldSchedule(Queue.Task p, List actions) {
return p instanceof WorkflowJob; // i.e., refuse FreestyleProject
}
",FALSE,BuildTriggerStepTest.java
" @Test public void buildVariables() throws Exception {
j.createFreeStyleProject(""ds"").addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""param"", ""default"")));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""echo \""build var: ${build(job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'param', value: 'override']]).buildVariables.param}\"""", true));
j.assertLogContains(""build var: override"", j.buildAndAssertSuccess(us));
}
"," @Test public void buildVariables() throws Exception {
j.createFreeStyleProject(""ds"").addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""param"", ""default"")));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""echo \""build var: ${build(job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'param', value: 'override']]).buildVariables.param}\"""", true));
j.assertLogContains(""build var: override"", j.buildAndAssertSuccess(us));
}
",FALSE,BuildTriggerStepTest.java
" @Test public void buildVariablesWorkflow() throws Exception {
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""env.RESULT = \""ds-${env.BUILD_NUMBER}\"""", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""def vars = build('ds').buildVariables; echo \""received RESULT=${vars.RESULT} vs. BUILD_NUMBER=${vars.BUILD_NUMBER}\"""", true));
j.assertLogContains(""received RESULT=ds-1 vs. BUILD_NUMBER=null"", j.buildAndAssertSuccess(us));
ds.getBuildByNumber(1).delete();
}
"," @Test public void buildVariablesWorkflow() throws Exception {
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""env.RESULT = \""ds-${env.BUILD_NUMBER}\"""", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""def vars = build('ds').buildVariables; echo \""received RESULT=${vars.RESULT} vs. BUILD_NUMBER=${vars.BUILD_NUMBER}\"""", true));
j.assertLogContains(""received RESULT=ds-1 vs. BUILD_NUMBER=null"", j.buildAndAssertSuccess(us));
ds.getBuildByNumber(1).delete();
}
",FALSE,BuildTriggerStepTest.java
" @Test public void coalescedQueue() throws Exception {
FreeStyleProject ds = j.createFreeStyleProject(""ds"");
ds.setConcurrentBuild(true);
ds.getBuildersList().add(new SleepBuilder(3000));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""echo \""triggered #${build('ds').number}\"""", true));
QueueTaskFuture us1F = us.scheduleBuild2(0);
us1F.waitForStart(); // make sure we do not coalesce the us `Queue.Item`s
QueueTaskFuture us2F = us.scheduleBuild2(0);
WorkflowRun us1 = us1F.get();
assertEquals(1, us1.getNumber());
j.assertLogContains(""triggered #1"", us1);
WorkflowRun us2 = us2F.get();
assertEquals(2, us2.getNumber());
j.assertLogContains(""triggered #1"", us2);
FreeStyleBuild ds1 = ds.getLastBuild();
assertEquals(1, ds1.getNumber());
assertEquals(2, ds1.getCauses().size()); // 2× UpstreamCause
}
"," @Test public void coalescedQueue() throws Exception {
FreeStyleProject ds = j.createFreeStyleProject(""ds"");
ds.setConcurrentBuild(true);
ds.getBuildersList().add(new SleepBuilder(3000));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""echo \""triggered #${build('ds').number}\"""", true));
QueueTaskFuture us1F = us.scheduleBuild2(0);
us1F.waitForStart(); // make sure we do not coalesce the us `Queue.Item`s
QueueTaskFuture us2F = us.scheduleBuild2(0);
WorkflowRun us1 = us1F.get();
assertEquals(1, us1.getNumber());
j.assertLogContains(""triggered #1"", us1);
WorkflowRun us2 = us2F.get();
assertEquals(2, us2.getNumber());
j.assertLogContains(""triggered #1"", us2);
FreeStyleBuild ds1 = ds.getLastBuild();
assertEquals(1, ds1.getNumber());
assertEquals(2, ds1.getCauses().size()); // 2× UpstreamCause
}
",FALSE,BuildTriggerStepTest.java
" @Test public void nonCoalescedQueueParallel() throws Exception {
j.jenkins.setNumExecutors(5);
FreeStyleProject ds = j.createFreeStyleProject(""ds"");
ds.setConcurrentBuild(true);
ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""which"", null)));
ds.getBuildersList().add(new SleepBuilder(3000));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(
""def branches = [:]\n"" +
""for (int i = 0; i < 5; i++) {\n"" +
"" def which = \""${i}\""\n"" +
"" branches[\""branch${i}\""] = {\n"" +
"" build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'which', value: which]]\n"" +
"" }\n"" +
""}\n"" +
""parallel branches"", true));
j.buildAndAssertSuccess(us);
FreeStyleBuild ds1 = ds.getLastBuild();
assertEquals(5, ds1.getNumber());
}
"," @Test public void nonCoalescedQueueParallel() throws Exception {
j.jenkins.setNumExecutors(5);
FreeStyleProject ds = j.createFreeStyleProject(""ds"");
ds.setConcurrentBuild(true);
ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""which"", null)));
ds.getBuildersList().add(new SleepBuilder(3000));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(
""def branches = [:]\n"" +
""for (int i = 0; i < 5; i++) {\n"" +
"" def which = \""${i}\""\n"" +
"" branches[\""branch${i}\""] = {\n"" +
"" build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'which', value: which]]\n"" +
"" }\n"" +
""}\n"" +
""parallel branches"", true));
j.buildAndAssertSuccess(us);
FreeStyleBuild ds1 = ds.getLastBuild();
assertEquals(5, ds1.getNumber());
}
",FALSE,BuildTriggerStepTest.java
" @Test public void raceCondition() throws Exception {
logging.record(BuildTriggerStepExecution.class.getPackage().getName(), Level.FINE).record(Queue.class, Level.FINE).record(Executor.class, Level.FINE);
j.jenkins.setQuietPeriod(0);
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""sleep 1"", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""def rebuild() {for (int i = 0; i < 20; i++) {build 'ds'}}; parallel A: {rebuild()}, B: {rebuild()}, C: {rebuild()}"", true));
j.buildAndAssertSuccess(us);
}
"," @Test public void raceCondition() throws Exception {
logging.record(BuildTriggerStepExecution.class.getPackage().getName(), Level.FINE).record(Queue.class, Level.FINE).record(Executor.class, Level.FINE);
j.jenkins.setQuietPeriod(0);
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition(""sleep 1"", true));
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""def rebuild() {for (int i = 0; i < 20; i++) {build 'ds'}}; parallel A: {rebuild()}, B: {rebuild()}, C: {rebuild()}"", true));
j.buildAndAssertSuccess(us);
}
",FALSE,BuildTriggerStepTest.java
" @Test public void defaultParameters() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'PARAM1', value: 'first']] ""));
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""PARAM1"", ""p1""), new StringParameterDefinition(""PARAM2"", ""p2"")));
// TODO use params when updating workflow-cps/workflow-job
ds.setDefinition(new CpsFlowDefinition(""echo \""${PARAM1} - ${PARAM2}\""""));
j.buildAndAssertSuccess(us);
j.assertLogContains(""first - p2"", ds.getLastBuild());
}
"," @Test public void defaultParameters() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'PARAM1', value: 'first']] ""));
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(""PARAM1"", ""p1""), new StringParameterDefinition(""PARAM2"", ""p2"")));
// TODO use params when updating workflow-cps/workflow-job
ds.setDefinition(new CpsFlowDefinition(""echo \""${PARAM1} - ${PARAM2}\""""));
j.buildAndAssertSuccess(us);
j.assertLogContains(""first - p2"", ds.getLastBuild());
}
",FALSE,BuildTriggerStepTest.java
" @Test public void storedForm() throws Exception {
WorkflowJob us = j.jenkins.getItemByFullName(""us"", WorkflowJob.class);
WorkflowRun us1 = us.getBuildByNumber(1);
WorkflowJob ds = j.jenkins.getItemByFullName(""ds"", WorkflowJob.class);
WorkflowRun ds1 = ds.getBuildByNumber(1);
ds1.setDescription(""something"");
j.assertBuildStatusSuccess(j.waitForCompletion(ds1));
j.assertBuildStatusSuccess(j.waitForCompletion(us1));
}
"," @Test public void storedForm() throws Exception {
WorkflowJob us = j.jenkins.getItemByFullName(""us"", WorkflowJob.class);
WorkflowRun us1 = us.getBuildByNumber(1);
WorkflowJob ds = j.jenkins.getItemByFullName(""ds"", WorkflowJob.class);
WorkflowRun ds1 = ds.getBuildByNumber(1);
ds1.setDescription(""something"");
j.assertBuildStatusSuccess(j.waitForCompletion(ds1));
j.assertBuildStatusSuccess(j.waitForCompletion(us1));
}
",FALSE,BuildTriggerStepTest.java
" public void triggerOrgFolder() throws Exception {
try (MockSCMController c = MockSCMController.create()) {
c.createRepository(""foo"");
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build job:'ds', wait:false""));
OrganizationFolder ds = j.jenkins.createProject(OrganizationFolder.class, ""ds"");
ds.getSCMNavigators().add(new MockSCMNavigator(c, true, false, false));
ds.getProjectFactories().add(new DummyMultiBranchProjectFactory());
j.waitUntilNoActivity();
assertThat(ds.getComputation().getResult(), nullValue());
j.buildAndAssertSuccess(us);
j.waitUntilNoActivity();
assertThat(ds.getComputation().getResult(), notNullValue());
}
}
"," public void triggerOrgFolder() throws Exception {
try (MockSCMController c = MockSCMController.create()) {
c.createRepository(""foo"");
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build job:'ds', wait:false""));
OrganizationFolder ds = j.jenkins.createProject(OrganizationFolder.class, ""ds"");
ds.getSCMNavigators().add(new MockSCMNavigator(c, true, false, false));
ds.getProjectFactories().add(new DummyMultiBranchProjectFactory());
j.waitUntilNoActivity();
assertThat(ds.getComputation().getResult(), nullValue());
j.buildAndAssertSuccess(us);
j.waitUntilNoActivity();
assertThat(ds.getComputation().getResult(), notNullValue());
}
}
",FALSE,BuildTriggerStepTest.java
" public boolean recognizes(@NonNull ItemGroup> parent, @NonNull String name,
@NonNull List extends SCMSource> scmSources,
@NonNull Map attributes,
@CheckForNull SCMHeadEvent> event, @NonNull TaskListener listener)
throws IOException, InterruptedException {
return false;
}
"," public boolean recognizes(@NonNull ItemGroup> parent, @NonNull String name,
@NonNull List extends SCMSource> scmSources,
@NonNull Map attributes,
@CheckForNull SCMHeadEvent> event, @NonNull TaskListener listener)
throws IOException, InterruptedException {
return false;
}
",FALSE,BuildTriggerStepTest.java
" public MultiBranchProjectFactory newInstance() {
return new DummyMultiBranchProjectFactory();
}
"," public MultiBranchProjectFactory newInstance() {
return new DummyMultiBranchProjectFactory();
}
",FALSE,BuildTriggerStepTest.java
" }
"," @Test public void permissions() throws Exception {
WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, ""us"");
us.setDefinition(new CpsFlowDefinition(""build 'ds'"", true));
WorkflowJob ds = j.jenkins.createProject(WorkflowJob.class, ""ds"");
ds.setDefinition(new CpsFlowDefinition("""", true));
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap(""us"", User.get(""dev"").impersonate())));
// Control case: dev can do anything to ds.
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere().to(""dev""));
j.buildAndAssertSuccess(us);
// Main test case: dev can see ds but not build it.
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.READ, Computer.BUILD).everywhere().to(""dev"").grant(Item.READ).onItems(ds).to(""dev""));
j.assertLogContains(""dev is missing the Job/Build permission"", j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0)));
// Aux test case: dev cannot see ds.
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.READ, Computer.BUILD).everywhere().to(""dev""));
j.assertLogContains(""No item named ds found"", j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0)));
// Aux test case: dev can learn of the existence of ds but no more.
j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.READ, Computer.BUILD).everywhere().to(""dev"").grant(Item.DISCOVER).onItems(ds).to(""dev""));
j.assertLogContains(""Please login to access job ds"", j.assertBuildStatus(Result.FAILURE, us.scheduleBuild2(0)));
}
",TRUE,BuildTriggerStepTest.java
" public ZipArchiveInputStream(final InputStream inputStream) {
this(inputStream, ZipEncodingHelper.UTF8);
}
"," public ZipArchiveInputStream(final InputStream inputStream) {
this(inputStream, ZipEncodingHelper.UTF8);
}
",FALSE,ZipArchiveInputStream.java
" public ZipArchiveInputStream(final InputStream inputStream, final String encoding) {
this(inputStream, encoding, true);
}
"," public ZipArchiveInputStream(final InputStream inputStream, final String encoding) {
this(inputStream, encoding, true);
}
",FALSE,ZipArchiveInputStream.java
" public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields) {
this(inputStream, encoding, useUnicodeExtraFields, false);
}
"," public ZipArchiveInputStream(final InputStream inputStream, final String encoding, final boolean useUnicodeExtraFields) {
this(inputStream, encoding, useUnicodeExtraFields, false);
}
",FALSE,ZipArchiveInputStream.java
" public ZipArchiveInputStream(final InputStream inputStream,
final String encoding,
final boolean useUnicodeExtraFields,
final boolean allowStoredEntriesWithDataDescriptor) {
this.encoding = encoding;
zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
this.useUnicodeExtraFields = useUnicodeExtraFields;
in = new PushbackInputStream(inputStream, buf.capacity());
this.allowStoredEntriesWithDataDescriptor =
allowStoredEntriesWithDataDescriptor;
// haven't read anything so far
buf.limit(0);
}
"," public ZipArchiveInputStream(final InputStream inputStream,
final String encoding,
final boolean useUnicodeExtraFields,
final boolean allowStoredEntriesWithDataDescriptor) {
this.encoding = encoding;
zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);
this.useUnicodeExtraFields = useUnicodeExtraFields;
in = new PushbackInputStream(inputStream, buf.capacity());
this.allowStoredEntriesWithDataDescriptor =
allowStoredEntriesWithDataDescriptor;
// haven't read anything so far
buf.limit(0);
}
",FALSE,ZipArchiveInputStream.java
" public ZipArchiveEntry getNextZipEntry() throws IOException {
uncompressedCount = 0;
boolean firstEntry = true;
if (closed || hitCentralDirectory) {
return null;
}
if (current != null) {
closeEntry();
firstEntry = false;
}
long currentHeaderOffset = getBytesRead();
try {
if (firstEntry) {
// split archives have a special signature before the
// first local file header - look for it and fail with
// the appropriate error message if this is a split
// archive.
readFirstLocalFileHeader(lfhBuf);
} else {
readFully(lfhBuf);
}
} catch (final EOFException e) {
return null;
}
final ZipLong sig = new ZipLong(lfhBuf);
if (!sig.equals(ZipLong.LFH_SIG)) {
if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG) || isApkSigningBlock(lfhBuf)) {
hitCentralDirectory = true;
skipRemainderOfArchive();
return null;
}
throw new ZipException(String.format(""Unexpected record signature: 0X%X"", sig.getValue()));
}
int off = WORD;
current = new CurrentEntry();
final int versionMadeBy = ZipShort.getValue(lfhBuf, off);
off += SHORT;
current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);
final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(lfhBuf, off);
final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();
final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;
current.hasDataDescriptor = gpFlag.usesDataDescriptor();
current.entry.setGeneralPurposeBit(gpFlag);
off += SHORT;
current.entry.setMethod(ZipShort.getValue(lfhBuf, off));
off += SHORT;
final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(lfhBuf, off));
current.entry.setTime(time);
off += WORD;
ZipLong size = null, cSize = null;
if (!current.hasDataDescriptor) {
current.entry.setCrc(ZipLong.getValue(lfhBuf, off));
off += WORD;
cSize = new ZipLong(lfhBuf, off);
off += WORD;
size = new ZipLong(lfhBuf, off);
off += WORD;
} else {
off += 3 * WORD;
}
final int fileNameLen = ZipShort.getValue(lfhBuf, off);
off += SHORT;
final int extraLen = ZipShort.getValue(lfhBuf, off);
off += SHORT; // NOSONAR - assignment as documentation
final byte[] fileName = new byte[fileNameLen];
readFully(fileName);
current.entry.setName(entryEncoding.decode(fileName), fileName);
if (hasUTF8Flag) {
current.entry.setNameSource(ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);
}
final byte[] extraData = new byte[extraLen];
readFully(extraData);
current.entry.setExtra(extraData);
if (!hasUTF8Flag && useUnicodeExtraFields) {
ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);
}
processZip64Extra(size, cSize);
current.entry.setLocalHeaderOffset(currentHeaderOffset);
current.entry.setDataOffset(getBytesRead());
current.entry.setStreamContiguous(true);
ZipMethod m = ZipMethod.getMethodByCode(current.entry.getMethod());
if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {
if (ZipUtil.canHandleEntryData(current.entry) && m != ZipMethod.STORED && m != ZipMethod.DEFLATED) {
InputStream bis = new BoundedInputStream(in, current.entry.getCompressedSize());
switch (m) {
case UNSHRINKING:
current.in = new UnshrinkingInputStream(bis);
break;
case IMPLODING:
current.in = new ExplodingInputStream(
current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),
current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),
bis);
break;
case BZIP2:
current.in = new BZip2CompressorInputStream(bis);
break;
case ENHANCED_DEFLATED:
current.in = new Deflate64CompressorInputStream(bis);
break;
default:
// we should never get here as all supported methods have been covered
// will cause an error when read is invoked, don't throw an exception here so people can
// skip unsupported entries
break;
}
}
} else if (m == ZipMethod.ENHANCED_DEFLATED) {
current.in = new Deflate64CompressorInputStream(in);
}
entriesRead++;
return current.entry;
}
"," public ZipArchiveEntry getNextZipEntry() throws IOException {
uncompressedCount = 0;
boolean firstEntry = true;
if (closed || hitCentralDirectory) {
return null;
}
if (current != null) {
closeEntry();
firstEntry = false;
}
long currentHeaderOffset = getBytesRead();
try {
if (firstEntry) {
// split archives have a special signature before the
// first local file header - look for it and fail with
// the appropriate error message if this is a split
// archive.
readFirstLocalFileHeader(lfhBuf);
} else {
readFully(lfhBuf);
}
} catch (final EOFException e) {
return null;
}
final ZipLong sig = new ZipLong(lfhBuf);
if (!sig.equals(ZipLong.LFH_SIG)) {
if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG) || isApkSigningBlock(lfhBuf)) {
hitCentralDirectory = true;
skipRemainderOfArchive();
return null;
}
throw new ZipException(String.format(""Unexpected record signature: 0X%X"", sig.getValue()));
}
int off = WORD;
current = new CurrentEntry();
final int versionMadeBy = ZipShort.getValue(lfhBuf, off);
off += SHORT;
current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);
final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(lfhBuf, off);
final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();
final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;
current.hasDataDescriptor = gpFlag.usesDataDescriptor();
current.entry.setGeneralPurposeBit(gpFlag);
off += SHORT;
current.entry.setMethod(ZipShort.getValue(lfhBuf, off));
off += SHORT;
final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(lfhBuf, off));
current.entry.setTime(time);
off += WORD;
ZipLong size = null, cSize = null;
if (!current.hasDataDescriptor) {
current.entry.setCrc(ZipLong.getValue(lfhBuf, off));
off += WORD;
cSize = new ZipLong(lfhBuf, off);
off += WORD;
size = new ZipLong(lfhBuf, off);
off += WORD;
} else {
off += 3 * WORD;
}
final int fileNameLen = ZipShort.getValue(lfhBuf, off);
off += SHORT;
final int extraLen = ZipShort.getValue(lfhBuf, off);
off += SHORT; // NOSONAR - assignment as documentation
final byte[] fileName = new byte[fileNameLen];
readFully(fileName);
current.entry.setName(entryEncoding.decode(fileName), fileName);
if (hasUTF8Flag) {
current.entry.setNameSource(ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);
}
final byte[] extraData = new byte[extraLen];
readFully(extraData);
current.entry.setExtra(extraData);
if (!hasUTF8Flag && useUnicodeExtraFields) {
ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);
}
processZip64Extra(size, cSize);
current.entry.setLocalHeaderOffset(currentHeaderOffset);
current.entry.setDataOffset(getBytesRead());
current.entry.setStreamContiguous(true);
ZipMethod m = ZipMethod.getMethodByCode(current.entry.getMethod());
if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {
if (ZipUtil.canHandleEntryData(current.entry) && m != ZipMethod.STORED && m != ZipMethod.DEFLATED) {
InputStream bis = new BoundedInputStream(in, current.entry.getCompressedSize());
switch (m) {
case UNSHRINKING:
current.in = new UnshrinkingInputStream(bis);
break;
case IMPLODING:
current.in = new ExplodingInputStream(
current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),
current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),
bis);
break;
case BZIP2:
current.in = new BZip2CompressorInputStream(bis);
break;
case ENHANCED_DEFLATED:
current.in = new Deflate64CompressorInputStream(bis);
break;
default:
// we should never get here as all supported methods have been covered
// will cause an error when read is invoked, don't throw an exception here so people can
// skip unsupported entries
break;
}
}
} else if (m == ZipMethod.ENHANCED_DEFLATED) {
current.in = new Deflate64CompressorInputStream(in);
}
entriesRead++;
return current.entry;
}
",FALSE,ZipArchiveInputStream.java
" private void readFirstLocalFileHeader(final byte[] lfh) throws IOException {
readFully(lfh);
final ZipLong sig = new ZipLong(lfh);
if (sig.equals(ZipLong.DD_SIG)) {
throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.SPLITTING);
}
if (sig.equals(ZipLong.SINGLE_SEGMENT_SPLIT_MARKER)) {
// The archive is not really split as only one segment was
// needed in the end. Just skip over the marker.
final byte[] missedLfhBytes = new byte[4];
readFully(missedLfhBytes);
System.arraycopy(lfh, 4, lfh, 0, LFH_LEN - 4);
System.arraycopy(missedLfhBytes, 0, lfh, LFH_LEN - 4, 4);
}
}
"," private void readFirstLocalFileHeader(final byte[] lfh) throws IOException {
readFully(lfh);
final ZipLong sig = new ZipLong(lfh);
if (sig.equals(ZipLong.DD_SIG)) {
throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.SPLITTING);
}
if (sig.equals(ZipLong.SINGLE_SEGMENT_SPLIT_MARKER)) {
// The archive is not really split as only one segment was
// needed in the end. Just skip over the marker.
final byte[] missedLfhBytes = new byte[4];
readFully(missedLfhBytes);
System.arraycopy(lfh, 4, lfh, 0, LFH_LEN - 4);
System.arraycopy(missedLfhBytes, 0, lfh, LFH_LEN - 4, 4);
}
}
",FALSE,ZipArchiveInputStream.java
" private void processZip64Extra(final ZipLong size, final ZipLong cSize) {
final Zip64ExtendedInformationExtraField z64 =
(Zip64ExtendedInformationExtraField)
current.entry.getExtraField(Zip64ExtendedInformationExtraField.HEADER_ID);
current.usesZip64 = z64 != null;
if (!current.hasDataDescriptor) {
if (z64 != null // same as current.usesZip64 but avoids NPE warning
&& (cSize.equals(ZipLong.ZIP64_MAGIC) || size.equals(ZipLong.ZIP64_MAGIC)) ) {
current.entry.setCompressedSize(z64.getCompressedSize().getLongValue());
current.entry.setSize(z64.getSize().getLongValue());
} else {
current.entry.setCompressedSize(cSize.getValue());
current.entry.setSize(size.getValue());
}
}
}
"," private void processZip64Extra(final ZipLong size, final ZipLong cSize) {
final Zip64ExtendedInformationExtraField z64 =
(Zip64ExtendedInformationExtraField)
current.entry.getExtraField(Zip64ExtendedInformationExtraField.HEADER_ID);
current.usesZip64 = z64 != null;
if (!current.hasDataDescriptor) {
if (z64 != null // same as current.usesZip64 but avoids NPE warning
&& (cSize.equals(ZipLong.ZIP64_MAGIC) || size.equals(ZipLong.ZIP64_MAGIC)) ) {
current.entry.setCompressedSize(z64.getCompressedSize().getLongValue());
current.entry.setSize(z64.getSize().getLongValue());
} else {
current.entry.setCompressedSize(cSize.getValue());
current.entry.setSize(size.getValue());
}
}
}
",FALSE,ZipArchiveInputStream.java
" public ArchiveEntry getNextEntry() throws IOException {
return getNextZipEntry();
}
"," public ArchiveEntry getNextEntry() throws IOException {
return getNextZipEntry();
}
",FALSE,ZipArchiveInputStream.java
" public boolean canReadEntryData(final ArchiveEntry ae) {
if (ae instanceof ZipArchiveEntry) {
final ZipArchiveEntry ze = (ZipArchiveEntry) ae;
return ZipUtil.canHandleEntryData(ze)
&& supportsDataDescriptorFor(ze)
&& supportsCompressedSizeFor(ze);
}
return false;
}
"," public boolean canReadEntryData(final ArchiveEntry ae) {
if (ae instanceof ZipArchiveEntry) {
final ZipArchiveEntry ze = (ZipArchiveEntry) ae;
return ZipUtil.canHandleEntryData(ze)
&& supportsDataDescriptorFor(ze)
&& supportsCompressedSizeFor(ze);
}
return false;
}
",FALSE,ZipArchiveInputStream.java
" public int read(final byte[] buffer, final int offset, final int length) throws IOException {
if (closed) {
throw new IOException(""The stream is closed"");
}
if (current == null) {
return -1;
}
// avoid int overflow, check null buffer
if (offset > buffer.length || length < 0 || offset < 0 || buffer.length - offset < length) {
throw new ArrayIndexOutOfBoundsException();
}
ZipUtil.checkRequestedFeatures(current.entry);
if (!supportsDataDescriptorFor(current.entry)) {
throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.DATA_DESCRIPTOR,
current.entry);
}
if (!supportsCompressedSizeFor(current.entry)) {
throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.UNKNOWN_COMPRESSED_SIZE,
current.entry);
}
int read;
if (current.entry.getMethod() == ZipArchiveOutputStream.STORED) {
read = readStored(buffer, offset, length);
} else if (current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED) {
read = readDeflated(buffer, offset, length);
} else if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()
|| current.entry.getMethod() == ZipMethod.IMPLODING.getCode()
|| current.entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()
|| current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {
read = current.in.read(buffer, offset, length);
} else {
throw new UnsupportedZipFeatureException(ZipMethod.getMethodByCode(current.entry.getMethod()),
current.entry);
}
if (read >= 0) {
current.crc.update(buffer, offset, read);
uncompressedCount += read;
}
return read;
}
"," public int read(final byte[] buffer, final int offset, final int length) throws IOException {
if (closed) {
throw new IOException(""The stream is closed"");
}
if (current == null) {
return -1;
}
// avoid int overflow, check null buffer
if (offset > buffer.length || length < 0 || offset < 0 || buffer.length - offset < length) {
throw new ArrayIndexOutOfBoundsException();
}
ZipUtil.checkRequestedFeatures(current.entry);
if (!supportsDataDescriptorFor(current.entry)) {
throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.DATA_DESCRIPTOR,
current.entry);
}
if (!supportsCompressedSizeFor(current.entry)) {
throw new UnsupportedZipFeatureException(UnsupportedZipFeatureException.Feature.UNKNOWN_COMPRESSED_SIZE,
current.entry);
}
int read;
if (current.entry.getMethod() == ZipArchiveOutputStream.STORED) {
read = readStored(buffer, offset, length);
} else if (current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED) {
read = readDeflated(buffer, offset, length);
} else if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()
|| current.entry.getMethod() == ZipMethod.IMPLODING.getCode()
|| current.entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()
|| current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {
read = current.in.read(buffer, offset, length);
} else {
throw new UnsupportedZipFeatureException(ZipMethod.getMethodByCode(current.entry.getMethod()),
current.entry);
}
if (read >= 0) {
current.crc.update(buffer, offset, read);
uncompressedCount += read;
}
return read;
}
",FALSE,ZipArchiveInputStream.java
" public long getCompressedCount() {
if (current.entry.getMethod() == ZipArchiveOutputStream.STORED) {
return current.bytesRead;
} else if (current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED) {
return getBytesInflated();
} else if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) {
return ((UnshrinkingInputStream) current.in).getCompressedCount();
} else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) {
return ((ExplodingInputStream) current.in).getCompressedCount();
} else if (current.entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()) {
return ((Deflate64CompressorInputStream) current.in).getCompressedCount();
} else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {
return ((BZip2CompressorInputStream) current.in).getCompressedCount();
} else {
return -1;
}
}
"," public long getCompressedCount() {
if (current.entry.getMethod() == ZipArchiveOutputStream.STORED) {
return current.bytesRead;
} else if (current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED) {
return getBytesInflated();
} else if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) {
return ((UnshrinkingInputStream) current.in).getCompressedCount();
} else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) {
return ((ExplodingInputStream) current.in).getCompressedCount();
} else if (current.entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()) {
return ((Deflate64CompressorInputStream) current.in).getCompressedCount();
} else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {
return ((BZip2CompressorInputStream) current.in).getCompressedCount();
} else {
return -1;
}
}
",FALSE,ZipArchiveInputStream.java
" public long getUncompressedCount() {
return uncompressedCount;
}
"," public long getUncompressedCount() {
return uncompressedCount;
}
",FALSE,ZipArchiveInputStream.java
" private int readStored(final byte[] buffer, final int offset, final int length) throws IOException {
if (current.hasDataDescriptor) {
if (lastStoredEntry == null) {
readStoredEntry();
}
return lastStoredEntry.read(buffer, offset, length);
}
final long csize = current.entry.getSize();
if (current.bytesRead >= csize) {
return -1;
}
if (buf.position() >= buf.limit()) {
buf.position(0);
final int l = in.read(buf.array());
if (l == -1) {
return -1;
}
buf.limit(l);
count(l);
current.bytesReadFromStream += l;
}
int toRead = Math.min(buf.remaining(), length);
if ((csize - current.bytesRead) < toRead) {
// if it is smaller than toRead then it fits into an int
toRead = (int) (csize - current.bytesRead);
}
buf.get(buffer, offset, toRead);
current.bytesRead += toRead;
return toRead;
}
"," private int readStored(final byte[] buffer, final int offset, final int length) throws IOException {
if (current.hasDataDescriptor) {
if (lastStoredEntry == null) {
readStoredEntry();
}
return lastStoredEntry.read(buffer, offset, length);
}
final long csize = current.entry.getSize();
if (current.bytesRead >= csize) {
return -1;
}
if (buf.position() >= buf.limit()) {
buf.position(0);
final int l = in.read(buf.array());
if (l == -1) {
buf.limit(0);
throw new IOException(""Truncated ZIP file"");
}
buf.limit(l);
count(l);
current.bytesReadFromStream += l;
}
int toRead = Math.min(buf.remaining(), length);
if ((csize - current.bytesRead) < toRead) {
// if it is smaller than toRead then it fits into an int
toRead = (int) (csize - current.bytesRead);
}
buf.get(buffer, offset, toRead);
current.bytesRead += toRead;
return toRead;
}
",TRUE,ZipArchiveInputStream.java
" private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException {
final int read = readFromInflater(buffer, offset, length);
if (read <= 0) {
if (inf.finished()) {
return -1;
} else if (inf.needsDictionary()) {
throw new ZipException(""This archive needs a preset dictionary""
+ "" which is not supported by Commons""
+ "" Compress."");
} else if (read == -1) {
throw new IOException(""Truncated ZIP file"");
}
}
return read;
}
"," private int readDeflated(final byte[] buffer, final int offset, final int length) throws IOException {
final int read = readFromInflater(buffer, offset, length);
if (read <= 0) {
if (inf.finished()) {
return -1;
} else if (inf.needsDictionary()) {
throw new ZipException(""This archive needs a preset dictionary""
+ "" which is not supported by Commons""
+ "" Compress."");
} else if (read == -1) {
throw new IOException(""Truncated ZIP file"");
}
}
return read;
}
",FALSE,ZipArchiveInputStream.java
" private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException {
int read = 0;
do {
if (inf.needsInput()) {
final int l = fill();
if (l > 0) {
current.bytesReadFromStream += buf.limit();
} else if (l == -1) {
return -1;
} else {
break;
}
}
try {
read = inf.inflate(buffer, offset, length);
} catch (final DataFormatException e) {
throw (IOException) new ZipException(e.getMessage()).initCause(e);
}
} while (read == 0 && inf.needsInput());
return read;
}
"," private int readFromInflater(final byte[] buffer, final int offset, final int length) throws IOException {
int read = 0;
do {
if (inf.needsInput()) {
final int l = fill();
if (l > 0) {
current.bytesReadFromStream += buf.limit();
} else if (l == -1) {
return -1;
} else {
break;
}
}
try {
read = inf.inflate(buffer, offset, length);
} catch (final DataFormatException e) {
throw (IOException) new ZipException(e.getMessage()).initCause(e);
}
} while (read == 0 && inf.needsInput());
return read;
}
",FALSE,ZipArchiveInputStream.java
" public void close() throws IOException {
if (!closed) {
closed = true;
try {
in.close();
} finally {
inf.end();
}
}
}
"," public void close() throws IOException {
if (!closed) {
closed = true;
try {
in.close();
} finally {
inf.end();
}
}
}
",FALSE,ZipArchiveInputStream.java
" public long skip(final long value) throws IOException {
if (value >= 0) {
long skipped = 0;
while (skipped < value) {
final long rem = value - skipped;
final int x = read(skipBuf, 0, (int) (skipBuf.length > rem ? rem : skipBuf.length));
if (x == -1) {
return skipped;
}
skipped += x;
}
return skipped;
}
throw new IllegalArgumentException();
}
"," public long skip(final long value) throws IOException {
if (value >= 0) {
long skipped = 0;
while (skipped < value) {
final long rem = value - skipped;
final int x = read(skipBuf, 0, (int) (skipBuf.length > rem ? rem : skipBuf.length));
if (x == -1) {
return skipped;
}
skipped += x;
}
return skipped;
}
throw new IllegalArgumentException();
}
",FALSE,ZipArchiveInputStream.java
" public static boolean matches(final byte[] signature, final int length) {
if (length < ZipArchiveOutputStream.LFH_SIG.length) {
return false;
}
return checksig(signature, ZipArchiveOutputStream.LFH_SIG) // normal file
|| checksig(signature, ZipArchiveOutputStream.EOCD_SIG) // empty zip
|| checksig(signature, ZipArchiveOutputStream.DD_SIG) // split zip
|| checksig(signature, ZipLong.SINGLE_SEGMENT_SPLIT_MARKER.getBytes());
}
"," public static boolean matches(final byte[] signature, final int length) {
if (length < ZipArchiveOutputStream.LFH_SIG.length) {
return false;
}
return checksig(signature, ZipArchiveOutputStream.LFH_SIG) // normal file
|| checksig(signature, ZipArchiveOutputStream.EOCD_SIG) // empty zip
|| checksig(signature, ZipArchiveOutputStream.DD_SIG) // split zip
|| checksig(signature, ZipLong.SINGLE_SEGMENT_SPLIT_MARKER.getBytes());
}
",FALSE,ZipArchiveInputStream.java
" private static boolean checksig(final byte[] signature, final byte[] expected) {
for (int i = 0; i < expected.length; i++) {
if (signature[i] != expected[i]) {
return false;
}
}
return true;
}
"," private static boolean checksig(final byte[] signature, final byte[] expected) {
for (int i = 0; i < expected.length; i++) {
if (signature[i] != expected[i]) {
return false;
}
}
return true;
}
",FALSE,ZipArchiveInputStream.java
" private void closeEntry() throws IOException {
if (closed) {
throw new IOException(""The stream is closed"");
}
if (current == null) {
return;
}
// Ensure all entry bytes are read
if (currentEntryHasOutstandingBytes()) {
drainCurrentEntryData();
} else {
// this is guaranteed to exhaust the stream
skip(Long.MAX_VALUE); //NOSONAR
final long inB = current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED
? getBytesInflated() : current.bytesRead;
// this is at most a single read() operation and can't
// exceed the range of int
final int diff = (int) (current.bytesReadFromStream - inB);
// Pushback any required bytes
if (diff > 0) {
pushback(buf.array(), buf.limit() - diff, diff);
current.bytesReadFromStream -= diff;
}
// Drain remainder of entry if not all data bytes were required
if (currentEntryHasOutstandingBytes()) {
drainCurrentEntryData();
}
}
if (lastStoredEntry == null && current.hasDataDescriptor) {
readDataDescriptor();
}
inf.reset();
buf.clear().flip();
current = null;
lastStoredEntry = null;
}
"," private void closeEntry() throws IOException {
if (closed) {
throw new IOException(""The stream is closed"");
}
if (current == null) {
return;
}
// Ensure all entry bytes are read
if (currentEntryHasOutstandingBytes()) {
drainCurrentEntryData();
} else {
// this is guaranteed to exhaust the stream
skip(Long.MAX_VALUE); //NOSONAR
final long inB = current.entry.getMethod() == ZipArchiveOutputStream.DEFLATED
? getBytesInflated() : current.bytesRead;
// this is at most a single read() operation and can't
// exceed the range of int
final int diff = (int) (current.bytesReadFromStream - inB);
// Pushback any required bytes
if (diff > 0) {
pushback(buf.array(), buf.limit() - diff, diff);
current.bytesReadFromStream -= diff;
}
// Drain remainder of entry if not all data bytes were required
if (currentEntryHasOutstandingBytes()) {
drainCurrentEntryData();
}
}
if (lastStoredEntry == null && current.hasDataDescriptor) {
readDataDescriptor();
}
inf.reset();
buf.clear().flip();
current = null;
lastStoredEntry = null;
}
",FALSE,ZipArchiveInputStream.java
" private boolean currentEntryHasOutstandingBytes() {
return current.bytesReadFromStream <= current.entry.getCompressedSize()
&& !current.hasDataDescriptor;
}
"," private boolean currentEntryHasOutstandingBytes() {
return current.bytesReadFromStream <= current.entry.getCompressedSize()
&& !current.hasDataDescriptor;
}
",FALSE,ZipArchiveInputStream.java
" private void drainCurrentEntryData() throws IOException {
long remaining = current.entry.getCompressedSize() - current.bytesReadFromStream;
while (remaining > 0) {
final long n = in.read(buf.array(), 0, (int) Math.min(buf.capacity(), remaining));
if (n < 0) {
throw new EOFException(""Truncated ZIP entry: ""
+ ArchiveUtils.sanitize(current.entry.getName()));
}
count(n);
remaining -= n;
}
}
"," private void drainCurrentEntryData() throws IOException {
long remaining = current.entry.getCompressedSize() - current.bytesReadFromStream;
while (remaining > 0) {
final long n = in.read(buf.array(), 0, (int) Math.min(buf.capacity(), remaining));
if (n < 0) {
throw new EOFException(""Truncated ZIP entry: ""
+ ArchiveUtils.sanitize(current.entry.getName()));
}
count(n);
remaining -= n;
}
}
",FALSE,ZipArchiveInputStream.java
" private long getBytesInflated() {
long inB = inf.getBytesRead();
if (current.bytesReadFromStream >= TWO_EXP_32) {
while (inB + TWO_EXP_32 <= current.bytesReadFromStream) {
inB += TWO_EXP_32;
}
}
return inB;
}
"," private long getBytesInflated() {
long inB = inf.getBytesRead();
if (current.bytesReadFromStream >= TWO_EXP_32) {
while (inB + TWO_EXP_32 <= current.bytesReadFromStream) {
inB += TWO_EXP_32;
}
}
return inB;
}
",FALSE,ZipArchiveInputStream.java
" private int fill() throws IOException {
if (closed) {
throw new IOException(""The stream is closed"");
}
final int length = in.read(buf.array());
if (length > 0) {
buf.limit(length);
count(buf.limit());
inf.setInput(buf.array(), 0, buf.limit());
}
return length;
}
"," private int fill() throws IOException {
if (closed) {
throw new IOException(""The stream is closed"");
}
final int length = in.read(buf.array());
if (length > 0) {
buf.limit(length);
count(buf.limit());
inf.setInput(buf.array(), 0, buf.limit());
}
return length;
}
",FALSE,ZipArchiveInputStream.java
" private void readFully(final byte[] b) throws IOException {
readFully(b, 0);
}
"," private void readFully(final byte[] b) throws IOException {
readFully(b, 0);
}
",FALSE,ZipArchiveInputStream.java
" private void readFully(final byte[] b, final int off) throws IOException {
final int len = b.length - off;
final int count = IOUtils.readFully(in, b, off, len);
count(count);
if (count < len) {
throw new EOFException();
}
}
"," private void readFully(final byte[] b, final int off) throws IOException {
final int len = b.length - off;
final int count = IOUtils.readFully(in, b, off, len);
count(count);
if (count < len) {
throw new EOFException();
}
}
",FALSE,ZipArchiveInputStream.java
" private void readDataDescriptor() throws IOException {
readFully(wordBuf);
ZipLong val = new ZipLong(wordBuf);
if (ZipLong.DD_SIG.equals(val)) {
// data descriptor with signature, skip sig
readFully(wordBuf);
val = new ZipLong(wordBuf);
}
current.entry.setCrc(val.getValue());
// if there is a ZIP64 extra field, sizes are eight bytes
// each, otherwise four bytes each. Unfortunately some
// implementations - namely Java7 - use eight bytes without
// using a ZIP64 extra field -
// https://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7073588
// just read 16 bytes and check whether bytes nine to twelve
// look like one of the signatures of what could follow a data
// descriptor (ignoring archive decryption headers for now).
// If so, push back eight bytes and assume sizes are four
// bytes, otherwise sizes are eight bytes each.
readFully(twoDwordBuf);
final ZipLong potentialSig = new ZipLong(twoDwordBuf, DWORD);
if (potentialSig.equals(ZipLong.CFH_SIG) || potentialSig.equals(ZipLong.LFH_SIG)) {
pushback(twoDwordBuf, DWORD, DWORD);
current.entry.setCompressedSize(ZipLong.getValue(twoDwordBuf));
current.entry.setSize(ZipLong.getValue(twoDwordBuf, WORD));
} else {
current.entry.setCompressedSize(ZipEightByteInteger.getLongValue(twoDwordBuf));
current.entry.setSize(ZipEightByteInteger.getLongValue(twoDwordBuf, DWORD));
}
}
"," private void readDataDescriptor() throws IOException {
readFully(wordBuf);
ZipLong val = new ZipLong(wordBuf);
if (ZipLong.DD_SIG.equals(val)) {
// data descriptor with signature, skip sig
readFully(wordBuf);
val = new ZipLong(wordBuf);
}
current.entry.setCrc(val.getValue());
// if there is a ZIP64 extra field, sizes are eight bytes
// each, otherwise four bytes each. Unfortunately some
// implementations - namely Java7 - use eight bytes without
// using a ZIP64 extra field -
// https://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7073588
// just read 16 bytes and check whether bytes nine to twelve
// look like one of the signatures of what could follow a data
// descriptor (ignoring archive decryption headers for now).
// If so, push back eight bytes and assume sizes are four
// bytes, otherwise sizes are eight bytes each.
readFully(twoDwordBuf);
final ZipLong potentialSig = new ZipLong(twoDwordBuf, DWORD);
if (potentialSig.equals(ZipLong.CFH_SIG) || potentialSig.equals(ZipLong.LFH_SIG)) {
pushback(twoDwordBuf, DWORD, DWORD);
current.entry.setCompressedSize(ZipLong.getValue(twoDwordBuf));
current.entry.setSize(ZipLong.getValue(twoDwordBuf, WORD));
} else {
current.entry.setCompressedSize(ZipEightByteInteger.getLongValue(twoDwordBuf));
current.entry.setSize(ZipEightByteInteger.getLongValue(twoDwordBuf, DWORD));
}
}
",FALSE,ZipArchiveInputStream.java
" private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry) {
return !entry.getGeneralPurposeBit().usesDataDescriptor()
|| (allowStoredEntriesWithDataDescriptor && entry.getMethod() == ZipEntry.STORED)
|| entry.getMethod() == ZipEntry.DEFLATED
|| entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode();
}
"," private boolean supportsDataDescriptorFor(final ZipArchiveEntry entry) {
return !entry.getGeneralPurposeBit().usesDataDescriptor()
|| (allowStoredEntriesWithDataDescriptor && entry.getMethod() == ZipEntry.STORED)
|| entry.getMethod() == ZipEntry.DEFLATED
|| entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode();
}
",FALSE,ZipArchiveInputStream.java
" private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry) {
return entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN
|| entry.getMethod() == ZipEntry.DEFLATED
|| entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()
|| (entry.getGeneralPurposeBit().usesDataDescriptor()
&& allowStoredEntriesWithDataDescriptor
&& entry.getMethod() == ZipEntry.STORED);
}
"," private boolean supportsCompressedSizeFor(final ZipArchiveEntry entry) {
return entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN
|| entry.getMethod() == ZipEntry.DEFLATED
|| entry.getMethod() == ZipMethod.ENHANCED_DEFLATED.getCode()
|| (entry.getGeneralPurposeBit().usesDataDescriptor()
&& allowStoredEntriesWithDataDescriptor
&& entry.getMethod() == ZipEntry.STORED);
}
",FALSE,ZipArchiveInputStream.java
" private void readStoredEntry() throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
int off = 0;
boolean done = false;
// length of DD without signature
final int ddLen = current.usesZip64 ? WORD + 2 * DWORD : 3 * WORD;
while (!done) {
final int r = in.read(buf.array(), off, ZipArchiveOutputStream.BUFFER_SIZE - off);
if (r <= 0) {
// read the whole archive without ever finding a
// central directory
throw new IOException(""Truncated ZIP file"");
}
if (r + off < 4) {
// buffer too small to check for a signature, loop
off += r;
continue;
}
done = bufferContainsSignature(bos, off, r, ddLen);
if (!done) {
off = cacheBytesRead(bos, off, r, ddLen);
}
}
final byte[] b = bos.toByteArray();
lastStoredEntry = new ByteArrayInputStream(b);
}
"," private void readStoredEntry() throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
int off = 0;
boolean done = false;
// length of DD without signature
final int ddLen = current.usesZip64 ? WORD + 2 * DWORD : 3 * WORD;
while (!done) {
final int r = in.read(buf.array(), off, ZipArchiveOutputStream.BUFFER_SIZE - off);
if (r <= 0) {
// read the whole archive without ever finding a
// central directory
throw new IOException(""Truncated ZIP file"");
}
if (r + off < 4) {
// buffer too small to check for a signature, loop
off += r;
continue;
}
done = bufferContainsSignature(bos, off, r, ddLen);
if (!done) {
off = cacheBytesRead(bos, off, r, ddLen);
}
}
final byte[] b = bos.toByteArray();
lastStoredEntry = new ByteArrayInputStream(b);
}
",FALSE,ZipArchiveInputStream.java
" private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen)
throws IOException {
boolean done = false;
int readTooMuch = 0;
for (int i = 0; !done && i < offset + lastRead - 4; i++) {
if (buf.array()[i] == LFH[0] && buf.array()[i + 1] == LFH[1]) {
if ((buf.array()[i + 2] == LFH[2] && buf.array()[i + 3] == LFH[3])
|| (buf.array()[i] == CFH[2] && buf.array()[i + 3] == CFH[3])) {
// found a LFH or CFH:
readTooMuch = offset + lastRead - i - expectedDDLen;
done = true;
}
else if (buf.array()[i + 2] == DD[2] && buf.array()[i + 3] == DD[3]) {
// found DD:
readTooMuch = offset + lastRead - i;
done = true;
}
if (done) {
// * push back bytes read in excess as well as the data
// descriptor
// * copy the remaining bytes to cache
// * read data descriptor
pushback(buf.array(), offset + lastRead - readTooMuch, readTooMuch);
bos.write(buf.array(), 0, i);
readDataDescriptor();
}
}
}
return done;
}
"," private boolean bufferContainsSignature(final ByteArrayOutputStream bos, final int offset, final int lastRead, final int expectedDDLen)
throws IOException {
boolean done = false;
int readTooMuch = 0;
for (int i = 0; !done && i < offset + lastRead - 4; i++) {
if (buf.array()[i] == LFH[0] && buf.array()[i + 1] == LFH[1]) {
if ((buf.array()[i + 2] == LFH[2] && buf.array()[i + 3] == LFH[3])
|| (buf.array()[i] == CFH[2] && buf.array()[i + 3] == CFH[3])) {
// found a LFH or CFH:
readTooMuch = offset + lastRead - i - expectedDDLen;
done = true;
}
else if (buf.array()[i + 2] == DD[2] && buf.array()[i + 3] == DD[3]) {
// found DD:
readTooMuch = offset + lastRead - i;
done = true;
}
if (done) {
// * push back bytes read in excess as well as the data
// descriptor
// * copy the remaining bytes to cache
// * read data descriptor
pushback(buf.array(), offset + lastRead - readTooMuch, readTooMuch);
bos.write(buf.array(), 0, i);
readDataDescriptor();
}
}
}
return done;
}
",FALSE,ZipArchiveInputStream.java
" private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen) {
final int cacheable = offset + lastRead - expecteDDLen - 3;
if (cacheable > 0) {
bos.write(buf.array(), 0, cacheable);
System.arraycopy(buf.array(), cacheable, buf.array(), 0, expecteDDLen + 3);
offset = expecteDDLen + 3;
} else {
offset += lastRead;
}
return offset;
}
"," private int cacheBytesRead(final ByteArrayOutputStream bos, int offset, final int lastRead, final int expecteDDLen) {
final int cacheable = offset + lastRead - expecteDDLen - 3;
if (cacheable > 0) {
bos.write(buf.array(), 0, cacheable);
System.arraycopy(buf.array(), cacheable, buf.array(), 0, expecteDDLen + 3);
offset = expecteDDLen + 3;
} else {
offset += lastRead;
}
return offset;
}
",FALSE,ZipArchiveInputStream.java
" private void pushback(final byte[] buf, final int offset, final int length) throws IOException {
((PushbackInputStream) in).unread(buf, offset, length);
pushedBackBytes(length);
}
"," private void pushback(final byte[] buf, final int offset, final int length) throws IOException {
((PushbackInputStream) in).unread(buf, offset, length);
pushedBackBytes(length);
}
",FALSE,ZipArchiveInputStream.java
" private void skipRemainderOfArchive() throws IOException {
// skip over central directory. One LFH has been read too much
// already. The calculation discounts file names and extra
// data so it will be too short.
realSkip((long) entriesRead * CFH_LEN - LFH_LEN);
findEocdRecord();
realSkip((long) ZipFile.MIN_EOCD_SIZE - WORD /* signature */ - SHORT /* comment len */);
readFully(shortBuf);
// file comment
realSkip(ZipShort.getValue(shortBuf));
}
"," private void skipRemainderOfArchive() throws IOException {
// skip over central directory. One LFH has been read too much
// already. The calculation discounts file names and extra
// data so it will be too short.
realSkip((long) entriesRead * CFH_LEN - LFH_LEN);
findEocdRecord();
realSkip((long) ZipFile.MIN_EOCD_SIZE - WORD /* signature */ - SHORT /* comment len */);
readFully(shortBuf);
// file comment
realSkip(ZipShort.getValue(shortBuf));
}
",FALSE,ZipArchiveInputStream.java
" private void findEocdRecord() throws IOException {
int currentByte = -1;
boolean skipReadCall = false;
while (skipReadCall || (currentByte = readOneByte()) > -1) {
skipReadCall = false;
if (!isFirstByteOfEocdSig(currentByte)) {
continue;
}
currentByte = readOneByte();
if (currentByte != ZipArchiveOutputStream.EOCD_SIG[1]) {
if (currentByte == -1) {
break;
}
skipReadCall = isFirstByteOfEocdSig(currentByte);
continue;
}
currentByte = readOneByte();
if (currentByte != ZipArchiveOutputStream.EOCD_SIG[2]) {
if (currentByte == -1) {
break;
}
skipReadCall = isFirstByteOfEocdSig(currentByte);
continue;
}
currentByte = readOneByte();
if (currentByte == -1
|| currentByte == ZipArchiveOutputStream.EOCD_SIG[3]) {
break;
}
skipReadCall = isFirstByteOfEocdSig(currentByte);
}
}
"," private void findEocdRecord() throws IOException {
int currentByte = -1;
boolean skipReadCall = false;
while (skipReadCall || (currentByte = readOneByte()) > -1) {
skipReadCall = false;
if (!isFirstByteOfEocdSig(currentByte)) {
continue;
}
currentByte = readOneByte();
if (currentByte != ZipArchiveOutputStream.EOCD_SIG[1]) {
if (currentByte == -1) {
break;
}
skipReadCall = isFirstByteOfEocdSig(currentByte);
continue;
}
currentByte = readOneByte();
if (currentByte != ZipArchiveOutputStream.EOCD_SIG[2]) {
if (currentByte == -1) {
break;
}
skipReadCall = isFirstByteOfEocdSig(currentByte);
continue;
}
currentByte = readOneByte();
if (currentByte == -1
|| currentByte == ZipArchiveOutputStream.EOCD_SIG[3]) {
break;
}
skipReadCall = isFirstByteOfEocdSig(currentByte);
}
}
",FALSE,ZipArchiveInputStream.java
" private void realSkip(final long value) throws IOException {
if (value >= 0) {
long skipped = 0;
while (skipped < value) {
final long rem = value - skipped;
final int x = in.read(skipBuf, 0, (int) (skipBuf.length > rem ? rem : skipBuf.length));
if (x == -1) {
return;
}
count(x);
skipped += x;
}
return;
}
throw new IllegalArgumentException();
}
"," private void realSkip(final long value) throws IOException {
if (value >= 0) {
long skipped = 0;
while (skipped < value) {
final long rem = value - skipped;
final int x = in.read(skipBuf, 0, (int) (skipBuf.length > rem ? rem : skipBuf.length));
if (x == -1) {
return;
}
count(x);
skipped += x;
}
return;
}
throw new IllegalArgumentException();
}
",FALSE,ZipArchiveInputStream.java
" private int readOneByte() throws IOException {
final int b = in.read();
if (b != -1) {
count(1);
}
return b;
}
"," private int readOneByte() throws IOException {
final int b = in.read();
if (b != -1) {
count(1);
}
return b;
}
",FALSE,ZipArchiveInputStream.java
" private boolean isFirstByteOfEocdSig(final int b) {
return b == ZipArchiveOutputStream.EOCD_SIG[0];
}
"," private boolean isFirstByteOfEocdSig(final int b) {
return b == ZipArchiveOutputStream.EOCD_SIG[0];
}
",FALSE,ZipArchiveInputStream.java
" private boolean isApkSigningBlock(byte[] suspectLocalFileHeader) throws IOException {
// length of block excluding the size field itself
BigInteger len = ZipEightByteInteger.getValue(suspectLocalFileHeader);
// LFH has already been read and all but the first eight bytes contain (part of) the APK signing block,
// also subtract 16 bytes in order to position us at the magic string
BigInteger toSkip = len.add(BigInteger.valueOf(DWORD - suspectLocalFileHeader.length
- APK_SIGNING_BLOCK_MAGIC.length));
byte[] magic = new byte[APK_SIGNING_BLOCK_MAGIC.length];
try {
if (toSkip.signum() < 0) {
// suspectLocalFileHeader contains the start of suspect magic string
int off = suspectLocalFileHeader.length + toSkip.intValue();
// length was shorter than magic length
if (off < DWORD) {
return false;
}
int bytesInBuffer = Math.abs(toSkip.intValue());
System.arraycopy(suspectLocalFileHeader, off, magic, 0, Math.min(bytesInBuffer, magic.length));
if (bytesInBuffer < magic.length) {
readFully(magic, bytesInBuffer);
}
} else {
while (toSkip.compareTo(LONG_MAX) > 0) {
realSkip(Long.MAX_VALUE);
toSkip = toSkip.add(LONG_MAX.negate());
}
realSkip(toSkip.longValue());
readFully(magic);
}
} catch (EOFException ex) {
// length was invalid
return false;
}
return Arrays.equals(magic, APK_SIGNING_BLOCK_MAGIC);
}
"," private boolean isApkSigningBlock(byte[] suspectLocalFileHeader) throws IOException {
// length of block excluding the size field itself
BigInteger len = ZipEightByteInteger.getValue(suspectLocalFileHeader);
// LFH has already been read and all but the first eight bytes contain (part of) the APK signing block,
// also subtract 16 bytes in order to position us at the magic string
BigInteger toSkip = len.add(BigInteger.valueOf(DWORD - suspectLocalFileHeader.length
- APK_SIGNING_BLOCK_MAGIC.length));
byte[] magic = new byte[APK_SIGNING_BLOCK_MAGIC.length];
try {
if (toSkip.signum() < 0) {
// suspectLocalFileHeader contains the start of suspect magic string
int off = suspectLocalFileHeader.length + toSkip.intValue();
// length was shorter than magic length
if (off < DWORD) {
return false;
}
int bytesInBuffer = Math.abs(toSkip.intValue());
System.arraycopy(suspectLocalFileHeader, off, magic, 0, Math.min(bytesInBuffer, magic.length));
if (bytesInBuffer < magic.length) {
readFully(magic, bytesInBuffer);
}
} else {
while (toSkip.compareTo(LONG_MAX) > 0) {
realSkip(Long.MAX_VALUE);
toSkip = toSkip.add(LONG_MAX.negate());
}
realSkip(toSkip.longValue());
readFully(magic);
}
} catch (EOFException ex) {
// length was invalid
return false;
}
return Arrays.equals(magic, APK_SIGNING_BLOCK_MAGIC);
}
",FALSE,ZipArchiveInputStream.java
" public BoundedInputStream(final InputStream in, final long size) {
this.max = size;
this.in = in;
}
"," public BoundedInputStream(final InputStream in, final long size) {
this.max = size;
this.in = in;
}
",FALSE,ZipArchiveInputStream.java
" public int read() throws IOException {
if (max >= 0 && pos >= max) {
return -1;
}
final int result = in.read();
pos++;
count(1);
current.bytesReadFromStream++;
return result;
}
"," public int read() throws IOException {
if (max >= 0 && pos >= max) {
return -1;
}
final int result = in.read();
pos++;
count(1);
current.bytesReadFromStream++;
return result;
}
",FALSE,ZipArchiveInputStream.java
" public int read(final byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
"," public int read(final byte[] b) throws IOException {
return this.read(b, 0, b.length);
}
",FALSE,ZipArchiveInputStream.java
" public int read(final byte[] b, final int off, final int len) throws IOException {
if (max >= 0 && pos >= max) {
return -1;
}
final long maxRead = max >= 0 ? Math.min(len, max - pos) : len;
final int bytesRead = in.read(b, off, (int) maxRead);
if (bytesRead == -1) {
return -1;
}
pos += bytesRead;
count(bytesRead);
current.bytesReadFromStream += bytesRead;
return bytesRead;
}
"," public int read(final byte[] b, final int off, final int len) throws IOException {
if (max >= 0 && pos >= max) {
return -1;
}
final long maxRead = max >= 0 ? Math.min(len, max - pos) : len;
final int bytesRead = in.read(b, off, (int) maxRead);
if (bytesRead == -1) {
return -1;
}
pos += bytesRead;
count(bytesRead);
current.bytesReadFromStream += bytesRead;
return bytesRead;
}
",FALSE,ZipArchiveInputStream.java
" public long skip(final long n) throws IOException {
final long toSkip = max >= 0 ? Math.min(n, max - pos) : n;
final long skippedBytes = IOUtils.skip(in, toSkip);
pos += skippedBytes;
return skippedBytes;
}
"," public long skip(final long n) throws IOException {
final long toSkip = max >= 0 ? Math.min(n, max - pos) : n;
final long skippedBytes = IOUtils.skip(in, toSkip);
pos += skippedBytes;
return skippedBytes;
}
",FALSE,ZipArchiveInputStream.java
" public int available() throws IOException {
if (max >= 0 && pos >= max) {
return 0;
}
return in.available();
}
"," public int available() throws IOException {
if (max >= 0 && pos >= max) {
return 0;
}
return in.available();
}
",FALSE,ZipArchiveInputStream.java
" public void testRead7ZipMultiVolumeArchiveForStream() throws IOException {
final FileInputStream archive =
new FileInputStream(getFile(""apache-maven-2.2.1.zip.001""));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive,null,false);
// these are the entries that are supposed to be processed
// correctly without any problems
for (final String element : ENTRIES) {
assertEquals(element, zi.getNextEntry().getName());
}
// this is the last entry that is truncated
final ArchiveEntry lastEntry = zi.getNextEntry();
assertEquals(LAST_ENTRY_NAME, lastEntry.getName());
final byte [] buffer = new byte [4096];
// before the fix, we'd get 0 bytes on this read and all
// subsequent reads thus a client application might enter
// an infinite loop after the fix, we should get an
// exception
try {
while (zi.read(buffer) > 0) { }
fail(""shouldn't be able to read from truncated entry"");
} catch (final IOException e) {
assertEquals(""Truncated ZIP file"", e.getMessage());
}
// and now we get another entry, which should also yield
// an exception
try {
zi.getNextEntry();
fail(""shouldn't be able to read another entry from truncated""
+ "" file"");
} catch (final IOException e) {
// this is to be expected
}
} finally {
if (zi != null) {
zi.close();
}
}
}
"," public void testRead7ZipMultiVolumeArchiveForStream() throws IOException {
final FileInputStream archive =
new FileInputStream(getFile(""apache-maven-2.2.1.zip.001""));
ZipArchiveInputStream zi = null;
try {
zi = new ZipArchiveInputStream(archive,null,false);
// these are the entries that are supposed to be processed
// correctly without any problems
for (final String element : ENTRIES) {
assertEquals(element, zi.getNextEntry().getName());
}
// this is the last entry that is truncated
final ArchiveEntry lastEntry = zi.getNextEntry();
assertEquals(LAST_ENTRY_NAME, lastEntry.getName());
final byte [] buffer = new byte [4096];
// before the fix, we'd get 0 bytes on this read and all
// subsequent reads thus a client application might enter
// an infinite loop after the fix, we should get an
// exception
try {
while (zi.read(buffer) > 0) { }
fail(""shouldn't be able to read from truncated entry"");
} catch (final IOException e) {
assertEquals(""Truncated ZIP file"", e.getMessage());
}
try {
zi.read(buffer);
fail(""shouldn't be able to read from truncated entry after exception"");
} catch (final IOException e) {
assertEquals(""Truncated ZIP file"", e.getMessage());
}
// and now we get another entry, which should also yield
// an exception
try {
zi.getNextEntry();
fail(""shouldn't be able to read another entry from truncated""
+ "" file"");
} catch (final IOException e) {
// this is to be expected
}
} finally {
if (zi != null) {
zi.close();
}
}
}
",TRUE,Maven221MultiVolumeTest.java
" public void testRead7ZipMultiVolumeArchiveForFile() throws IOException {
final File file = getFile(""apache-maven-2.2.1.zip.001"");
ZipFile zf = new ZipFile(file);
zf.close();
}
"," public void testRead7ZipMultiVolumeArchiveForFile() throws IOException {
final File file = getFile(""apache-maven-2.2.1.zip.001"");
ZipFile zf = new ZipFile(file);
zf.close();
}
",FALSE,Maven221MultiVolumeTest.java
" public void winzipBackSlashWorkaround() throws Exception {
ZipArchiveInputStream in = null;
try {
in = new ZipArchiveInputStream(new FileInputStream(getFile(""test-winzip.zip"")));
ZipArchiveEntry zae = in.getNextZipEntry();
zae = in.getNextZipEntry();
zae = in.getNextZipEntry();
assertEquals(""\u00e4/"", zae.getName());
} finally {
if (in != null) {
in.close();
}
}
}
"," public void winzipBackSlashWorkaround() throws Exception {
ZipArchiveInputStream in = null;
try {
in = new ZipArchiveInputStream(new FileInputStream(getFile(""test-winzip.zip"")));
ZipArchiveEntry zae = in.getNextZipEntry();
zae = in.getNextZipEntry();
zae = in.getNextZipEntry();
assertEquals(""\u00e4/"", zae.getName());
} finally {
if (in != null) {
in.close();
}
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void properUseOfInflater() throws Exception {
ZipFile zf = null;
ZipArchiveInputStream in = null;
try {
zf = new ZipFile(getFile(""COMPRESS-189.zip""));
final ZipArchiveEntry zae = zf.getEntry(""USD0558682-20080101.ZIP"");
in = new ZipArchiveInputStream(new BufferedInputStream(zf.getInputStream(zae)));
ZipArchiveEntry innerEntry;
while ((innerEntry = in.getNextZipEntry()) != null) {
if (innerEntry.getName().endsWith(""XML"")) {
assertTrue(0 < in.read());
}
}
} finally {
if (zf != null) {
zf.close();
}
if (in != null) {
in.close();
}
}
}
"," public void properUseOfInflater() throws Exception {
ZipFile zf = null;
ZipArchiveInputStream in = null;
try {
zf = new ZipFile(getFile(""COMPRESS-189.zip""));
final ZipArchiveEntry zae = zf.getEntry(""USD0558682-20080101.ZIP"");
in = new ZipArchiveInputStream(new BufferedInputStream(zf.getInputStream(zae)));
ZipArchiveEntry innerEntry;
while ((innerEntry = in.getNextZipEntry()) != null) {
if (innerEntry.getName().endsWith(""XML"")) {
assertTrue(0 < in.read());
}
}
} finally {
if (zf != null) {
zf.close();
}
if (in != null) {
in.close();
}
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void shouldConsumeArchiveCompletely() throws Exception {
final InputStream is = ZipArchiveInputStreamTest.class
.getResourceAsStream(""/archive_with_trailer.zip"");
final ZipArchiveInputStream zip = new ZipArchiveInputStream(is);
while (zip.getNextZipEntry() != null) {
// just consume the archive
}
final byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'
};
final byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
zip.close();
}
"," public void shouldConsumeArchiveCompletely() throws Exception {
final InputStream is = ZipArchiveInputStreamTest.class
.getResourceAsStream(""/archive_with_trailer.zip"");
final ZipArchiveInputStream zip = new ZipArchiveInputStream(is);
while (zip.getNextZipEntry() != null) {
// just consume the archive
}
final byte[] expected = new byte[] {
'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\n'
};
final byte[] actual = new byte[expected.length];
is.read(actual);
assertArrayEquals(expected, actual);
zip.close();
}
",FALSE,ZipArchiveInputStreamTest.java
" public void shouldReadNestedZip() throws IOException {
ZipArchiveInputStream in = null;
try {
in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-219.zip"")));
extractZipInputStream(in);
} finally {
if (in != null) {
in.close();
}
}
}
"," public void shouldReadNestedZip() throws IOException {
ZipArchiveInputStream in = null;
try {
in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-219.zip"")));
extractZipInputStream(in);
} finally {
if (in != null) {
in.close();
}
}
}
",FALSE,ZipArchiveInputStreamTest.java
" private void extractZipInputStream(final ZipArchiveInputStream in)
throws IOException {
ZipArchiveEntry zae = in.getNextZipEntry();
while (zae != null) {
if (zae.getName().endsWith("".zip"")) {
extractZipInputStream(new ZipArchiveInputStream(in));
}
zae = in.getNextZipEntry();
}
}
"," private void extractZipInputStream(final ZipArchiveInputStream in)
throws IOException {
ZipArchiveEntry zae = in.getNextZipEntry();
while (zae != null) {
if (zae.getName().endsWith("".zip"")) {
extractZipInputStream(new ZipArchiveInputStream(in));
}
zae = in.getNextZipEntry();
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testUnshrinkEntry() throws Exception {
final ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""SHRUNK.ZIP"")));
ZipArchiveEntry entry = in.getNextZipEntry();
assertEquals(""method"", ZipMethod.UNSHRINKING.getCode(), entry.getMethod());
assertTrue(in.canReadEntryData(entry));
FileInputStream original = new FileInputStream(getFile(""test1.xml""));
try {
assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in));
} finally {
original.close();
}
entry = in.getNextZipEntry();
assertEquals(""method"", ZipMethod.UNSHRINKING.getCode(), entry.getMethod());
assertTrue(in.canReadEntryData(entry));
original = new FileInputStream(getFile(""test2.xml""));
try {
assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in));
} finally {
original.close();
}
}
"," public void testUnshrinkEntry() throws Exception {
final ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""SHRUNK.ZIP"")));
ZipArchiveEntry entry = in.getNextZipEntry();
assertEquals(""method"", ZipMethod.UNSHRINKING.getCode(), entry.getMethod());
assertTrue(in.canReadEntryData(entry));
FileInputStream original = new FileInputStream(getFile(""test1.xml""));
try {
assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in));
} finally {
original.close();
}
entry = in.getNextZipEntry();
assertEquals(""method"", ZipMethod.UNSHRINKING.getCode(), entry.getMethod());
assertTrue(in.canReadEntryData(entry));
original = new FileInputStream(getFile(""test2.xml""));
try {
assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(in));
} finally {
original.close();
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testReadingOfFirstStoredEntry() throws Exception {
try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-264.zip"")))) {
final ZipArchiveEntry ze = in.getNextZipEntry();
assertEquals(5, ze.getSize());
assertArrayEquals(new byte[] { 'd', 'a', 't', 'a', '\n' },
IOUtils.toByteArray(in));
}
}
"," public void testReadingOfFirstStoredEntry() throws Exception {
try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-264.zip"")))) {
final ZipArchiveEntry ze = in.getNextZipEntry();
assertEquals(5, ze.getSize());
assertArrayEquals(new byte[] { 'd', 'a', 't', 'a', '\n' },
IOUtils.toByteArray(in));
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testMessageWithCorruptFileName() throws Exception {
try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-351.zip"")))) {
ZipArchiveEntry ze = in.getNextZipEntry();
while (ze != null) {
ze = in.getNextZipEntry();
}
fail(""expected EOFException"");
} catch (final EOFException ex) {
final String m = ex.getMessage();
assertTrue(m.startsWith(""Truncated ZIP entry: ?2016"")); // the first character is not printable
}
}
"," public void testMessageWithCorruptFileName() throws Exception {
try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""COMPRESS-351.zip"")))) {
ZipArchiveEntry ze = in.getNextZipEntry();
while (ze != null) {
ze = in.getNextZipEntry();
}
fail(""expected EOFException"");
} catch (final EOFException ex) {
final String m = ex.getMessage();
assertTrue(m.startsWith(""Truncated ZIP entry: ?2016"")); // the first character is not printable
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testUnzipBZip2CompressedEntry() throws Exception {
try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""bzip2-zip.zip"")))) {
final ZipArchiveEntry ze = in.getNextZipEntry();
assertEquals(42, ze.getSize());
final byte[] expected = new byte[42];
Arrays.fill(expected, (byte) 'a');
assertArrayEquals(expected, IOUtils.toByteArray(in));
}
}
"," public void testUnzipBZip2CompressedEntry() throws Exception {
try (ZipArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(getFile(""bzip2-zip.zip"")))) {
final ZipArchiveEntry ze = in.getNextZipEntry();
assertEquals(42, ze.getSize());
final byte[] expected = new byte[42];
Arrays.fill(expected, (byte) 'a');
assertArrayEquals(expected, IOUtils.toByteArray(in));
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void readDeflate64CompressedStream() throws Exception {
final File input = getFile(""COMPRESS-380/COMPRESS-380-input"");
final File archive = getFile(""COMPRESS-380/COMPRESS-380.zip"");
try (FileInputStream in = new FileInputStream(input);
ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(archive))) {
byte[] orig = IOUtils.toByteArray(in);
ZipArchiveEntry e = zin.getNextZipEntry();
byte[] fromZip = IOUtils.toByteArray(zin);
assertArrayEquals(orig, fromZip);
}
}
"," public void readDeflate64CompressedStream() throws Exception {
final File input = getFile(""COMPRESS-380/COMPRESS-380-input"");
final File archive = getFile(""COMPRESS-380/COMPRESS-380.zip"");
try (FileInputStream in = new FileInputStream(input);
ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(archive))) {
byte[] orig = IOUtils.toByteArray(in);
ZipArchiveEntry e = zin.getNextZipEntry();
byte[] fromZip = IOUtils.toByteArray(zin);
assertArrayEquals(orig, fromZip);
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception {
// this is a copy of bla.jar with META-INF/MANIFEST.MF's method manually changed to ENHANCED_DEFLATED
final File archive = getFile(""COMPRESS-380/COMPRESS-380-dd.zip"");
try (ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(archive))) {
ZipArchiveEntry e = zin.getNextZipEntry();
assertEquals(-1, e.getSize());
assertEquals(ZipMethod.ENHANCED_DEFLATED.getCode(), e.getMethod());
byte[] fromZip = IOUtils.toByteArray(zin);
byte[] expected = new byte[] {
'M', 'a', 'n', 'i', 'f', 'e', 's', 't', '-', 'V', 'e', 'r', 's', 'i', 'o', 'n', ':', ' ', '1', '.', '0',
'\r', '\n', '\r', '\n'
};
assertArrayEquals(expected, fromZip);
zin.getNextZipEntry();
assertEquals(25, e.getSize());
}
}
"," public void readDeflate64CompressedStreamWithDataDescriptor() throws Exception {
// this is a copy of bla.jar with META-INF/MANIFEST.MF's method manually changed to ENHANCED_DEFLATED
final File archive = getFile(""COMPRESS-380/COMPRESS-380-dd.zip"");
try (ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(archive))) {
ZipArchiveEntry e = zin.getNextZipEntry();
assertEquals(-1, e.getSize());
assertEquals(ZipMethod.ENHANCED_DEFLATED.getCode(), e.getMethod());
byte[] fromZip = IOUtils.toByteArray(zin);
byte[] expected = new byte[] {
'M', 'a', 'n', 'i', 'f', 'e', 's', 't', '-', 'V', 'e', 'r', 's', 'i', 'o', 'n', ':', ' ', '1', '.', '0',
'\r', '\n', '\r', '\n'
};
assertArrayEquals(expected, fromZip);
zin.getNextZipEntry();
assertEquals(25, e.getSize());
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testWithBytesAfterData() throws Exception {
final int expectedNumEntries = 2;
final InputStream is = ZipArchiveInputStreamTest.class
.getResourceAsStream(""/archive_with_bytes_after_data.zip"");
final ZipArchiveInputStream zip = new ZipArchiveInputStream(is);
try {
int actualNumEntries = 0;
ZipArchiveEntry zae = zip.getNextZipEntry();
while (zae != null) {
actualNumEntries++;
readEntry(zip, zae);
zae = zip.getNextZipEntry();
}
assertEquals(expectedNumEntries, actualNumEntries);
} finally {
zip.close();
}
}
"," public void testWithBytesAfterData() throws Exception {
final int expectedNumEntries = 2;
final InputStream is = ZipArchiveInputStreamTest.class
.getResourceAsStream(""/archive_with_bytes_after_data.zip"");
final ZipArchiveInputStream zip = new ZipArchiveInputStream(is);
try {
int actualNumEntries = 0;
ZipArchiveEntry zae = zip.getNextZipEntry();
while (zae != null) {
actualNumEntries++;
readEntry(zip, zae);
zae = zip.getNextZipEntry();
}
assertEquals(expectedNumEntries, actualNumEntries);
} finally {
zip.close();
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testThrowOnInvalidEntry() throws Exception {
final InputStream is = ZipArchiveInputStreamTest.class
.getResourceAsStream(""/invalid-zip.zip"");
final ZipArchiveInputStream zip = new ZipArchiveInputStream(is);
try {
zip.getNextZipEntry();
fail(""IOException expected"");
} catch (ZipException expected) {
assertTrue(expected.getMessage().contains(""Unexpected record signature""));
} finally {
zip.close();
}
}
"," public void testThrowOnInvalidEntry() throws Exception {
final InputStream is = ZipArchiveInputStreamTest.class
.getResourceAsStream(""/invalid-zip.zip"");
final ZipArchiveInputStream zip = new ZipArchiveInputStream(is);
try {
zip.getNextZipEntry();
fail(""IOException expected"");
} catch (ZipException expected) {
assertTrue(expected.getMessage().contains(""Unexpected record signature""));
} finally {
zip.close();
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void testOffsets() throws Exception {
// mixed.zip contains both inflated and stored files
try (InputStream archiveStream = ZipArchiveInputStream.class.getResourceAsStream(""/mixed.zip"");
ZipArchiveInputStream zipStream = new ZipArchiveInputStream((archiveStream))
) {
ZipArchiveEntry inflatedEntry = zipStream.getNextZipEntry();
Assert.assertEquals(""inflated.txt"", inflatedEntry.getName());
Assert.assertEquals(0x0000, inflatedEntry.getLocalHeaderOffset());
Assert.assertEquals(0x0046, inflatedEntry.getDataOffset());
ZipArchiveEntry storedEntry = zipStream.getNextZipEntry();
Assert.assertEquals(""stored.txt"", storedEntry.getName());
Assert.assertEquals(0x5892, storedEntry.getLocalHeaderOffset());
Assert.assertEquals(0x58d6, storedEntry.getDataOffset());
Assert.assertNull(zipStream.getNextZipEntry());
}
}
"," public void testOffsets() throws Exception {
// mixed.zip contains both inflated and stored files
try (InputStream archiveStream = ZipArchiveInputStream.class.getResourceAsStream(""/mixed.zip"");
ZipArchiveInputStream zipStream = new ZipArchiveInputStream((archiveStream))
) {
ZipArchiveEntry inflatedEntry = zipStream.getNextZipEntry();
Assert.assertEquals(""inflated.txt"", inflatedEntry.getName());
Assert.assertEquals(0x0000, inflatedEntry.getLocalHeaderOffset());
Assert.assertEquals(0x0046, inflatedEntry.getDataOffset());
ZipArchiveEntry storedEntry = zipStream.getNextZipEntry();
Assert.assertEquals(""stored.txt"", storedEntry.getName());
Assert.assertEquals(0x5892, storedEntry.getLocalHeaderOffset());
Assert.assertEquals(0x58d6, storedEntry.getDataOffset());
Assert.assertNull(zipStream.getNextZipEntry());
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void nameSourceDefaultsToName() throws Exception {
nameSource(""bla.zip"", ""test1.xml"", ZipArchiveEntry.NameSource.NAME);
}
"," public void nameSourceDefaultsToName() throws Exception {
nameSource(""bla.zip"", ""test1.xml"", ZipArchiveEntry.NameSource.NAME);
}
",FALSE,ZipArchiveInputStreamTest.java
" public void nameSourceIsSetToUnicodeExtraField() throws Exception {
nameSource(""utf8-winzip-test.zip"", ""\u20AC_for_Dollar.txt"",
ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD);
}
"," public void nameSourceIsSetToUnicodeExtraField() throws Exception {
nameSource(""utf8-winzip-test.zip"", ""\u20AC_for_Dollar.txt"",
ZipArchiveEntry.NameSource.UNICODE_EXTRA_FIELD);
}
",FALSE,ZipArchiveInputStreamTest.java
" public void nameSourceIsSetToEFS() throws Exception {
nameSource(""utf8-7zip-test.zip"", ""\u20AC_for_Dollar.txt"", 3,
ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);
}
"," public void nameSourceIsSetToEFS() throws Exception {
nameSource(""utf8-7zip-test.zip"", ""\u20AC_for_Dollar.txt"", 3,
ZipArchiveEntry.NameSource.NAME_WITH_EFS_FLAG);
}
",FALSE,ZipArchiveInputStreamTest.java
" public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception {
// we never read any data
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new ByteArrayInputStream(new byte[0]))) {
ZipArchiveEntry e = new ZipArchiveEntry(""test"");
e.setMethod(ZipMethod.DEFLATED.getCode());
assertTrue(zis.canReadEntryData(e));
e.setMethod(ZipMethod.ENHANCED_DEFLATED.getCode());
assertTrue(zis.canReadEntryData(e));
e.setMethod(ZipMethod.BZIP2.getCode());
assertFalse(zis.canReadEntryData(e));
}
}
"," public void properlyMarksEntriesAsUnreadableIfUncompressedSizeIsUnknown() throws Exception {
// we never read any data
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new ByteArrayInputStream(new byte[0]))) {
ZipArchiveEntry e = new ZipArchiveEntry(""test"");
e.setMethod(ZipMethod.DEFLATED.getCode());
assertTrue(zis.canReadEntryData(e));
e.setMethod(ZipMethod.ENHANCED_DEFLATED.getCode());
assertTrue(zis.canReadEntryData(e));
e.setMethod(ZipMethod.BZIP2.getCode());
assertFalse(zis.canReadEntryData(e));
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bla.zip""));
}
"," public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bla.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-264.zip""));
}
"," public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-264.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""SHRUNK.ZIP""));
}
"," public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""SHRUNK.ZIP""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""imploding-8Kdict-3trees.zip""));
}
"," public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""imploding-8Kdict-3trees.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-380/COMPRESS-380.zip""));
}
"," public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-380/COMPRESS-380.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bzip2-zip.zip""));
}
"," public void singleByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
singleByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bzip2-zip.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" private void singleByteReadConsistentlyReturnsMinusOneAtEof(File file) throws Exception {
try (FileInputStream in = new FileInputStream(file);
ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
ArchiveEntry e = archive.getNextEntry();
IOUtils.toByteArray(archive);
assertEquals(-1, archive.read());
assertEquals(-1, archive.read());
}
}
"," private void singleByteReadConsistentlyReturnsMinusOneAtEof(File file) throws Exception {
try (FileInputStream in = new FileInputStream(file);
ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
ArchiveEntry e = archive.getNextEntry();
IOUtils.toByteArray(archive);
assertEquals(-1, archive.read());
assertEquals(-1, archive.read());
}
}
",FALSE,ZipArchiveInputStreamTest.java
" public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bla.zip""));
}
"," public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bla.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-264.zip""));
}
"," public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingStore() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-264.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""SHRUNK.ZIP""));
}
"," public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingUnshrink() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""SHRUNK.ZIP""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""imploding-8Kdict-3trees.zip""));
}
"," public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingExplode() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""imploding-8Kdict-3trees.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-380/COMPRESS-380.zip""));
}
"," public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingDeflate64() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""COMPRESS-380/COMPRESS-380.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bzip2-zip.zip""));
}
"," public void multiByteReadConsistentlyReturnsMinusOneAtEofUsingBzip2() throws Exception {
multiByteReadConsistentlyReturnsMinusOneAtEof(getFile(""bzip2-zip.zip""));
}
",FALSE,ZipArchiveInputStreamTest.java
" private void multiByteReadConsistentlyReturnsMinusOneAtEof(File file) throws Exception {
byte[] buf = new byte[2];
try (FileInputStream in = new FileInputStream(getFile(""bla.zip""));
ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
ArchiveEntry e = archive.getNextEntry();
IOUtils.toByteArray(archive);
assertEquals(-1, archive.read(buf));
assertEquals(-1, archive.read(buf));
}
}
"," private void multiByteReadConsistentlyReturnsMinusOneAtEof(File file) throws Exception {
byte[] buf = new byte[2];
try (FileInputStream in = new FileInputStream(getFile(""bla.zip""));
ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
ArchiveEntry e = archive.getNextEntry();
IOUtils.toByteArray(archive);
assertEquals(-1, archive.read(buf));
assertEquals(-1, archive.read(buf));
}
}
",FALSE,ZipArchiveInputStreamTest.java
" }
"," public void singleByteReadThrowsAtEofForCorruptedStoredEntry() throws Exception {
byte[] content;
try (FileInputStream fs = new FileInputStream(getFile(""COMPRESS-264.zip""))) {
content = IOUtils.toByteArray(fs);
}
// make size much bigger than entry's real size
for (int i = 17; i < 26; i++) {
content[i] = (byte) 0xff;
}
try (ByteArrayInputStream in = new ByteArrayInputStream(content);
ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
ArchiveEntry e = archive.getNextEntry();
try {
IOUtils.toByteArray(archive);
fail(""expected exception"");
} catch (IOException ex) {
assertEquals(""Truncated ZIP file"", ex.getMessage());
}
try {
archive.read();
fail(""expected exception"");
} catch (IOException ex) {
assertEquals(""Truncated ZIP file"", ex.getMessage());
}
try {
archive.read();
fail(""expected exception"");
} catch (IOException ex) {
assertEquals(""Truncated ZIP file"", ex.getMessage());
}
}
}
",TRUE,ZipArchiveInputStreamTest.java
" }
"," public void multiByteReadThrowsAtEofForCorruptedStoredEntry() throws Exception {
byte[] content;
try (FileInputStream fs = new FileInputStream(getFile(""COMPRESS-264.zip""))) {
content = IOUtils.toByteArray(fs);
}
// make size much bigger than entry's real size
for (int i = 17; i < 26; i++) {
content[i] = (byte) 0xff;
}
byte[] buf = new byte[2];
try (ByteArrayInputStream in = new ByteArrayInputStream(content);
ZipArchiveInputStream archive = new ZipArchiveInputStream(in)) {
ArchiveEntry e = archive.getNextEntry();
try {
IOUtils.toByteArray(archive);
fail(""expected exception"");
} catch (IOException ex) {
assertEquals(""Truncated ZIP file"", ex.getMessage());
}
try {
archive.read(buf);
fail(""expected exception"");
} catch (IOException ex) {
assertEquals(""Truncated ZIP file"", ex.getMessage());
}
try {
archive.read(buf);
fail(""expected exception"");
} catch (IOException ex) {
assertEquals(""Truncated ZIP file"", ex.getMessage());
}
}
}
",TRUE,ZipArchiveInputStreamTest.java
" private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException {
final int len = (int)zae.getSize();
final byte[] buff = new byte[len];
zip.read(buff, 0, len);
return buff;
}
"," private static byte[] readEntry(ZipArchiveInputStream zip, ZipArchiveEntry zae) throws IOException {
final int len = (int)zae.getSize();
final byte[] buff = new byte[len];
zip.read(buff, 0, len);
return buff;
}
",FALSE,ZipArchiveInputStreamTest.java
" private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception {
nameSource(archive, entry, 1, expected);
}
"," private static void nameSource(String archive, String entry, ZipArchiveEntry.NameSource expected) throws Exception {
nameSource(archive, entry, 1, expected);
}
",FALSE,ZipArchiveInputStreamTest.java
" private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected)
throws Exception {
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(getFile(archive)))) {
ZipArchiveEntry ze;
do {
ze = zis.getNextZipEntry();
} while (--entryNo > 0);
assertEquals(entry, ze.getName());
assertEquals(expected, ze.getNameSource());
}
}
"," private static void nameSource(String archive, String entry, int entryNo, ZipArchiveEntry.NameSource expected)
throws Exception {
try (ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(getFile(archive)))) {
ZipArchiveEntry ze;
do {
ze = zis.getNextZipEntry();
} while (--entryNo > 0);
assertEquals(entry, ze.getName());
assertEquals(expected, ze.getNameSource());
}
}
",FALSE,ZipArchiveInputStreamTest.java
" protected void activate() {
factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
}
"," protected void activate() {
factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
try {
factory.setFeature(""http://apache.org/xml/features/nonvalidating/load-external-dtd"", false);
factory.setFeature(""http://xml.org/sax/features/external-parameter-entities"", false);
factory.setFeature(""http://xml.org/sax/features/external-general-entities"", false);
} catch (Exception e) {
LOGGER.error(""SAX parser configuration error: "" + e.getMessage(), e);
}
}
",TRUE,XSSAPIImpl.java
" protected void deactivate() {
factory = null;
}
"," protected void deactivate() {
factory = null;
}
",FALSE,XSSAPIImpl.java
" public Integer getValidInteger(String integer, int defaultValue) {
if (integer != null && integer.length() > 0) {
try {
return validator.getValidInteger(""XSS"", integer, -2000000000, 2000000000, false);
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
"," public Integer getValidInteger(String integer, int defaultValue) {
if (integer != null && integer.length() > 0) {
try {
return validator.getValidInteger(""XSS"", integer, -2000000000, 2000000000, false);
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
",FALSE,XSSAPIImpl.java
" public Long getValidLong(String source, long defaultValue) {
if (source != null && source.length() > 0) {
try {
LongValidationRule ivr = new LongValidationRule( ""number"", ESAPI.encoder(), -9000000000000000000L, 9000000000000000000L );
ivr.setAllowNull(false);
return ivr.getValid(""XSS"", source);
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
"," public Long getValidLong(String source, long defaultValue) {
if (source != null && source.length() > 0) {
try {
LongValidationRule ivr = new LongValidationRule( ""number"", ESAPI.encoder(), -9000000000000000000L, 9000000000000000000L );
ivr.setAllowNull(false);
return ivr.getValid(""XSS"", source);
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
",FALSE,XSSAPIImpl.java
" public Double getValidDouble(String source, double defaultValue) {
if (source != null && source.length() > 0) {
try {
return validator.getValidDouble(""XSS"", source, 0d, Double.MAX_VALUE, false);
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
"," public Double getValidDouble(String source, double defaultValue) {
if (source != null && source.length() > 0) {
try {
return validator.getValidDouble(""XSS"", source, 0d, Double.MAX_VALUE, false);
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
",FALSE,XSSAPIImpl.java
" public String getValidDimension(String dimension, String defaultValue) {
if (dimension != null && dimension.length() > 0) {
if (PATTERN_AUTO_DIMENSION.matcher(dimension).matches()) {
return ""\""auto\"""";
}
try {
return validator.getValidInteger(""XSS"", dimension, -10000, 10000, false).toString();
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
"," public String getValidDimension(String dimension, String defaultValue) {
if (dimension != null && dimension.length() > 0) {
if (PATTERN_AUTO_DIMENSION.matcher(dimension).matches()) {
return ""\""auto\"""";
}
try {
return validator.getValidInteger(""XSS"", dimension, -10000, 10000, false).toString();
} catch (Exception e) {
// ignore
}
}
// fall through to default if empty, null, or validation failure
return defaultValue;
}
",FALSE,XSSAPIImpl.java
" private String mangleNamespaces(String absPath) {
if (absPath != null) {
// check for absolute urls
final int schemeIndex = absPath.indexOf(SCHEME_PATTERN);
final String manglePath;
final String prefix;
if (schemeIndex != -1) {
final int pathIndex = absPath.indexOf(""/"", schemeIndex + 3);
if (pathIndex != -1) {
prefix = absPath.substring(0, pathIndex);
manglePath = absPath.substring(pathIndex);
} else {
prefix = absPath;
manglePath = """";
}
} else {
prefix = """";
manglePath = absPath;
}
if (manglePath.contains(MANGLE_NAMESPACE_OUT_SUFFIX)) {
final Matcher m = MANGLE_NAMESPACE_PATTERN.matcher(manglePath);
final StringBuffer buf = new StringBuffer();
while (m.find()) {
final String replacement = MANGLE_NAMESPACE_IN_PREFIX + m.group(1) + MANGLE_NAMESPACE_IN_SUFFIX;
m.appendReplacement(buf, replacement);
}
m.appendTail(buf);
absPath = prefix + buf.toString();
}
}
return absPath;
}
"," private String mangleNamespaces(String absPath) {
if (absPath != null) {
// check for absolute urls
final int schemeIndex = absPath.indexOf(SCHEME_PATTERN);
final String manglePath;
final String prefix;
if (schemeIndex != -1) {
final int pathIndex = absPath.indexOf(""/"", schemeIndex + 3);
if (pathIndex != -1) {
prefix = absPath.substring(0, pathIndex);
manglePath = absPath.substring(pathIndex);
} else {
prefix = absPath;
manglePath = """";
}
} else {
prefix = """";
manglePath = absPath;
}
if (manglePath.contains(MANGLE_NAMESPACE_OUT_SUFFIX)) {
final Matcher m = MANGLE_NAMESPACE_PATTERN.matcher(manglePath);
final StringBuffer buf = new StringBuffer();
while (m.find()) {
final String replacement = MANGLE_NAMESPACE_IN_PREFIX + m.group(1) + MANGLE_NAMESPACE_IN_SUFFIX;
m.appendReplacement(buf, replacement);
}
m.appendTail(buf);
absPath = prefix + buf.toString();
}
}
return absPath;
}
",FALSE,XSSAPIImpl.java
" public String getValidHref(final String url) {
if (url != null && url.length() > 0) {
// Percent-encode characters that are not allowed in unquoted
// HTML attributes: "", ', >, <, ` and space. We don't encode =
// since this would break links with query parameters.
String encodedUrl = url.replaceAll(""\"""", ""%22"")
.replaceAll(""'"", ""%27"")
.replaceAll("">"", ""%3E"")
.replaceAll(""<"", ""%3C"")
.replaceAll(""`"", ""%60"")
.replaceAll("" "", ""%20"");
int qMarkIx = encodedUrl.indexOf('?');
if (qMarkIx > 0) {
encodedUrl = encodedUrl.substring(0, qMarkIx) + encodedUrl.substring(qMarkIx).replaceAll("":"", ""%3A"");
}
encodedUrl = mangleNamespaces(encodedUrl);
if (xssFilter.isValidHref(encodedUrl)) {
return encodedUrl;
}
}
// fall through to empty string
return """";
}
"," public String getValidHref(final String url) {
if (url != null && url.length() > 0) {
// Percent-encode characters that are not allowed in unquoted
// HTML attributes: "", ', >, <, ` and space. We don't encode =
// since this would break links with query parameters.
String encodedUrl = url.replaceAll(""\"""", ""%22"")
.replaceAll(""'"", ""%27"")
.replaceAll("">"", ""%3E"")
.replaceAll(""<"", ""%3C"")
.replaceAll(""`"", ""%60"")
.replaceAll("" "", ""%20"");
int qMarkIx = encodedUrl.indexOf('?');
if (qMarkIx > 0) {
encodedUrl = encodedUrl.substring(0, qMarkIx) + encodedUrl.substring(qMarkIx).replaceAll("":"", ""%3A"");
}
encodedUrl = mangleNamespaces(encodedUrl);
if (xssFilter.isValidHref(encodedUrl)) {
return encodedUrl;
}
}
// fall through to empty string
return """";
}
",FALSE,XSSAPIImpl.java
" public String getValidJSToken(String token, String defaultValue) {
if (token != null && token.length() > 0) {
token = token.trim();
String q = token.substring(0, 1);
if (q.matches(""['\""]"") && token.endsWith(q)) {
String literal = token.substring(1, token.length() - 1);
return q + encodeForJSString(literal) + q;
} else if (token.matches(""[0-9a-zA-Z_$][0-9a-zA-Z_$.]*"")) {
return token;
}
}
// fall through to default value
return defaultValue;
}
"," public String getValidJSToken(String token, String defaultValue) {
if (token != null && token.length() > 0) {
token = token.trim();
String q = token.substring(0, 1);
if (q.matches(""['\""]"") && token.endsWith(q)) {
String literal = token.substring(1, token.length() - 1);
return q + encodeForJSString(literal) + q;
} else if (token.matches(""[0-9a-zA-Z_$][0-9a-zA-Z_$.]*"")) {
return token;
}
}
// fall through to default value
return defaultValue;
}
",FALSE,XSSAPIImpl.java
" public String getValidStyleToken(String token, String defaultValue) {
if (token != null && token.length() > 0 && token.matches(CSS_TOKEN)) {
return token;
}
return defaultValue;
}
"," public String getValidStyleToken(String token, String defaultValue) {
if (token != null && token.length() > 0 && token.matches(CSS_TOKEN)) {
return token;
}
return defaultValue;
}
",FALSE,XSSAPIImpl.java
" public String getValidCSSColor(String color, String defaultColor) {
if (color != null && color.length() > 0) {
color = color.trim();
/*
* Avoid security implications by including only the characters required to specify colors in hex
* or functional notation. Critical characters disallowed: x (as in expression(...)),
* u (as in url(...)) and semi colon (as in escaping the context of the color value).
*/
if (color.matches(""(?i)[#a-fghlrs(+0-9-.%,) \\t\\n\\x0B\\f\\r]+"")) {
return color;
}
// named color values
if (color.matches(""(?i)[a-zA-Z \\t\\n\\x0B\\f\\r]+"")) {
return color;
}
}
return defaultColor;
}
"," public String getValidCSSColor(String color, String defaultColor) {
if (color != null && color.length() > 0) {
color = color.trim();
/*
* Avoid security implications by including only the characters required to specify colors in hex
* or functional notation. Critical characters disallowed: x (as in expression(...)),
* u (as in url(...)) and semi colon (as in escaping the context of the color value).
*/
if (color.matches(""(?i)[#a-fghlrs(+0-9-.%,) \\t\\n\\x0B\\f\\r]+"")) {
return color;
}
// named color values
if (color.matches(""(?i)[a-zA-Z \\t\\n\\x0B\\f\\r]+"")) {
return color;
}
}
return defaultColor;
}
",FALSE,XSSAPIImpl.java
" public String getValidMultiLineComment(String comment, String defaultComment) {
if (comment != null && !comment.contains(""*/"")) {
return comment;
}
return defaultComment;
}
"," public String getValidMultiLineComment(String comment, String defaultComment) {
if (comment != null && !comment.contains(""*/"")) {
return comment;
}
return defaultComment;
}
",FALSE,XSSAPIImpl.java
" public String getValidJSON(String json, String defaultJson) {
if (json == null) {
return getValidJSON(defaultJson, """");
}
json = json.trim();
if ("""".equals(json)) {
return """";
}
int curlyIx = json.indexOf(""{"");
int straightIx = json.indexOf(""["");
if (curlyIx >= 0 && (curlyIx < straightIx || straightIx < 0)) {
try {
JSONObject obj = new JSONObject(json);
return obj.toString();
} catch (JSONException e) {
LOGGER.debug(""JSON validation failed: "" + e.getMessage(), e);
}
} else {
try {
JSONArray arr = new JSONArray(json);
return arr.toString();
} catch (JSONException e) {
LOGGER.debug(""JSON validation failed: "" + e.getMessage(), e);
}
}
return getValidJSON(defaultJson, """");
}
"," public String getValidJSON(String json, String defaultJson) {
if (json == null) {
return getValidJSON(defaultJson, """");
}
json = json.trim();
if ("""".equals(json)) {
return """";
}
int curlyIx = json.indexOf(""{"");
int straightIx = json.indexOf(""["");
if (curlyIx >= 0 && (curlyIx < straightIx || straightIx < 0)) {
try {
JSONObject obj = new JSONObject(json);
return obj.toString();
} catch (JSONException e) {
LOGGER.debug(""JSON validation failed: "" + e.getMessage(), e);
}
} else {
try {
JSONArray arr = new JSONArray(json);
return arr.toString();
} catch (JSONException e) {
LOGGER.debug(""JSON validation failed: "" + e.getMessage(), e);
}
}
return getValidJSON(defaultJson, """");
}
",FALSE,XSSAPIImpl.java
" public String getValidXML(String xml, String defaultXml) {
if (xml == null) {
return getValidXML(defaultXml, """");
}
xml = xml.trim();
if ("""".equals(xml)) {
return """";
}
try {
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.parse(new InputSource(new StringReader(xml)));
return xml;
} catch (Exception e) {
LOGGER.debug(""XML validation failed: "" + e.getMessage(), e);
}
return getValidXML(defaultXml, """");
}
"," public String getValidXML(String xml, String defaultXml) {
if (xml == null) {
return getValidXML(defaultXml, """");
}
xml = xml.trim();
if ("""".equals(xml)) {
return """";
}
try {
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.parse(new InputSource(new StringReader(xml)));
return xml;
} catch (Exception e) {
LOGGER.debug(""XML validation failed: "" + e.getMessage(), e);
}
return getValidXML(defaultXml, """");
}
",FALSE,XSSAPIImpl.java
" public String encodeForHTML(String source) {
return source == null ? null : Encode.forHtml(source);
}
"," public String encodeForHTML(String source) {
return source == null ? null : Encode.forHtml(source);
}
",FALSE,XSSAPIImpl.java
" public String encodeForHTMLAttr(String source) {
return source == null ? null : Encode.forHtmlAttribute(source);
}
"," public String encodeForHTMLAttr(String source) {
return source == null ? null : Encode.forHtmlAttribute(source);
}
",FALSE,XSSAPIImpl.java
" public String encodeForXML(String source) {
return source == null ? null : Encode.forXml(source);
}
"," public String encodeForXML(String source) {
return source == null ? null : Encode.forXml(source);
}
",FALSE,XSSAPIImpl.java
" public String encodeForXMLAttr(String source) {
return source == null ? null : Encode.forXmlAttribute(source);
}
"," public String encodeForXMLAttr(String source) {
return source == null ? null : Encode.forXmlAttribute(source);
}
",FALSE,XSSAPIImpl.java
" public String encodeForJSString(String source) {
return source == null ? null : Encode.forJavaScript(source).replace(""\\-"", ""\\u002D"");
}
"," public String encodeForJSString(String source) {
return source == null ? null : Encode.forJavaScript(source).replace(""\\-"", ""\\u002D"");
}
",FALSE,XSSAPIImpl.java
" public String encodeForCSSString(String source) {
return source == null ? null : Encode.forCssString(source);
}
"," public String encodeForCSSString(String source) {
return source == null ? null : Encode.forCssString(source);
}
",FALSE,XSSAPIImpl.java
" public String filterHTML(String source) {
return xssFilter.filter(ProtectionContext.HTML_HTML_CONTENT, source);
}
"," public String filterHTML(String source) {
return xssFilter.filter(ProtectionContext.HTML_HTML_CONTENT, source);
}
",FALSE,XSSAPIImpl.java
" public XSSAPI getRequestSpecificAPI(final SlingHttpServletRequest request) {
return this;
}
"," public XSSAPI getRequestSpecificAPI(final SlingHttpServletRequest request) {
return this;
}
",FALSE,XSSAPIImpl.java
" public XSSAPI getResourceResolverSpecificAPI(final ResourceResolver resourceResolver) {
return this;
}
"," public XSSAPI getResourceResolverSpecificAPI(final ResourceResolver resourceResolver) {
return this;
}
",FALSE,XSSAPIImpl.java
" public void setup() {
try {
XSSFilterImpl xssFilter = new XSSFilterImpl();
setDefaultHandler(xssFilter, ""./src/main/resources/SLING-INF/content/config.xml"");
xssAPI = new XSSAPIImpl();
Whitebox.invokeMethod(xssAPI, ""activate"");
Field filterField = XSSAPIImpl.class.getDeclaredField(""xssFilter"");
filterField.setAccessible(true);
filterField.set(xssAPI, xssFilter);
ResourceResolver mockResolver = mock(ResourceResolver.class);
when(mockResolver.map(anyString())).thenAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
String url = (String) args[0];
return url.replaceAll(""jcr:"", ""_jcr_"");
}
});
SlingHttpServletRequest mockRequest = mock(SlingHttpServletRequest.class);
when(mockRequest.getResourceResolver()).thenReturn(mockResolver);
xssAPI = xssAPI.getRequestSpecificAPI(mockRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
"," public void setup() {
try {
XSSFilterImpl xssFilter = new XSSFilterImpl();
setDefaultHandler(xssFilter, ""./src/main/resources/SLING-INF/content/config.xml"");
xssAPI = new XSSAPIImpl();
Whitebox.invokeMethod(xssAPI, ""activate"");
Field filterField = XSSAPIImpl.class.getDeclaredField(""xssFilter"");
filterField.setAccessible(true);
filterField.set(xssAPI, xssFilter);
ResourceResolver mockResolver = mock(ResourceResolver.class);
when(mockResolver.map(anyString())).thenAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
String url = (String) args[0];
return url.replaceAll(""jcr:"", ""_jcr_"");
}
});
SlingHttpServletRequest mockRequest = mock(SlingHttpServletRequest.class);
when(mockRequest.getResourceResolver()).thenReturn(mockResolver);
xssAPI = xssAPI.getRequestSpecificAPI(mockRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
",FALSE,XSSAPIImplTest.java
" private static void setDefaultHandler(XSSFilterImpl xssFilter, String filename) throws Exception {
InputStream policyStream = new FileInputStream(filename);
Policy policy = Policy.getInstance(policyStream);
AntiSamy antiSamy = new AntiSamy(policy);
PolicyHandler mockPolicyHandler = mock(PolicyHandler.class);
when(mockPolicyHandler.getPolicy()).thenReturn(policy);
when(mockPolicyHandler.getAntiSamy()).thenReturn(antiSamy);
Whitebox.invokeMethod(xssFilter, ""setDefaultHandler"", mockPolicyHandler);
}
"," private static void setDefaultHandler(XSSFilterImpl xssFilter, String filename) throws Exception {
InputStream policyStream = new FileInputStream(filename);
Policy policy = Policy.getInstance(policyStream);
AntiSamy antiSamy = new AntiSamy(policy);
PolicyHandler mockPolicyHandler = mock(PolicyHandler.class);
when(mockPolicyHandler.getPolicy()).thenReturn(policy);
when(mockPolicyHandler.getAntiSamy()).thenReturn(antiSamy);
Whitebox.invokeMethod(xssFilter, ""setDefaultHandler"", mockPolicyHandler);
}
",FALSE,XSSAPIImplTest.java
" public void testEncodeForHTML() {
String[][] testData = {
// Source Expected Result
//
{null, null},
{""simple"", ""simple""},
{"""", """ <script>alert('pwned');</script>""},
{""günter"", ""günter""},
{""\u30e9\u30c9\u30af\u30ea\u30d5\u3001\u30de\u30e9\u30bd\u30f3\u4e94\u8f2a\u4ee3\u8868\u306b1\u4e07m\u51fa\u5834\u306b\u3082\u542b\u307f"", ""\u30e9\u30c9\u30af\u30ea\u30d5\u3001\u30de\u30e9\u30bd\u30f3\u4e94\u8f2a\u4ee3\u8868\u306b1\u4e07m\u51fa\u5834\u306b\u3082\u542b\u307f""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""HTML Encoding '"" + source + ""'"", expected, xssAPI.encodeForHTMLAttr(source));
}
}
"," public void testEncodeForHTMLAttr() {
String[][] testData = {
// Source Expected Result
//
{null, null},
{""simple"", ""simple""},
{"""", """ <script>alert('pwned');</script>""},
{""günter"", ""günter""},
{""\u30e9\u30c9\u30af\u30ea\u30d5\u3001\u30de\u30e9\u30bd\u30f3\u4e94\u8f2a\u4ee3\u8868\u306b1\u4e07m\u51fa\u5834\u306b\u3082\u542b\u307f"", ""\u30e9\u30c9\u30af\u30ea\u30d5\u3001\u30de\u30e9\u30bd\u30f3\u4e94\u8f2a\u4ee3\u8868\u306b1\u4e07m\u51fa\u5834\u306b\u3082\u542b\u307f""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""HTML Encoding '"" + source + ""'"", expected, xssAPI.encodeForHTMLAttr(source));
}
}
",FALSE,XSSAPIImplTest.java
" public void testEncodeForXML() {
String[][] testData = {
// Source Expected Result
//
{null, null},
{""simple"", ""simple""},
{"""", """"},
{""wow! "", ""wow! ""},
{""nice
"", ""nice
""},
{"" "", """"},
{"" "", "" ""},
{"""", """"},
{""günter"", ""günter""},
{""strike "", ""strike ""},
{""s "", ""s ""},
{""empty href "", ""empty href ""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""Filtering '"" + source + ""'"", expected, xssAPI.filterHTML(source));
}
}
"," public void testFilterHTML() {
String[][] testData = {
// Source Expected Result
{null, """"},
{"""", """"},
{""simple"", ""simple""},
{"""", """"},
{""wow! "", ""wow! ""},
{""nice
"", ""nice
""},
{"" "", """"},
{"" "", "" ""},
{"""", """"},
{""günter"", ""günter""},
{""strike "", ""strike ""},
{""s "", ""s ""},
{""empty href "", ""empty href ""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""Filtering '"" + source + ""'"", expected, xssAPI.filterHTML(source));
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidHref() {
String[][] testData = {
// Href Expected Result
//
{null, """"},
{"""", """"},
{""simple"", ""simple""},
{""../parent"", ""../parent""},
{""repo/günter"", ""repo/günter""},
// JCR namespaces:
{""my/page/jcr:content.feed"", ""my/page/_jcr_content.feed""},
{""my/jcr:content/page/jcr:content"", ""my/_jcr_content/page/_jcr_content""},
{""\"" onClick=ugly"", ""%22%20onClick=ugly""},
{""javascript:ugly"", """"},
{""http://localhost:4502"", ""http://localhost:4502""},
{""http://localhost:4502/test"", ""http://localhost:4502/test""},
{""http://localhost:4502/jcr:content/test"", ""http://localhost:4502/_jcr_content/test""},
{""http://localhost:4502/test.html?a=b&b=c"", ""http://localhost:4502/test.html?a=b&b=c""},
// space
{""/test/ab cd"", ""/test/ab%20cd""},
{""http://localhost:4502/test/ab cd"", ""http://localhost:4502/test/ab%20cd""},
{""/test/ab attr=c"", ""/test/ab%20attr=c""},
{""http://localhost:4502/test/ab attr=c"", ""http://localhost:4502/test/ab%20attr=c""},
// ""
{""/test/ab\""cd"", ""/test/ab%22cd""},
{""http://localhost:4502/test/ab\""cd"", ""http://localhost:4502/test/ab%22cd""},
// '
{""/test/ab'cd"", ""/test/ab%27cd""},
{""http://localhost:4502/test/ab'cd"", ""http://localhost:4502/test/ab%27cd""},
// =
{""/test/ab=cd"", ""/test/ab=cd""},
{""http://localhost:4502/test/ab=cd"", ""http://localhost:4502/test/ab=cd""},
// >
{""/test/ab>cd"", ""/test/ab%3Ecd""},
{""http://localhost:4502/test/ab>cd"", ""http://localhost:4502/test/ab%3Ecd""},
// <
{""/test/ab
{""/test/ab>cd"", ""/test/ab%3Ecd""},
{""http://localhost:4502/test/ab>cd"", ""http://localhost:4502/test/ab%3Ecd""},
// <
{""/test/ab"", ""<\\/script>""},
{""'alert(document.cookie)"", ""\\x27alert(document.cookie)""},
{""2014-04-22T10:11:24.002+01:00"", ""2014\\u002D04\\u002D22T10:11:24.002+01:00""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""Encoding '"" + source + ""'"", expected, xssAPI.encodeForJSString(source));
}
}
"," public void testEncodeForJSString() {
String[][] testData = {
// Source Expected Result
//
{null, null},
{""simple"", ""simple""},
{""break\""out"", ""break\\x22out""},
{""break'out"", ""break\\x27out""},
{"""", ""<\\/script>""},
{""'alert(document.cookie)"", ""\\x27alert(document.cookie)""},
{""2014-04-22T10:11:24.002+01:00"", ""2014\\u002D04\\u002D22T10:11:24.002+01:00""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""Encoding '"" + source + ""'"", expected, xssAPI.encodeForJSString(source));
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidJSToken() {
String[][] testData = {
// Source Expected Result
//
{null, RUBBISH},
{"""", RUBBISH},
{""simple"", ""simple""},
{""clickstreamcloud.thingy"", ""clickstreamcloud.thingy""},
{""break out"", RUBBISH},
{""break,out"", RUBBISH},
{""\""literal string\"""", ""\""literal string\""""},
{""'literal string'"", ""'literal string'""},
{""\""bad literal'"", RUBBISH},
{""'literal'); junk'"", ""'literal\\x27); junk'""},
{""1200"", ""1200""},
{""3.14"", ""3.14""},
{""1,200"", RUBBISH},
{""1200 + 1"", RUBBISH}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""Validating Javascript token '"" + source + ""'"", expected, xssAPI.getValidJSToken(source, RUBBISH));
}
}
"," public void testGetValidJSToken() {
String[][] testData = {
// Source Expected Result
//
{null, RUBBISH},
{"""", RUBBISH},
{""simple"", ""simple""},
{""clickstreamcloud.thingy"", ""clickstreamcloud.thingy""},
{""break out"", RUBBISH},
{""break,out"", RUBBISH},
{""\""literal string\"""", ""\""literal string\""""},
{""'literal string'"", ""'literal string'""},
{""\""bad literal'"", RUBBISH},
{""'literal'); junk'"", ""'literal\\x27); junk'""},
{""1200"", ""1200""},
{""3.14"", ""3.14""},
{""1,200"", RUBBISH},
{""1200 + 1"", RUBBISH}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
TestCase.assertEquals(""Validating Javascript token '"" + source + ""'"", expected, xssAPI.getValidJSToken(source, RUBBISH));
}
}
",FALSE,XSSAPIImplTest.java
" public void testEncodeForCSSString() {
String[][] testData = {
// Source Expected result
{null, null},
{""test"" , ""test""},
{""\\"" , ""\\5c""},
{""'"" , ""\\27""},
{""\"""" , ""\\22""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.encodeForCSSString(source);
TestCase.assertEquals(""Encoding '"" + source + ""'"", expected, result);
}
}
"," public void testEncodeForCSSString() {
String[][] testData = {
// Source Expected result
{null, null},
{""test"" , ""test""},
{""\\"" , ""\\5c""},
{""'"" , ""\\27""},
{""\"""" , ""\\22""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.encodeForCSSString(source);
TestCase.assertEquals(""Encoding '"" + source + ""'"", expected, result);
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidStyleToken() {
String[][] testData = {
// Source Expected result
{null , RUBBISH},
{"""" , RUBBISH},
// CSS close
{""}"" , RUBBISH},
// line break
{""br\neak"" , RUBBISH},
// no javascript:
{""javascript:alert(1)"" , RUBBISH},
{""'javascript:alert(1)'"" , RUBBISH},
{""\""javascript:alert('XSS')\"""" , RUBBISH},
{""url(javascript:alert(1))"" , RUBBISH},
{""url('javascript:alert(1)')"" , RUBBISH},
{""url(\""javascript:alert('XSS')\"")"" , RUBBISH},
// no expression
{""expression(alert(1))"" , RUBBISH},
{""expression (alert(1))"" , RUBBISH},
{""expression(this.location='a.co')"" , RUBBISH},
// html tags
{"""", RUBBISH},
// usual CSS stuff
{""background-color"" , ""background-color""},
{""-moz-box-sizing"" , ""-moz-box-sizing""},
{"".42%"" , "".42%""},
{""#fff"" , ""#fff""},
// valid strings
{""'literal string'"" , ""'literal string'""},
{""\""literal string\"""" , ""\""literal string\""""},
{""'it\\'s here'"" , ""'it\\'s here'""},
{""\""it\\\""s here\"""" , ""\""it\\\""s here\""""},
// invalid strings
{""\""bad string"" , RUBBISH},
{""'it's here'"" , RUBBISH},
{""\""it\""s here\"""" , RUBBISH},
// valid parenthesis
{""rgb(255, 255, 255)"" , ""rgb(255, 255, 255)""},
// invalid parenthesis
{""rgb(255, 255, 255"" , RUBBISH},
{""255, 255, 255)"" , RUBBISH},
// valid tokens
{""url(http://example.com/test.png)"", ""url(http://example.com/test.png)""},
{""url('image/test.png')"" , ""url('image/test.png')""},
// invalid tokens
{""color: red"" , RUBBISH}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidStyleToken(source, RUBBISH);
if (!result.equals(expected)) {
fail(""Validating style token '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
"," public void testGetValidStyleToken() {
String[][] testData = {
// Source Expected result
{null , RUBBISH},
{"""" , RUBBISH},
// CSS close
{""}"" , RUBBISH},
// line break
{""br\neak"" , RUBBISH},
// no javascript:
{""javascript:alert(1)"" , RUBBISH},
{""'javascript:alert(1)'"" , RUBBISH},
{""\""javascript:alert('XSS')\"""" , RUBBISH},
{""url(javascript:alert(1))"" , RUBBISH},
{""url('javascript:alert(1)')"" , RUBBISH},
{""url(\""javascript:alert('XSS')\"")"" , RUBBISH},
// no expression
{""expression(alert(1))"" , RUBBISH},
{""expression (alert(1))"" , RUBBISH},
{""expression(this.location='a.co')"" , RUBBISH},
// html tags
{"""", RUBBISH},
// usual CSS stuff
{""background-color"" , ""background-color""},
{""-moz-box-sizing"" , ""-moz-box-sizing""},
{"".42%"" , "".42%""},
{""#fff"" , ""#fff""},
// valid strings
{""'literal string'"" , ""'literal string'""},
{""\""literal string\"""" , ""\""literal string\""""},
{""'it\\'s here'"" , ""'it\\'s here'""},
{""\""it\\\""s here\"""" , ""\""it\\\""s here\""""},
// invalid strings
{""\""bad string"" , RUBBISH},
{""'it's here'"" , RUBBISH},
{""\""it\""s here\"""" , RUBBISH},
// valid parenthesis
{""rgb(255, 255, 255)"" , ""rgb(255, 255, 255)""},
// invalid parenthesis
{""rgb(255, 255, 255"" , RUBBISH},
{""255, 255, 255)"" , RUBBISH},
// valid tokens
{""url(http://example.com/test.png)"", ""url(http://example.com/test.png)""},
{""url('image/test.png')"" , ""url('image/test.png')""},
// invalid tokens
{""color: red"" , RUBBISH}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidStyleToken(source, RUBBISH);
if (!result.equals(expected)) {
fail(""Validating style token '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidCSSColor() {
String[][] testData = {
// Source Expected Result
//
{null, RUBBISH},
{"""", RUBBISH},
{""rgb(0,+0,-0)"", ""rgb(0,+0,-0)""},
{""rgba ( 0\f%, 0%,\t0%,\n100%\r)"", ""rgba ( 0\f%, 0%,\t0%,\n100%\r)"",},
{""#ddd"", ""#ddd""},
{""#eeeeee"", ""#eeeeee"",},
{""hsl(0,1,2)"", ""hsl(0,1,2)""},
{""hsla(0,1,2,3)"", ""hsla(0,1,2,3)""},
{""currentColor"", ""currentColor""},
{""transparent"", ""transparent""},
{""\f\r\n\t MenuText\f\r\n\t "", ""MenuText""},
{""expression(99,99,99)"", RUBBISH},
{""blue;"", RUBBISH},
{""url(99,99,99)"", RUBBISH}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidCSSColor(source, RUBBISH);
if (!result.equals(expected)) {
fail(""Validating CSS Color '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
"," public void testGetValidCSSColor() {
String[][] testData = {
// Source Expected Result
//
{null, RUBBISH},
{"""", RUBBISH},
{""rgb(0,+0,-0)"", ""rgb(0,+0,-0)""},
{""rgba ( 0\f%, 0%,\t0%,\n100%\r)"", ""rgba ( 0\f%, 0%,\t0%,\n100%\r)"",},
{""#ddd"", ""#ddd""},
{""#eeeeee"", ""#eeeeee"",},
{""hsl(0,1,2)"", ""hsl(0,1,2)""},
{""hsla(0,1,2,3)"", ""hsla(0,1,2,3)""},
{""currentColor"", ""currentColor""},
{""transparent"", ""transparent""},
{""\f\r\n\t MenuText\f\r\n\t "", ""MenuText""},
{""expression(99,99,99)"", RUBBISH},
{""blue;"", RUBBISH},
{""url(99,99,99)"", RUBBISH}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidCSSColor(source, RUBBISH);
if (!result.equals(expected)) {
fail(""Validating CSS Color '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidMultiLineComment() {
String[][] testData = {
//Source Expected Result
{null , RUBBISH},
{""blah */ hack"" , RUBBISH},
{""Valid comment"" , ""Valid comment""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidMultiLineComment(source, RUBBISH);
if (!result.equals(expected)) {
fail(""Validating multiline comment '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
"," public void testGetValidMultiLineComment() {
String[][] testData = {
//Source Expected Result
{null , RUBBISH},
{""blah */ hack"" , RUBBISH},
{""Valid comment"" , ""Valid comment""}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidMultiLineComment(source, RUBBISH);
if (!result.equals(expected)) {
fail(""Validating multiline comment '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidJSON() {
String[][] testData = {
{null, RUBBISH_JSON},
{"""", """"},
{""1]"", RUBBISH_JSON},
{""{}"", ""{}""},
{""{1}"", RUBBISH_JSON},
{
""{test: 'test'}"",
""{\""test\"":\""test\""}""
},
{
""{test:\""test}"",
RUBBISH_JSON
},
{
""{test1:'test1', test2: {test21: 'test21', test22: 'test22'}}"",
""{\""test1\"":\""test1\"",\""test2\"":{\""test21\"":\""test21\"",\""test22\"":\""test22\""}}""
},
{""[]"", ""[]""},
{""[1,2]"", ""[1,2]""},
{""[1"", RUBBISH_JSON},
{
""[{test: 'test'}]"",
""[{\""test\"":\""test\""}]""
}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidJSON(source, RUBBISH_JSON);
if (!result.equals(expected)) {
fail(""Validating JSON '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
"," public void testGetValidJSON() {
String[][] testData = {
{null, RUBBISH_JSON},
{"""", """"},
{""1]"", RUBBISH_JSON},
{""{}"", ""{}""},
{""{1}"", RUBBISH_JSON},
{
""{test: 'test'}"",
""{\""test\"":\""test\""}""
},
{
""{test:\""test}"",
RUBBISH_JSON
},
{
""{test1:'test1', test2: {test21: 'test21', test22: 'test22'}}"",
""{\""test1\"":\""test1\"",\""test2\"":{\""test21\"":\""test21\"",\""test22\"":\""test22\""}}""
},
{""[]"", ""[]""},
{""[1,2]"", ""[1,2]""},
{""[1"", RUBBISH_JSON},
{
""[{test: 'test'}]"",
""[{\""test\"":\""test\""}]""
}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidJSON(source, RUBBISH_JSON);
if (!result.equals(expected)) {
fail(""Validating JSON '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
",FALSE,XSSAPIImplTest.java
" public void testGetValidXML() {
String[][] testData = {
{null, RUBBISH_XML},
{"""", """"},
{
"" "",
"" ""
},
{
"""",
RUBBISH_XML
},
{
""test "",
""test ""
},
{
""test"",
RUBBISH_XML
},
{
""test "",
""test ""
},
{
""test "",
RUBBISH_XML
},
{
""xyz "",
""xyz ""
},
{
""xyz "",
RUBBISH_XML
}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidXML(source, RUBBISH_XML);
if (!result.equals(expected)) {
fail(""Validating XML '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
"," public void testGetValidXML() {
String[][] testData = {
{null, RUBBISH_XML},
{"""", """"},
{
"" "",
"" ""
},
{
"""",
RUBBISH_XML
},
{
""test "",
""test ""
},
{
""test"",
RUBBISH_XML
},
{
""test "",
""test ""
},
{
""test "",
RUBBISH_XML
},
{
""xyz "",
""xyz ""
},
{
""xyz "",
RUBBISH_XML
},
{
"" "",
"" ""
}
};
for (String[] aTestData : testData) {
String source = aTestData[0];
String expected = aTestData[1];
String result = xssAPI.getValidXML(source, RUBBISH_XML);
if (!result.equals(expected)) {
fail(""Validating XML '"" + source + ""', expecting '"" + expected + ""', but got '"" + result + ""'"");
}
}
}
",TRUE,XSSAPIImplTest.java
" private static byte[] toUtf8Bytes(String str)
{
try
{
return str.getBytes(""UTF-8"");
}
catch(UnsupportedEncodingException e)
{
throw new IllegalStateException(""The Java spec requires UTF-8 support."", e);
}
}
"," private static byte[] toUtf8Bytes(String str)
{
try
{
return str.getBytes(""UTF-8"");
}
catch(UnsupportedEncodingException e)
{
throw new IllegalStateException(""The Java spec requires UTF-8 support."", e);
}
}
",FALSE,PercentCodec.java
" private static StringBuilder appendTwoUpperHex(StringBuilder sb, int b)
{
if(b < Byte.MIN_VALUE || b > Byte.MAX_VALUE)
throw new IllegalArgumentException(""b is not a byte (was "" + b + ')');
b &= 0xFF;
if(b<0x10)
sb.append('0');
return sb.append(Integer.toHexString(b).toUpperCase());
}
"," private static StringBuilder appendTwoUpperHex(StringBuilder sb, int b)
{
if(b < Byte.MIN_VALUE || b > Byte.MAX_VALUE)
throw new IllegalArgumentException(""b is not a byte (was "" + b + ')');
b &= 0xFF;
if(b<0x10)
sb.append('0');
return sb.append(Integer.toHexString(b).toUpperCase());
}
",FALSE,PercentCodec.java
" public String encodeCharacter( char[] immune, Character c )
{
String cStr = String.valueOf(c.charValue());
byte[] bytes;
StringBuilder sb;
if(UNENCODED_SET.contains(c))
return cStr;
bytes = toUtf8Bytes(cStr);
sb = new StringBuilder(bytes.length * 3);
for(byte b : bytes)
appendTwoUpperHex(sb.append('%'), b);
return sb.toString();
}
"," public String encodeCharacter( char[] immune, Character c )
{
String cStr = String.valueOf(c.charValue());
byte[] bytes;
StringBuilder sb;
// check for user specified immune characters
if ( immune != null && containsCharacter( c.charValue(), immune ) )
return cStr;
// check for standard characters (e.g., alphanumeric, etc.)
if(UNENCODED_SET.contains(c))
return cStr;
bytes = toUtf8Bytes(cStr);
sb = new StringBuilder(bytes.length * 3);
for(byte b : bytes)
appendTwoUpperHex(sb.append('%'), b);
return sb.toString();
}
",TRUE,PercentCodec.java
" public Character decodeCharacter( PushbackString input ) {
input.mark();
Character first = input.next();
if ( first == null ) {
input.reset();
return null;
}
// if this is not an encoded character, return null
if (first != '%' ) {
input.reset();
return null;
}
// Search for exactly 2 hex digits following
StringBuilder sb = new StringBuilder();
for ( int i=0; i<2; i++ ) {
Character c = input.nextHex();
if ( c != null ) sb.append( c );
}
if ( sb.length() == 2 ) {
try {
// parse the hex digit and create a character
int i = Integer.parseInt(sb.toString(), 16);
if (Character.isValidCodePoint(i)) {
return (char) i;
}
} catch( NumberFormatException ignored ) { }
}
input.reset();
return null;
}
"," public Character decodeCharacter( PushbackString input ) {
input.mark();
Character first = input.next();
if ( first == null ) {
input.reset();
return null;
}
// if this is not an encoded character, return null
if (first != '%' ) {
input.reset();
return null;
}
// Search for exactly 2 hex digits following
StringBuilder sb = new StringBuilder();
for ( int i=0; i<2; i++ ) {
Character c = input.nextHex();
if ( c != null ) sb.append( c );
}
if ( sb.length() == 2 ) {
try {
// parse the hex digit and create a character
int i = Integer.parseInt(sb.toString(), 16);
if (Character.isValidCodePoint(i)) {
return (char) i;
}
} catch( NumberFormatException ignored ) { }
}
input.reset();
return null;
}
",FALSE,PercentCodec.java
" NioZipEncoding(final Charset charset, boolean useReplacement) {
this.charset = charset;
this.useReplacement = useReplacement;
}
"," NioZipEncoding(final Charset charset, boolean useReplacement) {
this.charset = charset;
this.useReplacement = useReplacement;
}
",FALSE,NioZipEncoding.java
" public Charset getCharset() {
return charset;
}
"," public Charset getCharset() {
return charset;
}
",FALSE,NioZipEncoding.java
" public boolean canEncode(final String name) {
final CharsetEncoder enc = newEncoder();
return enc.canEncode(name);
}
"," public boolean canEncode(final String name) {
final CharsetEncoder enc = newEncoder();
return enc.canEncode(name);
}
",FALSE,NioZipEncoding.java
" public ByteBuffer encode(final String name) {
final CharsetEncoder enc = newEncoder();
final CharBuffer cb = CharBuffer.wrap(name);
CharBuffer tmp = null;
ByteBuffer out = ByteBuffer.allocate(estimateInitialBufferSize(enc, cb.remaining()));
while (cb.remaining() > 0) {
final CoderResult res = enc.encode(cb, out, false);
if (res.isUnmappable() || res.isMalformed()) {
// write the unmappable characters in utf-16
// pseudo-URL encoding style to ByteBuffer.
int spaceForSurrogate = estimateIncrementalEncodingSize(enc, 6 * res.length());
if (spaceForSurrogate > out.remaining()) {
// if the destination buffer isn't over sized, assume that the presence of one
// unmappable character makes it likely that there will be more. Find all the
// un-encoded characters and allocate space based on those estimates.
int charCount = 0;
for (int i = cb.position() ; i < cb.limit(); i++) {
charCount += !enc.canEncode(cb.get(i)) ? 6 : 1;
}
int totalExtraSpace = estimateIncrementalEncodingSize(enc, charCount);
out = ZipEncodingHelper.growBufferBy(out, totalExtraSpace - out.remaining());
}
if (tmp == null) {
tmp = CharBuffer.allocate(6);
}
for (int i = 0; i < res.length(); ++i) {
out = encodeFully(enc, encodeSurrogate(tmp, cb.get()), out);
}
} else if (res.isOverflow()) {
int increment = estimateIncrementalEncodingSize(enc, cb.remaining());
out = ZipEncodingHelper.growBufferBy(out, increment);
}
}
// tell the encoder we are done
enc.encode(cb, out, true);
// may have caused underflow, but that's been ignored traditionally
out.limit(out.position());
out.rewind();
return out;
}
"," public ByteBuffer encode(final String name) {
final CharsetEncoder enc = newEncoder();
final CharBuffer cb = CharBuffer.wrap(name);
CharBuffer tmp = null;
ByteBuffer out = ByteBuffer.allocate(estimateInitialBufferSize(enc, cb.remaining()));
while (cb.remaining() > 0) {
final CoderResult res = enc.encode(cb, out, false);
if (res.isUnmappable() || res.isMalformed()) {
// write the unmappable characters in utf-16
// pseudo-URL encoding style to ByteBuffer.
int spaceForSurrogate = estimateIncrementalEncodingSize(enc, 6 * res.length());
if (spaceForSurrogate > out.remaining()) {
// if the destination buffer isn't over sized, assume that the presence of one
// unmappable character makes it likely that there will be more. Find all the
// un-encoded characters and allocate space based on those estimates.
int charCount = 0;
for (int i = cb.position() ; i < cb.limit(); i++) {
charCount += !enc.canEncode(cb.get(i)) ? 6 : 1;
}
int totalExtraSpace = estimateIncrementalEncodingSize(enc, charCount);
out = ZipEncodingHelper.growBufferBy(out, totalExtraSpace - out.remaining());
}
if (tmp == null) {
tmp = CharBuffer.allocate(6);
}
for (int i = 0; i < res.length(); ++i) {
out = encodeFully(enc, encodeSurrogate(tmp, cb.get()), out);
}
} else if (res.isOverflow()) {
int increment = estimateIncrementalEncodingSize(enc, cb.remaining());
out = ZipEncodingHelper.growBufferBy(out, increment);
} else if (res.isUnderflow() || res.isError()) {
break;
}
}
// tell the encoder we are done
enc.encode(cb, out, true);
// may have caused underflow, but that's been ignored traditionally
out.limit(out.position());
out.rewind();
return out;
}
",TRUE,NioZipEncoding.java
" public String decode(final byte[] data) throws IOException {
return newDecoder()
.decode(ByteBuffer.wrap(data)).toString();
}
"," public String decode(final byte[] data) throws IOException {
return newDecoder()
.decode(ByteBuffer.wrap(data)).toString();
}
",FALSE,NioZipEncoding.java
" private static ByteBuffer encodeFully(CharsetEncoder enc, CharBuffer cb, ByteBuffer out) {
ByteBuffer o = out;
while (cb.hasRemaining()) {
CoderResult result = enc.encode(cb, o, false);
if (result.isOverflow()) {
int increment = estimateIncrementalEncodingSize(enc, cb.remaining());
o = ZipEncodingHelper.growBufferBy(o, increment);
}
}
return o;
}
"," private static ByteBuffer encodeFully(CharsetEncoder enc, CharBuffer cb, ByteBuffer out) {
ByteBuffer o = out;
while (cb.hasRemaining()) {
CoderResult result = enc.encode(cb, o, false);
if (result.isOverflow()) {
int increment = estimateIncrementalEncodingSize(enc, cb.remaining());
o = ZipEncodingHelper.growBufferBy(o, increment);
}
}
return o;
}
",FALSE,NioZipEncoding.java
" private static CharBuffer encodeSurrogate(CharBuffer cb, char c) {
cb.position(0).limit(6);
cb.put('%');
cb.put('U');
cb.put(HEX_CHARS[(c >> 12) & 0x0f]);
cb.put(HEX_CHARS[(c >> 8) & 0x0f]);
cb.put(HEX_CHARS[(c >> 4) & 0x0f]);
cb.put(HEX_CHARS[c & 0x0f]);
cb.flip();
return cb;
}
"," private static CharBuffer encodeSurrogate(CharBuffer cb, char c) {
cb.position(0).limit(6);
cb.put('%');
cb.put('U');
cb.put(HEX_CHARS[(c >> 12) & 0x0f]);
cb.put(HEX_CHARS[(c >> 8) & 0x0f]);
cb.put(HEX_CHARS[(c >> 4) & 0x0f]);
cb.put(HEX_CHARS[c & 0x0f]);
cb.flip();
return cb;
}
",FALSE,NioZipEncoding.java
" private CharsetEncoder newEncoder() {
if (useReplacement) {
return charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith(REPLACEMENT_BYTES);
} else {
return charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
}
}
"," private CharsetEncoder newEncoder() {
if (useReplacement) {
return charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith(REPLACEMENT_BYTES);
} else {
return charset.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
}
}
",FALSE,NioZipEncoding.java
" private CharsetDecoder newDecoder() {
if (!useReplacement) {
return this.charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
} else {
return charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith(REPLACEMENT_STRING);
}
}
"," private CharsetDecoder newDecoder() {
if (!useReplacement) {
return this.charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
} else {
return charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.replaceWith(REPLACEMENT_STRING);
}
}
",FALSE,NioZipEncoding.java
" private static int estimateInitialBufferSize(CharsetEncoder enc, int charChount) {
float first = enc.maxBytesPerChar();
float rest = (charChount - 1) * enc.averageBytesPerChar();
return (int) Math.ceil(first + rest);
}
"," private static int estimateInitialBufferSize(CharsetEncoder enc, int charChount) {
float first = enc.maxBytesPerChar();
float rest = (charChount - 1) * enc.averageBytesPerChar();
return (int) Math.ceil(first + rest);
}
",FALSE,NioZipEncoding.java
" private static int estimateIncrementalEncodingSize(CharsetEncoder enc, int charCount) {
return (int) Math.ceil(charCount * enc.averageBytesPerChar());
}
"," private static int estimateIncrementalEncodingSize(CharsetEncoder enc, int charCount) {
return (int) Math.ceil(charCount * enc.averageBytesPerChar());
}
",FALSE,NioZipEncoding.java
" public YAMLConfiguration()
{
super();
}
"," public YAMLConfiguration()
{
super();
}
",FALSE,YAMLConfiguration.java
" public YAMLConfiguration(final HierarchicalConfiguration c)
{
super(c);
}
"," public YAMLConfiguration(final HierarchicalConfiguration c)
{
super(c);
}
",FALSE,YAMLConfiguration.java
" public void read(final Reader in) throws ConfigurationException
{
try
{
final Yaml yaml = new Yaml();
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
"," public void read(final Reader in) throws ConfigurationException
{
try
{
final Yaml yaml = createYamlForReading(new LoaderOptions());
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
",TRUE,YAMLConfiguration.java
" public void read(final Reader in, final LoaderOptions options)
throws ConfigurationException
{
try
{
final Yaml yaml = new Yaml(options);
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
"," public void read(final Reader in, final LoaderOptions options)
throws ConfigurationException
{
try
{
final Yaml yaml = createYamlForReading(options);
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
",TRUE,YAMLConfiguration.java
" public void write(final Writer out) throws ConfigurationException, IOException
{
final DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
dump(out, options);
}
"," public void write(final Writer out) throws ConfigurationException, IOException
{
final DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
dump(out, options);
}
",FALSE,YAMLConfiguration.java
" public void dump(final Writer out, final DumperOptions options)
throws ConfigurationException, IOException
{
final Yaml yaml = new Yaml(options);
yaml.dump(constructMap(getNodeModel().getNodeHandler().getRootNode()),
out);
}
"," public void dump(final Writer out, final DumperOptions options)
throws ConfigurationException, IOException
{
final Yaml yaml = new Yaml(options);
yaml.dump(constructMap(getNodeModel().getNodeHandler().getRootNode()),
out);
}
",FALSE,YAMLConfiguration.java
" public void read(final InputStream in) throws ConfigurationException
{
try
{
final Yaml yaml = new Yaml();
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
"," public void read(final InputStream in) throws ConfigurationException
{
try
{
final Yaml yaml = createYamlForReading(new LoaderOptions());
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
",TRUE,YAMLConfiguration.java
" public void read(final InputStream in, final LoaderOptions options)
throws ConfigurationException
{
try
{
final Yaml yaml = new Yaml(options);
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
"," public void read(final InputStream in, final LoaderOptions options)
throws ConfigurationException
{
try
{
final Yaml yaml = createYamlForReading(options);
final Map map = (Map) yaml.load(in);
load(map);
}
catch (final Exception e)
{
rethrowException(e);
}
}
",TRUE,YAMLConfiguration.java
"
"," private static Yaml createYamlForReading(LoaderOptions options)
{
return new Yaml(createClassLoadingDisablingConstructor(), new Representer(), new DumperOptions(), options);
}
",TRUE,YAMLConfiguration.java
"
"," private static Constructor createClassLoadingDisablingConstructor()
{
return new Constructor()
{
@Override
protected Class> getClassForName(String name)
{
throw new ConfigurationRuntimeException(""Class loading is disabled."");
}
};
}
",TRUE,YAMLConfiguration.java
" public void setUp() throws Exception
{
yamlConfiguration = new YAMLConfiguration();
yamlConfiguration.read(new FileReader(testYaml));
}
"," public void setUp() throws Exception
{
yamlConfiguration = new YAMLConfiguration();
yamlConfiguration.read(new FileReader(testYaml));
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_simple()
{
assertEquals(""value1"", yamlConfiguration.getProperty(""key1""));
}
"," public void testGetProperty_simple()
{
assertEquals(""value1"", yamlConfiguration.getProperty(""key1""));
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_nested()
{
assertEquals(""value23"", yamlConfiguration.getProperty(""key2.key3""));
}
"," public void testGetProperty_nested()
{
assertEquals(""value23"", yamlConfiguration.getProperty(""key2.key3""));
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_nested_with_list()
{
assertEquals(Arrays.asList(""col1"", ""col2""),
yamlConfiguration.getProperty(""key4.key5""));
}
"," public void testGetProperty_nested_with_list()
{
assertEquals(Arrays.asList(""col1"", ""col2""),
yamlConfiguration.getProperty(""key4.key5""));
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_subset()
{
final Configuration subset = yamlConfiguration.subset(""key4"");
assertEquals(Arrays.asList(""col1"", ""col2""), subset.getProperty(""key5""));
}
"," public void testGetProperty_subset()
{
final Configuration subset = yamlConfiguration.subset(""key4"");
assertEquals(Arrays.asList(""col1"", ""col2""), subset.getProperty(""key5""));
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_very_nested_properties()
{
final Object property =
yamlConfiguration.getProperty(""very.nested.properties"");
assertEquals(Arrays.asList(""nested1"", ""nested2"", ""nested3""), property);
}
"," public void testGetProperty_very_nested_properties()
{
final Object property =
yamlConfiguration.getProperty(""very.nested.properties"");
assertEquals(Arrays.asList(""nested1"", ""nested2"", ""nested3""), property);
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_integer()
{
final Object property = yamlConfiguration.getProperty(""int1"");
assertTrue(""property should be an Integer"",
property instanceof Integer);
assertEquals(37, property);
}
"," public void testGetProperty_integer()
{
final Object property = yamlConfiguration.getProperty(""int1"");
assertTrue(""property should be an Integer"",
property instanceof Integer);
assertEquals(37, property);
}
",FALSE,TestYAMLConfiguration.java
" public void testSave() throws IOException, ConfigurationException
{
// save the YAMLConfiguration as a String...
final StringWriter sw = new StringWriter();
yamlConfiguration.write(sw);
final String output = sw.toString();
// ..and then try parsing it back as using SnakeYAML
final Map parsed = new Yaml().loadAs(output, Map.class);
assertEquals(6, parsed.entrySet().size());
assertEquals(""value1"", parsed.get(""key1""));
final Map key2 = (Map) parsed.get(""key2"");
assertEquals(""value23"", key2.get(""key3""));
final List key5 =
(List) ((Map) parsed.get(""key4"")).get(""key5"");
assertEquals(2, key5.size());
assertEquals(""col1"", key5.get(0));
assertEquals(""col2"", key5.get(1));
}
"," public void testSave() throws IOException, ConfigurationException
{
// save the YAMLConfiguration as a String...
final StringWriter sw = new StringWriter();
yamlConfiguration.write(sw);
final String output = sw.toString();
// ..and then try parsing it back as using SnakeYAML
final Map parsed = new Yaml().loadAs(output, Map.class);
assertEquals(6, parsed.entrySet().size());
assertEquals(""value1"", parsed.get(""key1""));
final Map key2 = (Map) parsed.get(""key2"");
assertEquals(""value23"", key2.get(""key3""));
final List key5 =
(List) ((Map) parsed.get(""key4"")).get(""key5"");
assertEquals(2, key5.size());
assertEquals(""col1"", key5.get(0));
assertEquals(""col2"", key5.get(1));
}
",FALSE,TestYAMLConfiguration.java
" public void testGetProperty_dictionary()
{
assertEquals(""Martin D'vloper"",
yamlConfiguration.getProperty(""martin.name""));
assertEquals(""Developer"", yamlConfiguration.getProperty(""martin.job""));
assertEquals(""Elite"", yamlConfiguration.getProperty(""martin.skill""));
}
"," public void testGetProperty_dictionary()
{
assertEquals(""Martin D'vloper"",
yamlConfiguration.getProperty(""martin.name""));
assertEquals(""Developer"", yamlConfiguration.getProperty(""martin.job""));
assertEquals(""Elite"", yamlConfiguration.getProperty(""martin.skill""));
}
",FALSE,TestYAMLConfiguration.java
" public void testCopyConstructor()
{
final BaseHierarchicalConfiguration c = new BaseHierarchicalConfiguration();
c.addProperty(""foo"", ""bar"");
yamlConfiguration = new YAMLConfiguration(c);
assertEquals(""bar"", yamlConfiguration.getString(""foo""));
}
"," public void testCopyConstructor()
{
final BaseHierarchicalConfiguration c = new BaseHierarchicalConfiguration();
c.addProperty(""foo"", ""bar"");
yamlConfiguration = new YAMLConfiguration(c);
assertEquals(""bar"", yamlConfiguration.getString(""foo""));
}
",FALSE,TestYAMLConfiguration.java
" }
"," public void testObjectCreationFromReader()
{
final File createdFile = new File(temporaryFolder.getRoot(), ""data.txt"");
final String yaml = ""!!java.io.FileOutputStream ["" + createdFile.getAbsolutePath() + ""]"";
try
{
yamlConfiguration.read(new StringReader(yaml));
fail(""Loading configuration did not cause an exception!"");
}
catch (ConfigurationException e)
{
//expected
}
assertFalse(""Java object was created"", createdFile.exists());
}
",TRUE,TestYAMLConfiguration.java
" }
"," public void testObjectCreationFromStream()
{
final File createdFile = new File(temporaryFolder.getRoot(), ""data.txt"");
final String yaml = ""!!java.io.FileOutputStream ["" + createdFile.getAbsolutePath() + ""]"";
try
{
yamlConfiguration.read(new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)));
fail(""Loading configuration did not cause an exception!"");
}
catch (ConfigurationException e)
{
//expected
}
assertFalse(""Java object was created"", createdFile.exists());
}
",TRUE,TestYAMLConfiguration.java
" public void setEnforceAssertionsSigned(boolean enforceAssertionsSigned) {
this.enforceAssertionsSigned = enforceAssertionsSigned;
}
"," public void setEnforceAssertionsSigned(boolean enforceAssertionsSigned) {
this.enforceAssertionsSigned = enforceAssertionsSigned;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setEnforceKnownIssuer(boolean enforceKnownIssuer) {
this.enforceKnownIssuer = enforceKnownIssuer;
}
"," public void setEnforceKnownIssuer(boolean enforceKnownIssuer) {
this.enforceKnownIssuer = enforceKnownIssuer;
}
",FALSE,SAMLSSOResponseValidator.java
" public SSOValidatorResponse validateSamlResponse(
org.opensaml.saml.saml2.core.Response samlResponse,
boolean postBinding
) throws WSSecurityException {
// Check the Issuer
validateIssuer(samlResponse.getIssuer());
// The Response must contain at least one Assertion.
if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) {
LOG.fine(""The Response must contain at least one Assertion"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// The Response must contain a Destination that matches the assertionConsumerURL if it is
// signed
String destination = samlResponse.getDestination();
if (samlResponse.isSigned()
&& (destination == null || !destination.equals(assertionConsumerURL))) {
LOG.fine(""The Response must contain a destination that matches the assertion consumer URL"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Validate Assertions
boolean foundValidSubject = false;
Date sessionNotOnOrAfter = null;
for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
// Check the Issuer
if (assertion.getIssuer() == null) {
LOG.fine(""Assertion Issuer must not be null"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
validateIssuer(assertion.getIssuer());
if (enforceAssertionsSigned && postBinding && assertion.getSignature() == null) {
LOG.fine(""If the HTTP Post binding is used to deliver the Response, ""
+ ""the enclosed assertions must be signed"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Check for AuthnStatements and validate the Subject accordingly
if (assertion.getAuthnStatements() != null
&& !assertion.getAuthnStatements().isEmpty()) {
org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject();
if (validateAuthenticationSubject(subject, assertion.getID(), postBinding)) {
validateAudienceRestrictionCondition(assertion.getConditions());
foundValidSubject = true;
// Store Session NotOnOrAfter
for (AuthnStatement authnStatment : assertion.getAuthnStatements()) {
if (authnStatment.getSessionNotOnOrAfter() != null) {
sessionNotOnOrAfter = authnStatment.getSessionNotOnOrAfter().toDate();
}
}
}
}
}
if (!foundValidSubject) {
LOG.fine(""The Response did not contain any Authentication Statement that matched ""
+ ""the Subject Confirmation criteria"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
SSOValidatorResponse validatorResponse = new SSOValidatorResponse();
validatorResponse.setResponseId(samlResponse.getID());
validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter);
if (samlResponse.getIssueInstant() != null) {
validatorResponse.setCreated(samlResponse.getIssueInstant().toDate());
}
// the assumption for now is that SAMLResponse will contain only a single assertion
Element assertionElement = samlResponse.getAssertions().get(0).getDOM();
Element clonedAssertionElement = (Element)assertionElement.cloneNode(true);
validatorResponse.setAssertionElement(clonedAssertionElement);
validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement));
return validatorResponse;
}
"," public SSOValidatorResponse validateSamlResponse(
org.opensaml.saml.saml2.core.Response samlResponse,
boolean postBinding
) throws WSSecurityException {
// Check the Issuer
validateIssuer(samlResponse.getIssuer());
// The Response must contain at least one Assertion.
if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) {
LOG.fine(""The Response must contain at least one Assertion"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// The Response must contain a Destination that matches the assertionConsumerURL if it is
// signed
String destination = samlResponse.getDestination();
if (samlResponse.isSigned()
&& (destination == null || !destination.equals(assertionConsumerURL))) {
LOG.fine(""The Response must contain a destination that matches the assertion consumer URL"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Validate Assertions
org.opensaml.saml.saml2.core.Assertion validAssertion = null;
Date sessionNotOnOrAfter = null;
for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
// Check the Issuer
if (assertion.getIssuer() == null) {
LOG.fine(""Assertion Issuer must not be null"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
validateIssuer(assertion.getIssuer());
if (enforceAssertionsSigned && postBinding && assertion.getSignature() == null) {
LOG.fine(""If the HTTP Post binding is used to deliver the Response, ""
+ ""the enclosed assertions must be signed"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Check for AuthnStatements and validate the Subject accordingly
if (assertion.getAuthnStatements() != null
&& !assertion.getAuthnStatements().isEmpty()) {
org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject();
if (validateAuthenticationSubject(subject, assertion.getID(), postBinding)) {
validateAudienceRestrictionCondition(assertion.getConditions());
validAssertion = assertion;
// Store Session NotOnOrAfter
for (AuthnStatement authnStatment : assertion.getAuthnStatements()) {
if (authnStatment.getSessionNotOnOrAfter() != null) {
sessionNotOnOrAfter = authnStatment.getSessionNotOnOrAfter().toDate();
}
}
}
}
}
if (validAssertion == null) {
LOG.fine(""The Response did not contain any Authentication Statement that matched ""
+ ""the Subject Confirmation criteria"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
SSOValidatorResponse validatorResponse = new SSOValidatorResponse();
validatorResponse.setResponseId(samlResponse.getID());
validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter);
if (samlResponse.getIssueInstant() != null) {
validatorResponse.setCreated(samlResponse.getIssueInstant().toDate());
}
// the assumption for now is that SAMLResponse will contain only a single assertion
Element assertionElement = validAssertion.getDOM();
Element clonedAssertionElement = (Element)assertionElement.cloneNode(true);
validatorResponse.setAssertionElement(clonedAssertionElement);
validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement));
return validatorResponse;
}
",TRUE,SAMLSSOResponseValidator.java
" private void validateIssuer(org.opensaml.saml.saml2.core.Issuer issuer) throws WSSecurityException {
if (issuer == null) {
return;
}
// Issuer value must match (be contained in) Issuer IDP
if (enforceKnownIssuer && !issuerIDP.startsWith(issuer.getValue())) {
LOG.fine(""Issuer value: "" + issuer.getValue() + "" does not match issuer IDP: ""
+ issuerIDP);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Format must be nameid-format-entity
if (issuer.getFormat() != null
&& !SAML2Constants.NAMEID_FORMAT_ENTITY.equals(issuer.getFormat())) {
LOG.fine(""Issuer format is not null and does not equal: ""
+ SAML2Constants.NAMEID_FORMAT_ENTITY);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
"," private void validateIssuer(org.opensaml.saml.saml2.core.Issuer issuer) throws WSSecurityException {
if (issuer == null) {
return;
}
// Issuer value must match (be contained in) Issuer IDP
if (enforceKnownIssuer && !issuerIDP.startsWith(issuer.getValue())) {
LOG.fine(""Issuer value: "" + issuer.getValue() + "" does not match issuer IDP: ""
+ issuerIDP);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Format must be nameid-format-entity
if (issuer.getFormat() != null
&& !SAML2Constants.NAMEID_FORMAT_ENTITY.equals(issuer.getFormat())) {
LOG.fine(""Issuer format is not null and does not equal: ""
+ SAML2Constants.NAMEID_FORMAT_ENTITY);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
",FALSE,SAMLSSOResponseValidator.java
" private boolean validateAuthenticationSubject(
org.opensaml.saml.saml2.core.Subject subject, String id, boolean postBinding
) throws WSSecurityException {
if (subject.getSubjectConfirmations() == null) {
return false;
}
boolean foundBearerSubjectConf = false;
// We need to find a Bearer Subject Confirmation method
for (org.opensaml.saml.saml2.core.SubjectConfirmation subjectConf
: subject.getSubjectConfirmations()) {
if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
foundBearerSubjectConf = true;
validateSubjectConfirmation(subjectConf.getSubjectConfirmationData(), id, postBinding);
}
}
return foundBearerSubjectConf;
}
"," private boolean validateAuthenticationSubject(
org.opensaml.saml.saml2.core.Subject subject, String id, boolean postBinding
) throws WSSecurityException {
if (subject.getSubjectConfirmations() == null) {
return false;
}
boolean foundBearerSubjectConf = false;
// We need to find a Bearer Subject Confirmation method
for (org.opensaml.saml.saml2.core.SubjectConfirmation subjectConf
: subject.getSubjectConfirmations()) {
if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
foundBearerSubjectConf = true;
validateSubjectConfirmation(subjectConf.getSubjectConfirmationData(), id, postBinding);
}
}
return foundBearerSubjectConf;
}
",FALSE,SAMLSSOResponseValidator.java
" private void validateSubjectConfirmation(
org.opensaml.saml.saml2.core.SubjectConfirmationData subjectConfData, String id, boolean postBinding
) throws WSSecurityException {
if (subjectConfData == null) {
LOG.fine(""Subject Confirmation Data of a Bearer Subject Confirmation is null"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Recipient must match assertion consumer URL
String recipient = subjectConfData.getRecipient();
if (recipient == null || !recipient.equals(assertionConsumerURL)) {
LOG.fine(""Recipient "" + recipient + "" does not match assertion consumer URL ""
+ assertionConsumerURL);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// We must have a NotOnOrAfter timestamp
if (subjectConfData.getNotOnOrAfter() == null
|| subjectConfData.getNotOnOrAfter().isBeforeNow()) {
LOG.fine(""Subject Conf Data does not contain NotOnOrAfter or it has expired"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Need to keep bearer assertion IDs based on NotOnOrAfter to detect replay attacks
if (postBinding && replayCache != null) {
if (replayCache.getId(id) == null) {
Date expires = subjectConfData.getNotOnOrAfter().toDate();
Date currentTime = new Date();
long ttl = expires.getTime() - currentTime.getTime();
replayCache.putId(id, ttl / 1000L);
} else {
LOG.fine(""Replay attack with token id: "" + id);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
// Check address
if (subjectConfData.getAddress() != null
&& !subjectConfData.getAddress().equals(clientAddress)) {
LOG.fine(""Subject Conf Data address "" + subjectConfData.getAddress() + "" does match""
+ "" client address "" + clientAddress);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// It must not contain a NotBefore timestamp
if (subjectConfData.getNotBefore() != null) {
LOG.fine(""The Subject Conf Data must not contain a NotBefore timestamp"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// InResponseTo must match the AuthnRequest request Id
if (requestId != null && !requestId.equals(subjectConfData.getInResponseTo())) {
LOG.fine(""The InResponseTo String does match the original request id "" + requestId);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
"," private void validateSubjectConfirmation(
org.opensaml.saml.saml2.core.SubjectConfirmationData subjectConfData, String id, boolean postBinding
) throws WSSecurityException {
if (subjectConfData == null) {
LOG.fine(""Subject Confirmation Data of a Bearer Subject Confirmation is null"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Recipient must match assertion consumer URL
String recipient = subjectConfData.getRecipient();
if (recipient == null || !recipient.equals(assertionConsumerURL)) {
LOG.fine(""Recipient "" + recipient + "" does not match assertion consumer URL ""
+ assertionConsumerURL);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// We must have a NotOnOrAfter timestamp
if (subjectConfData.getNotOnOrAfter() == null
|| subjectConfData.getNotOnOrAfter().isBeforeNow()) {
LOG.fine(""Subject Conf Data does not contain NotOnOrAfter or it has expired"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// Need to keep bearer assertion IDs based on NotOnOrAfter to detect replay attacks
if (postBinding && replayCache != null) {
if (replayCache.getId(id) == null) {
Date expires = subjectConfData.getNotOnOrAfter().toDate();
Date currentTime = new Date();
long ttl = expires.getTime() - currentTime.getTime();
replayCache.putId(id, ttl / 1000L);
} else {
LOG.fine(""Replay attack with token id: "" + id);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
// Check address
if (subjectConfData.getAddress() != null
&& !subjectConfData.getAddress().equals(clientAddress)) {
LOG.fine(""Subject Conf Data address "" + subjectConfData.getAddress() + "" does match""
+ "" client address "" + clientAddress);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// It must not contain a NotBefore timestamp
if (subjectConfData.getNotBefore() != null) {
LOG.fine(""The Subject Conf Data must not contain a NotBefore timestamp"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
// InResponseTo must match the AuthnRequest request Id
if (requestId != null && !requestId.equals(subjectConfData.getInResponseTo())) {
LOG.fine(""The InResponseTo String does match the original request id "" + requestId);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
",FALSE,SAMLSSOResponseValidator.java
" private void validateAudienceRestrictionCondition(
org.opensaml.saml.saml2.core.Conditions conditions
) throws WSSecurityException {
if (conditions == null) {
LOG.fine(""Conditions are null"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
List audienceRestrs = conditions.getAudienceRestrictions();
if (!matchSaml2AudienceRestriction(spIdentifier, audienceRestrs)) {
LOG.fine(""Assertion does not contain unique subject provider identifier ""
+ spIdentifier + "" in the audience restriction conditions"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
"," private void validateAudienceRestrictionCondition(
org.opensaml.saml.saml2.core.Conditions conditions
) throws WSSecurityException {
if (conditions == null) {
LOG.fine(""Conditions are null"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
List audienceRestrs = conditions.getAudienceRestrictions();
if (!matchSaml2AudienceRestriction(spIdentifier, audienceRestrs)) {
LOG.fine(""Assertion does not contain unique subject provider identifier ""
+ spIdentifier + "" in the audience restriction conditions"");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ""invalidSAMLsecurity"");
}
}
",FALSE,SAMLSSOResponseValidator.java
" private boolean matchSaml2AudienceRestriction(
String appliesTo, List audienceRestrictions
) {
boolean oneMatchFound = false;
if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
for (AudienceRestriction audienceRestriction : audienceRestrictions) {
if (audienceRestriction.getAudiences() != null) {
boolean matchFound = false;
for (org.opensaml.saml.saml2.core.Audience audience : audienceRestriction.getAudiences()) {
if (appliesTo.equals(audience.getAudienceURI())) {
matchFound = true;
oneMatchFound = true;
break;
}
}
if (!matchFound) {
return false;
}
}
}
}
return oneMatchFound;
}
"," private boolean matchSaml2AudienceRestriction(
String appliesTo, List audienceRestrictions
) {
boolean oneMatchFound = false;
if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
for (AudienceRestriction audienceRestriction : audienceRestrictions) {
if (audienceRestriction.getAudiences() != null) {
boolean matchFound = false;
for (org.opensaml.saml.saml2.core.Audience audience : audienceRestriction.getAudiences()) {
if (appliesTo.equals(audience.getAudienceURI())) {
matchFound = true;
oneMatchFound = true;
break;
}
}
if (!matchFound) {
return false;
}
}
}
}
return oneMatchFound;
}
",FALSE,SAMLSSOResponseValidator.java
" public String getIssuerIDP() {
return issuerIDP;
}
"," public String getIssuerIDP() {
return issuerIDP;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setIssuerIDP(String issuerIDP) {
this.issuerIDP = issuerIDP;
}
"," public void setIssuerIDP(String issuerIDP) {
this.issuerIDP = issuerIDP;
}
",FALSE,SAMLSSOResponseValidator.java
" public String getAssertionConsumerURL() {
return assertionConsumerURL;
}
"," public String getAssertionConsumerURL() {
return assertionConsumerURL;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setAssertionConsumerURL(String assertionConsumerURL) {
this.assertionConsumerURL = assertionConsumerURL;
}
"," public void setAssertionConsumerURL(String assertionConsumerURL) {
this.assertionConsumerURL = assertionConsumerURL;
}
",FALSE,SAMLSSOResponseValidator.java
" public String getClientAddress() {
return clientAddress;
}
"," public String getClientAddress() {
return clientAddress;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setClientAddress(String clientAddress) {
this.clientAddress = clientAddress;
}
"," public void setClientAddress(String clientAddress) {
this.clientAddress = clientAddress;
}
",FALSE,SAMLSSOResponseValidator.java
" public String getRequestId() {
return requestId;
}
"," public String getRequestId() {
return requestId;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setRequestId(String requestId) {
this.requestId = requestId;
}
"," public void setRequestId(String requestId) {
this.requestId = requestId;
}
",FALSE,SAMLSSOResponseValidator.java
" public String getSpIdentifier() {
return spIdentifier;
}
"," public String getSpIdentifier() {
return spIdentifier;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setSpIdentifier(String spIdentifier) {
this.spIdentifier = spIdentifier;
}
"," public void setSpIdentifier(String spIdentifier) {
this.spIdentifier = spIdentifier;
}
",FALSE,SAMLSSOResponseValidator.java
" public void setReplayCache(TokenReplayCache replayCache) {
this.replayCache = replayCache;
}
"," public void setReplayCache(TokenReplayCache replayCache) {
this.replayCache = replayCache;
}
",FALSE,SAMLSSOResponseValidator.java
" public DateTime getSessionNotOnOrAfter() {
return sessionNotOnOrAfter;
}
"," public DateTime getSessionNotOnOrAfter() {
return sessionNotOnOrAfter;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setSessionNotOnOrAfter(DateTime sessionNotOnOrAfter) {
this.sessionNotOnOrAfter = sessionNotOnOrAfter;
}
"," public void setSessionNotOnOrAfter(DateTime sessionNotOnOrAfter) {
this.sessionNotOnOrAfter = sessionNotOnOrAfter;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public DateTime getAuthnInstant() {
return authnInstant;
}
"," public DateTime getAuthnInstant() {
return authnInstant;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setAuthnInstant(DateTime authnInstant) {
this.authnInstant = authnInstant;
}
"," public void setAuthnInstant(DateTime authnInstant) {
this.authnInstant = authnInstant;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setSubjectConfirmationData(SubjectConfirmationDataBean subjectConfirmationData) {
this.subjectConfirmationData = subjectConfirmationData;
}
"," public void setSubjectConfirmationData(SubjectConfirmationDataBean subjectConfirmationData) {
this.subjectConfirmationData = subjectConfirmationData;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setConditions(ConditionsBean conditionsBean) {
this.conditions = conditionsBean;
}
"," public void setConditions(ConditionsBean conditionsBean) {
this.conditions = conditionsBean;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setConfirmationMethod(String confMethod) {
confirmationMethod = confMethod;
}
"," public void setConfirmationMethod(String confMethod) {
confirmationMethod = confMethod;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setStatement(Statement statement) {
this.statement = statement;
}
"," public void setStatement(Statement statement) {
this.statement = statement;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setCertIdentifier(CERT_IDENTIFIER certIdentifier) {
this.certIdentifier = certIdentifier;
}
"," public void setCertIdentifier(CERT_IDENTIFIER certIdentifier) {
this.certIdentifier = certIdentifier;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setCerts(X509Certificate[] certs) {
this.certs = certs;
}
"," public void setCerts(X509Certificate[] certs) {
this.certs = certs;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public byte[] getEphemeralKey() {
return ephemeralKey;
}
"," public byte[] getEphemeralKey() {
return ephemeralKey;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setIssuer(String issuer) {
this.issuer = issuer;
}
"," public void setIssuer(String issuer) {
this.issuer = issuer;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setSubjectNameIDFormat(String subjectNameIDFormat) {
this.subjectNameIDFormat = subjectNameIDFormat;
}
"," public void setSubjectNameIDFormat(String subjectNameIDFormat) {
this.subjectNameIDFormat = subjectNameIDFormat;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setSubjectLocality(String ipAddress, String dnsAddress) {
this.subjectLocalityIpAddress = ipAddress;
this.subjectLocalityDnsAddress = dnsAddress;
}
"," public void setSubjectLocality(String ipAddress, String dnsAddress) {
this.subjectLocalityIpAddress = ipAddress;
this.subjectLocalityDnsAddress = dnsAddress;
}
",FALSE,AbstractSAMLCallbackHandler.java
" }
"," public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
",TRUE,AbstractSAMLCallbackHandler.java
" public void setResource(String resource) {
this.resource = resource;
}
"," public void setResource(String resource) {
this.resource = resource;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void setCustomAttributeValues(List customAttributeValues) {
this.customAttributeValues = customAttributeValues;
}
"," public void setCustomAttributeValues(List customAttributeValues) {
this.customAttributeValues = customAttributeValues;
}
",FALSE,AbstractSAMLCallbackHandler.java
" protected void createAndSetStatement(SubjectBean subjectBean, SAMLCallback callback) {
if (statement == Statement.AUTHN) {
AuthenticationStatementBean authBean = new AuthenticationStatementBean();
if (subjectBean != null) {
authBean.setSubject(subjectBean);
}
if (subjectLocalityIpAddress != null || subjectLocalityDnsAddress != null) {
SubjectLocalityBean subjectLocality = new SubjectLocalityBean();
subjectLocality.setIpAddress(subjectLocalityIpAddress);
subjectLocality.setDnsAddress(subjectLocalityDnsAddress);
authBean.setSubjectLocality(subjectLocality);
}
authBean.setAuthenticationInstant(authnInstant);
authBean.setSessionNotOnOrAfter(sessionNotOnOrAfter);
authBean.setAuthenticationMethod(""Password"");
callback.setAuthenticationStatementData(Collections.singletonList(authBean));
} else if (statement == Statement.ATTR) {
AttributeStatementBean attrBean = new AttributeStatementBean();
AttributeBean attributeBean = new AttributeBean();
if (subjectBean != null) {
attrBean.setSubject(subjectBean);
attributeBean.setSimpleName(""role"");
attributeBean.setQualifiedName(""http://custom-ns"");
} else {
attributeBean.setQualifiedName(""role"");
}
if (customAttributeValues != null) {
attributeBean.setAttributeValues(customAttributeValues);
} else {
attributeBean.addAttributeValue(""user"");
}
attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
callback.setAttributeStatementData(Collections.singletonList(attrBean));
} else {
AuthDecisionStatementBean authzBean = new AuthDecisionStatementBean();
if (subjectBean != null) {
authzBean.setSubject(subjectBean);
}
ActionBean actionBean = new ActionBean();
actionBean.setContents(""Read"");
authzBean.setActions(Collections.singletonList(actionBean));
authzBean.setResource(""endpoint"");
authzBean.setDecision(AuthDecisionStatementBean.Decision.PERMIT);
authzBean.setResource(resource);
callback.setAuthDecisionStatementData(Collections.singletonList(authzBean));
}
}
"," protected void createAndSetStatement(SubjectBean subjectBean, SAMLCallback callback) {
if (statement == Statement.AUTHN) {
AuthenticationStatementBean authBean = new AuthenticationStatementBean();
if (subjectBean != null) {
authBean.setSubject(subjectBean);
}
if (subjectLocalityIpAddress != null || subjectLocalityDnsAddress != null) {
SubjectLocalityBean subjectLocality = new SubjectLocalityBean();
subjectLocality.setIpAddress(subjectLocalityIpAddress);
subjectLocality.setDnsAddress(subjectLocalityDnsAddress);
authBean.setSubjectLocality(subjectLocality);
}
authBean.setAuthenticationInstant(authnInstant);
authBean.setSessionNotOnOrAfter(sessionNotOnOrAfter);
authBean.setAuthenticationMethod(""Password"");
callback.setAuthenticationStatementData(Collections.singletonList(authBean));
} else if (statement == Statement.ATTR) {
AttributeStatementBean attrBean = new AttributeStatementBean();
AttributeBean attributeBean = new AttributeBean();
if (subjectBean != null) {
attrBean.setSubject(subjectBean);
attributeBean.setSimpleName(""role"");
attributeBean.setQualifiedName(""http://custom-ns"");
} else {
attributeBean.setQualifiedName(""role"");
}
if (customAttributeValues != null) {
attributeBean.setAttributeValues(customAttributeValues);
} else {
attributeBean.addAttributeValue(""user"");
}
attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
callback.setAttributeStatementData(Collections.singletonList(attrBean));
} else {
AuthDecisionStatementBean authzBean = new AuthDecisionStatementBean();
if (subjectBean != null) {
authzBean.setSubject(subjectBean);
}
ActionBean actionBean = new ActionBean();
actionBean.setContents(""Read"");
authzBean.setActions(Collections.singletonList(actionBean));
authzBean.setResource(""endpoint"");
authzBean.setDecision(AuthDecisionStatementBean.Decision.PERMIT);
authzBean.setResource(resource);
callback.setAuthDecisionStatementData(Collections.singletonList(authzBean));
}
}
",FALSE,AbstractSAMLCallbackHandler.java
" protected KeyInfoBean createKeyInfo() throws Exception {
KeyInfoBean keyInfo = new KeyInfoBean();
if (statement == Statement.AUTHN) {
keyInfo.setCertificate(certs[0]);
keyInfo.setCertIdentifer(certIdentifier);
} else if (statement == Statement.ATTR) {
// Build a new Document
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Create an Encrypted Key
WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
encrKey.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
encrKey.setUseThisCert(certs[0]);
encrKey.prepare(doc, null);
ephemeralKey = encrKey.getEphemeralKey();
Element encryptedKeyElement = encrKey.getEncryptedKeyElement();
// Append the EncryptedKey to a KeyInfo element
Element keyInfoElement =
doc.createElementNS(
WSConstants.SIG_NS, WSConstants.SIG_PREFIX + "":"" + WSConstants.KEYINFO_LN
);
keyInfoElement.setAttributeNS(
WSConstants.XMLNS_NS, ""xmlns:"" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
);
keyInfoElement.appendChild(encryptedKeyElement);
keyInfo.setElement(keyInfoElement);
}
return keyInfo;
}
"," protected KeyInfoBean createKeyInfo() throws Exception {
KeyInfoBean keyInfo = new KeyInfoBean();
if (statement == Statement.AUTHN) {
keyInfo.setCertificate(certs[0]);
keyInfo.setCertIdentifer(certIdentifier);
} else if (statement == Statement.ATTR) {
// Build a new Document
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Create an Encrypted Key
WSSecEncryptedKey encrKey = new WSSecEncryptedKey();
encrKey.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
encrKey.setUseThisCert(certs[0]);
encrKey.prepare(doc, null);
ephemeralKey = encrKey.getEphemeralKey();
Element encryptedKeyElement = encrKey.getEncryptedKeyElement();
// Append the EncryptedKey to a KeyInfo element
Element keyInfoElement =
doc.createElementNS(
WSConstants.SIG_NS, WSConstants.SIG_PREFIX + "":"" + WSConstants.KEYINFO_LN
);
keyInfoElement.setAttributeNS(
WSConstants.XMLNS_NS, ""xmlns:"" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS
);
keyInfoElement.appendChild(encryptedKeyElement);
keyInfo.setElement(keyInfoElement);
}
return keyInfo;
}
",FALSE,AbstractSAMLCallbackHandler.java
" public void validate(Object object) throws ValidationException {
String fieldName = getFieldName();
Object value = this.getFieldValue(fieldName, object);
// if there is no value - don't do comparison
// if a value is required, a required validator should be added to the field
if (value == null || value.toString().length() == 0) {
return;
}
if (!(value.getClass().equals(String.class)) || !Pattern.compile(getUrlRegex(), Pattern.CASE_INSENSITIVE).matcher(String.valueOf(value)).matches()) {
addFieldError(fieldName, object);
}
}
"," public void validate(Object object) throws ValidationException {
String fieldName = getFieldName();
Object value = this.getFieldValue(fieldName, object);
// if there is no value - don't do comparison
// if a value is required, a required validator should be added to the field
if (value == null || value.toString().length() == 0) {
return;
}
if (!(value.getClass().equals(String.class)) || !Pattern.compile(getUrlRegex(), Pattern.CASE_INSENSITIVE).matcher(String.valueOf(value).trim()).matches()) {
addFieldError(fieldName, object);
}
}
",TRUE,URLValidator.java
" public String getUrlRegex() {
if (StringUtils.isNotEmpty(urlRegexExpression)) {
return (String) parse(urlRegexExpression, String.class);
} else if (StringUtils.isNotEmpty(urlRegex)) {
return urlRegex;
} else {
return ""^(https?|ftp):\\/\\/"" +
""(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+"" +
""(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?"" +
""@)?(#?"" +
"")((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*"" +
""[a-z][a-z0-9-]*[a-z0-9]"" +
""|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}"" +
""(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])"" +
"")(:\\d+)?"" +
"")(((\\/{0,1}([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*"" +
""(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)"" +
""?)?)?"" +
""(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?"" +
""$"";
}
}
"," public String getUrlRegex() {
if (StringUtils.isNotEmpty(urlRegexExpression)) {
return (String) parse(urlRegexExpression, String.class);
} else if (StringUtils.isNotEmpty(urlRegex)) {
return urlRegex;
} else {
return ""^(https?|ftp):\\/\\/"" +
""(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+"" +
""(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?"" +
""@)?(#?"" +
"")((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*"" +
""[a-z][a-z0-9-]*[a-z0-9]"" +
""|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}"" +
""(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])"" +
"")(:\\d+)?"" +
"")(((\\/{0,1}([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*"" +
""(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)"" +
""?)?)?"" +
""(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?"" +
""$"";
}
}
",FALSE,URLValidator.java
" public void setUrlRegex(String urlRegex) {
this.urlRegex = urlRegex;
}
"," public void setUrlRegex(String urlRegex) {
this.urlRegex = urlRegex;
}
",FALSE,URLValidator.java
" public void setUrlRegexExpression(String urlRegexExpression) {
this.urlRegexExpression = urlRegexExpression;
}
"," public void setUrlRegexExpression(String urlRegexExpression) {
this.urlRegexExpression = urlRegexExpression;
}
",FALSE,URLValidator.java
" RequestBuilder(String method, HttpUrl baseUrl,
@Nullable String relativeUrl, @Nullable Headers headers, @Nullable MediaType contentType,
boolean hasBody, boolean isFormEncoded, boolean isMultipart) {
this.method = method;
this.baseUrl = baseUrl;
this.relativeUrl = relativeUrl;
this.requestBuilder = new Request.Builder();
this.contentType = contentType;
this.hasBody = hasBody;
if (headers != null) {
requestBuilder.headers(headers);
}
if (isFormEncoded) {
// Will be set to 'body' in 'build'.
formBuilder = new FormBody.Builder();
} else if (isMultipart) {
// Will be set to 'body' in 'build'.
multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
}
}
"," RequestBuilder(String method, HttpUrl baseUrl,
@Nullable String relativeUrl, @Nullable Headers headers, @Nullable MediaType contentType,
boolean hasBody, boolean isFormEncoded, boolean isMultipart) {
this.method = method;
this.baseUrl = baseUrl;
this.relativeUrl = relativeUrl;
this.requestBuilder = new Request.Builder();
this.contentType = contentType;
this.hasBody = hasBody;
if (headers != null) {
requestBuilder.headers(headers);
}
if (isFormEncoded) {
// Will be set to 'body' in 'build'.
formBuilder = new FormBody.Builder();
} else if (isMultipart) {
// Will be set to 'body' in 'build'.
multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
}
}
",FALSE,RequestBuilder.java
" void setRelativeUrl(Object relativeUrl) {
this.relativeUrl = relativeUrl.toString();
}
"," void setRelativeUrl(Object relativeUrl) {
this.relativeUrl = relativeUrl.toString();
}
",FALSE,RequestBuilder.java
" void addHeader(String name, String value) {
if (""Content-Type"".equalsIgnoreCase(name)) {
try {
contentType = MediaType.get(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(""Malformed content type: "" + value, e);
}
} else {
requestBuilder.addHeader(name, value);
}
}
"," void addHeader(String name, String value) {
if (""Content-Type"".equalsIgnoreCase(name)) {
try {
contentType = MediaType.get(value);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(""Malformed content type: "" + value, e);
}
} else {
requestBuilder.addHeader(name, value);
}
}
",FALSE,RequestBuilder.java
" void addPathParam(String name, String value, boolean encoded) {
if (relativeUrl == null) {
// The relative URL is cleared when the first query parameter is set.
throw new AssertionError();
}
relativeUrl = relativeUrl.replace(""{"" + name + ""}"", canonicalizeForPath(value, encoded));
}
"," void addPathParam(String name, String value, boolean encoded) {
if (relativeUrl == null) {
// The relative URL is cleared when the first query parameter is set.
throw new AssertionError();
}
String replacement = canonicalizeForPath(value, encoded);
String newRelativeUrl = relativeUrl.replace(""{"" + name + ""}"", replacement);
if (PATH_TRAVERSAL.matcher(newRelativeUrl).matches()) {
throw new IllegalArgumentException(
""@Path parameters shouldn't perform path traversal ('.' or '..'): "" + value);
}
relativeUrl = newRelativeUrl;
}
",TRUE,RequestBuilder.java
" private static String canonicalizeForPath(String input, boolean alreadyEncoded) {
int codePoint;
for (int i = 0, limit = input.length(); i < limit; i += Character.charCount(codePoint)) {
codePoint = input.codePointAt(i);
if (codePoint < 0x20 || codePoint >= 0x7f
|| PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1
|| (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) {
// Slow path: the character at i requires encoding!
Buffer out = new Buffer();
out.writeUtf8(input, 0, i);
canonicalizeForPath(out, input, i, limit, alreadyEncoded);
return out.readUtf8();
}
}
// Fast path: no characters required encoding.
return input;
}
"," private static String canonicalizeForPath(String input, boolean alreadyEncoded) {
int codePoint;
for (int i = 0, limit = input.length(); i < limit; i += Character.charCount(codePoint)) {
codePoint = input.codePointAt(i);
if (codePoint < 0x20 || codePoint >= 0x7f
|| PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1
|| (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) {
// Slow path: the character at i requires encoding!
Buffer out = new Buffer();
out.writeUtf8(input, 0, i);
canonicalizeForPath(out, input, i, limit, alreadyEncoded);
return out.readUtf8();
}
}
// Fast path: no characters required encoding.
return input;
}
",FALSE,RequestBuilder.java
" private static void canonicalizeForPath(Buffer out, String input, int pos, int limit,
boolean alreadyEncoded) {
Buffer utf8Buffer = null; // Lazily allocated.
int codePoint;
for (int i = pos; i < limit; i += Character.charCount(codePoint)) {
codePoint = input.codePointAt(i);
if (alreadyEncoded
&& (codePoint == '\t' || codePoint == '\n' || codePoint == '\f' || codePoint == '\r')) {
// Skip this character.
} else if (codePoint < 0x20 || codePoint >= 0x7f
|| PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1
|| (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) {
// Percent encode this character.
if (utf8Buffer == null) {
utf8Buffer = new Buffer();
}
utf8Buffer.writeUtf8CodePoint(codePoint);
while (!utf8Buffer.exhausted()) {
int b = utf8Buffer.readByte() & 0xff;
out.writeByte('%');
out.writeByte(HEX_DIGITS[(b >> 4) & 0xf]);
out.writeByte(HEX_DIGITS[b & 0xf]);
}
} else {
// This character doesn't need encoding. Just copy it over.
out.writeUtf8CodePoint(codePoint);
}
}
}
"," private static void canonicalizeForPath(Buffer out, String input, int pos, int limit,
boolean alreadyEncoded) {
Buffer utf8Buffer = null; // Lazily allocated.
int codePoint;
for (int i = pos; i < limit; i += Character.charCount(codePoint)) {
codePoint = input.codePointAt(i);
if (alreadyEncoded
&& (codePoint == '\t' || codePoint == '\n' || codePoint == '\f' || codePoint == '\r')) {
// Skip this character.
} else if (codePoint < 0x20 || codePoint >= 0x7f
|| PATH_SEGMENT_ALWAYS_ENCODE_SET.indexOf(codePoint) != -1
|| (!alreadyEncoded && (codePoint == '/' || codePoint == '%'))) {
// Percent encode this character.
if (utf8Buffer == null) {
utf8Buffer = new Buffer();
}
utf8Buffer.writeUtf8CodePoint(codePoint);
while (!utf8Buffer.exhausted()) {
int b = utf8Buffer.readByte() & 0xff;
out.writeByte('%');
out.writeByte(HEX_DIGITS[(b >> 4) & 0xf]);
out.writeByte(HEX_DIGITS[b & 0xf]);
}
} else {
// This character doesn't need encoding. Just copy it over.
out.writeUtf8CodePoint(codePoint);
}
}
}
",FALSE,RequestBuilder.java
" void addQueryParam(String name, @Nullable String value, boolean encoded) {
if (relativeUrl != null) {
// Do a one-time combination of the built relative URL and the base URL.
urlBuilder = baseUrl.newBuilder(relativeUrl);
if (urlBuilder == null) {
throw new IllegalArgumentException(
""Malformed URL. Base: "" + baseUrl + "", Relative: "" + relativeUrl);
}
relativeUrl = null;
}
if (encoded) {
//noinspection ConstantConditions Checked to be non-null by above 'if' block.
urlBuilder.addEncodedQueryParameter(name, value);
} else {
//noinspection ConstantConditions Checked to be non-null by above 'if' block.
urlBuilder.addQueryParameter(name, value);
}
}
"," void addQueryParam(String name, @Nullable String value, boolean encoded) {
if (relativeUrl != null) {
// Do a one-time combination of the built relative URL and the base URL.
urlBuilder = baseUrl.newBuilder(relativeUrl);
if (urlBuilder == null) {
throw new IllegalArgumentException(
""Malformed URL. Base: "" + baseUrl + "", Relative: "" + relativeUrl);
}
relativeUrl = null;
}
if (encoded) {
//noinspection ConstantConditions Checked to be non-null by above 'if' block.
urlBuilder.addEncodedQueryParameter(name, value);
} else {
//noinspection ConstantConditions Checked to be non-null by above 'if' block.
urlBuilder.addQueryParameter(name, value);
}
}
",FALSE,RequestBuilder.java
" void addFormField(String name, String value, boolean encoded) {
if (encoded) {
formBuilder.addEncoded(name, value);
} else {
formBuilder.add(name, value);
}
}
"," void addFormField(String name, String value, boolean encoded) {
if (encoded) {
formBuilder.addEncoded(name, value);
} else {
formBuilder.add(name, value);
}
}
",FALSE,RequestBuilder.java
" void addPart(Headers headers, RequestBody body) {
multipartBuilder.addPart(headers, body);
}
"," void addPart(Headers headers, RequestBody body) {
multipartBuilder.addPart(headers, body);
}
",FALSE,RequestBuilder.java
" void addPart(MultipartBody.Part part) {
multipartBuilder.addPart(part);
}
"," void addPart(MultipartBody.Part part) {
multipartBuilder.addPart(part);
}
",FALSE,RequestBuilder.java
" void setBody(RequestBody body) {
this.body = body;
}
"," void setBody(RequestBody body) {
this.body = body;
}
",FALSE,RequestBuilder.java
" Request.Builder get() {
HttpUrl url;
HttpUrl.Builder urlBuilder = this.urlBuilder;
if (urlBuilder != null) {
url = urlBuilder.build();
} else {
// No query parameters triggered builder creation, just combine the relative URL and base URL.
//noinspection ConstantConditions Non-null if urlBuilder is null.
url = baseUrl.resolve(relativeUrl);
if (url == null) {
throw new IllegalArgumentException(
""Malformed URL. Base: "" + baseUrl + "", Relative: "" + relativeUrl);
}
}
RequestBody body = this.body;
if (body == null) {
// Try to pull from one of the builders.
if (formBuilder != null) {
body = formBuilder.build();
} else if (multipartBuilder != null) {
body = multipartBuilder.build();
} else if (hasBody) {
// Body is absent, make an empty body.
body = RequestBody.create(null, new byte[0]);
}
}
MediaType contentType = this.contentType;
if (contentType != null) {
if (body != null) {
body = new ContentTypeOverridingRequestBody(body, contentType);
} else {
requestBuilder.addHeader(""Content-Type"", contentType.toString());
}
}
return requestBuilder
.url(url)
.method(method, body);
}
"," Request.Builder get() {
HttpUrl url;
HttpUrl.Builder urlBuilder = this.urlBuilder;
if (urlBuilder != null) {
url = urlBuilder.build();
} else {
// No query parameters triggered builder creation, just combine the relative URL and base URL.
//noinspection ConstantConditions Non-null if urlBuilder is null.
url = baseUrl.resolve(relativeUrl);
if (url == null) {
throw new IllegalArgumentException(
""Malformed URL. Base: "" + baseUrl + "", Relative: "" + relativeUrl);
}
}
RequestBody body = this.body;
if (body == null) {
// Try to pull from one of the builders.
if (formBuilder != null) {
body = formBuilder.build();
} else if (multipartBuilder != null) {
body = multipartBuilder.build();
} else if (hasBody) {
// Body is absent, make an empty body.
body = RequestBody.create(null, new byte[0]);
}
}
MediaType contentType = this.contentType;
if (contentType != null) {
if (body != null) {
body = new ContentTypeOverridingRequestBody(body, contentType);
} else {
requestBuilder.addHeader(""Content-Type"", contentType.toString());
}
}
return requestBuilder
.url(url)
.method(method, body);
}
",FALSE,RequestBuilder.java
" ContentTypeOverridingRequestBody(RequestBody delegate, MediaType contentType) {
this.delegate = delegate;
this.contentType = contentType;
}
"," ContentTypeOverridingRequestBody(RequestBody delegate, MediaType contentType) {
this.delegate = delegate;
this.contentType = contentType;
}
",FALSE,RequestBuilder.java
" @Override public MediaType contentType() {
return contentType;
}
"," @Override public MediaType contentType() {
return contentType;
}
",FALSE,RequestBuilder.java
" @Override public long contentLength() throws IOException {
return delegate.contentLength();
}
"," @Override public long contentLength() throws IOException {
return delegate.contentLength();
}
",FALSE,RequestBuilder.java
" @Override public void writeTo(BufferedSink sink) throws IOException {
delegate.writeTo(sink);
}
"," @Override public void writeTo(BufferedSink sink) throws IOException {
delegate.writeTo(sink);
}
",FALSE,RequestBuilder.java
" @Test public void customMethodNoBody() {
class Example {
@HTTP(method = ""CUSTOM1"", path = ""/foo"")
Call method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo(""CUSTOM1"");
assertThat(request.url().toString()).isEqualTo(""http://example.com/foo"");
assertThat(request.body()).isNull();
}
"," @Test public void customMethodNoBody() {
class Example {
@HTTP(method = ""CUSTOM1"", path = ""/foo"")
Call method() {
return null;
}
}
Request request = buildRequest(Example.class);
assertThat(request.method()).isEqualTo(""CUSTOM1"");
assertThat(request.url().toString()).isEqualTo(""http://example.com/foo"");
assertThat(request.body()).isNull();
}
",FALSE,RequestFactoryTest.java
" @Test public void customMethodWithBody() {
class Example {
@HTTP(method = ""CUSTOM2"", path = ""/foo"", hasBody = true)
Call method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi"");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo(""CUSTOM2"");
assertThat(request.url().toString()).isEqualTo(""http://example.com/foo"");
assertBody(request.body(), ""hi"");
}
"," @Test public void customMethodWithBody() {
class Example {
@HTTP(method = ""CUSTOM2"", path = ""/foo"", hasBody = true)
Call method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi"");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo(""CUSTOM2"");
assertThat(request.url().toString()).isEqualTo(""http://example.com/foo"");
assertBody(request.body(), ""hi"");
}
",FALSE,RequestFactoryTest.java
" @Test public void onlyOneEncodingIsAllowedMultipartFirst() {
class Example {
@Multipart //
@FormUrlEncoded //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Only one encoding annotation is allowed.\n for method Example.method"");
}
}
"," @Test public void onlyOneEncodingIsAllowedMultipartFirst() {
class Example {
@Multipart //
@FormUrlEncoded //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Only one encoding annotation is allowed.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void onlyOneEncodingIsAllowedFormEncodingFirst() {
class Example {
@FormUrlEncoded //
@Multipart //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Only one encoding annotation is allowed.\n for method Example.method"");
}
}
"," @Test public void onlyOneEncodingIsAllowedFormEncodingFirst() {
class Example {
@FormUrlEncoded //
@Multipart //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Only one encoding annotation is allowed.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void invalidPathParam() throws Exception {
class Example {
@GET(""/"") //
Call method(@Path(""hey!"") String thing) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Path parameter name must match \\{([a-zA-Z][a-zA-Z0-9_-]*)\\}.""
+ "" Found: hey! (parameter #1)\n for method Example.method"");
}
}
"," @Test public void invalidPathParam() throws Exception {
class Example {
@GET(""/"") //
Call method(@Path(""hey!"") String thing) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Path parameter name must match \\{([a-zA-Z][a-zA-Z0-9_-]*)\\}.""
+ "" Found: hey! (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void pathParamNotAllowedInQuery() throws Exception {
class Example {
@GET(""/foo?bar={bar}"") //
Call method(@Path(""bar"") String thing) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""URL query string \""bar={bar}\"" must not have replace block.""
+ "" For dynamic query parameters use @Query.\n for method Example.method"");
}
}
"," @Test public void pathParamNotAllowedInQuery() throws Exception {
class Example {
@GET(""/foo?bar={bar}"") //
Call method(@Path(""bar"") String thing) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""URL query string \""bar={bar}\"" must not have replace block.""
+ "" For dynamic query parameters use @Query.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void multipleParameterAnnotationsNotAllowed() throws Exception {
class Example {
@GET(""/"") //
Call method(@Body @Query(""nope"") String o) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Multiple Retrofit annotations found, only one allowed. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void multipleParameterAnnotationsNotAllowed() throws Exception {
class Example {
@GET(""/"") //
Call method(@Body @Query(""nope"") String o) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Multiple Retrofit annotations found, only one allowed. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception {
class Example {
@GET(""/"") //
Call method(@Query(""maybe"") @NonNull Object o) {
return null;
}
}
Request request = buildRequest(Example.class, ""yep"");
assertThat(request.url().toString()).isEqualTo(""http://example.com/?maybe=yep"");
}
"," @Test public void multipleParameterAnnotationsOnlyOneRetrofitAllowed() throws Exception {
class Example {
@GET(""/"") //
Call method(@Query(""maybe"") @NonNull Object o) {
return null;
}
}
Request request = buildRequest(Example.class, ""yep"");
assertThat(request.url().toString()).isEqualTo(""http://example.com/?maybe=yep"");
}
",FALSE,RequestFactoryTest.java
" @Test public void twoMethodsFail() {
class Example {
@PATCH(""/foo"") //
@POST(""/foo"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isIn(""Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method"",
""Only one HTTP method is allowed. Found: POST and PATCH.\n for method Example.method"");
}
}
"," @Test public void twoMethodsFail() {
class Example {
@PATCH(""/foo"") //
@POST(""/foo"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage())
.isIn(""Only one HTTP method is allowed. Found: PATCH and POST.\n for method Example.method"",
""Only one HTTP method is allowed. Found: POST and PATCH.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void lackingMethod() {
class Example {
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""HTTP method annotation is required (e.g., @GET, @POST, etc.).\n for method Example.method"");
}
}
"," @Test public void lackingMethod() {
class Example {
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""HTTP method annotation is required (e.g., @GET, @POST, etc.).\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void implicitMultipartForbidden() {
class Example {
@POST(""/"") //
Call method(@Part(""a"") int a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Part parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void implicitMultipartForbidden() {
class Example {
@POST(""/"") //
Call method(@Part(""a"") int a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Part parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void implicitMultipartWithPartMapForbidden() {
class Example {
@POST(""/"") //
Call method(@PartMap Map params) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@PartMap parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void implicitMultipartWithPartMapForbidden() {
class Example {
@POST(""/"") //
Call method(@PartMap Map params) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@PartMap parameters can only be used with multipart encoding. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void multipartFailsOnNonBodyMethod() {
class Example {
@Multipart //
@GET(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Multipart can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"");
}
}
"," @Test public void multipartFailsOnNonBodyMethod() {
class Example {
@Multipart //
@GET(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Multipart can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void multipartFailsWithNoParts() {
class Example {
@Multipart //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Multipart method must contain at least one @Part.\n for method Example.method"");
}
}
"," @Test public void multipartFailsWithNoParts() {
class Example {
@Multipart //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Multipart method must contain at least one @Part.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void implicitFormEncodingByFieldForbidden() {
class Example {
@POST(""/"") //
Call method(@Field(""a"") int a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Field parameters can only be used with form encoding. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void implicitFormEncodingByFieldForbidden() {
class Example {
@POST(""/"") //
Call method(@Field(""a"") int a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Field parameters can only be used with form encoding. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void implicitFormEncodingByFieldMapForbidden() {
class Example {
@POST(""/"") //
Call method(@FieldMap Map a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@FieldMap parameters can only be used with form encoding. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void implicitFormEncodingByFieldMapForbidden() {
class Example {
@POST(""/"") //
Call method(@FieldMap Map a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@FieldMap parameters can only be used with form encoding. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void formEncodingFailsOnNonBodyMethod() {
class Example {
@FormUrlEncoded //
@GET(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"");
}
}
"," @Test public void formEncodingFailsOnNonBodyMethod() {
class Example {
@FormUrlEncoded //
@GET(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""FormUrlEncoded can only be specified on HTTP methods with request body (e.g., @POST).\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void formEncodingFailsWithNoParts() {
class Example {
@FormUrlEncoded //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(""Form-encoded method must contain at least one @Field.\n for method Example.method"");
}
}
"," @Test public void formEncodingFailsWithNoParts() {
class Example {
@FormUrlEncoded //
@POST(""/"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(""Form-encoded method must contain at least one @Field.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void headersFailWhenEmptyOnMethod() {
class Example {
@GET(""/"") //
@Headers({}) //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(""@Headers annotation is empty.\n for method Example.method"");
}
}
"," @Test public void headersFailWhenEmptyOnMethod() {
class Example {
@GET(""/"") //
@Headers({}) //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(""@Headers annotation is empty.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void headersFailWhenMalformed() {
class Example {
@GET(""/"") //
@Headers(""Malformed"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Headers value must be in the form \""Name: Value\"". Found: \""Malformed\""\n for method Example.method"");
}
}
"," @Test public void headersFailWhenMalformed() {
class Example {
@GET(""/"") //
@Headers(""Malformed"") //
Call method() {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@Headers value must be in the form \""Name: Value\"". Found: \""Malformed\""\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void pathParamNonPathParamAndTypedBytes() {
class Example {
@PUT(""/{a}"") //
Call method(@Path(""a"") int a, @Path(""b"") int b, @Body int c) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""URL \""/{a}\"" does not contain \""{b}\"". (parameter #2)\n for method Example.method"");
}
}
"," @Test public void pathParamNonPathParamAndTypedBytes() {
class Example {
@PUT(""/{a}"") //
Call method(@Path(""a"") int a, @Path(""b"") int b, @Body int c) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""URL \""/{a}\"" does not contain \""{b}\"". (parameter #2)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void parameterWithoutAnnotation() {
class Example {
@GET(""/"") //
Call method(String a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""No Retrofit annotation found. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void parameterWithoutAnnotation() {
class Example {
@GET(""/"") //
Call method(String a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""No Retrofit annotation found. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void nonBodyHttpMethodWithSingleEntity() {
class Example {
@GET(""/"") //
Call method(@Body String o) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Non-body HTTP method cannot contain @Body.\n for method Example.method"");
}
}
"," @Test public void nonBodyHttpMethodWithSingleEntity() {
class Example {
@GET(""/"") //
Call method(@Body String o) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""Non-body HTTP method cannot contain @Body.\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void queryMapMustBeAMap() {
class Example {
@GET(""/"") //
Call method(@QueryMap List a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@QueryMap parameter type must be Map. (parameter #1)\n for method Example.method"");
}
}
"," @Test public void queryMapMustBeAMap() {
class Example {
@GET(""/"") //
Call method(@QueryMap List a) {
return null;
}
}
try {
buildRequest(Example.class);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage(
""@QueryMap parameter type must be Map. (parameter #1)\n for method Example.method"");
}
}
",FALSE,RequestFactoryTest.java
" @Test public void queryMapSupportsSubclasses() {
class Foo extends HashMap {
}
class Example {
@GET(""/"") //
Call method(@QueryMap Foo a) {
return null;
}
}
Foo foo = new Foo();
foo.put(""hello"", ""world"");
Request request = buildRequest(Example.class, foo);
assertThat(request.url().toString()).isEqualTo(""http://example.com/?hello=world"");
}
"," @Test public void queryMapSupportsSubclasses() {
class Foo extends HashMap {
}
class Example {
@GET(""/"") //
Call method(@QueryMap Foo a) {
return null;
}
}
Foo foo = new Foo();
foo.put(""hello"", ""world"");
Request request = buildRequest(Example.class, foo);
assertThat(request.url().toString()).isEqualTo(""http://example.com/?hello=world"");
}
",FALSE,RequestFactoryTest.java
" @Test public void queryMapRejectsNull() {
class Example {
@GET(""/"") //
Call method(@QueryMap Map