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.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(""), 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(""': 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.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.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.emitTagPending(); t.transition(Data); break; default: t.dataBuffer.append(c); needsExitTransition = true; } } else { needsExitTransition = true; } if (needsExitTransition) { t.emit(""': 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
OneTwo
""; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, ""http://foo.com/""); assertEquals(""Foo
OneTwo
"", TextUtil.stripNewlines(doc.html())); assertEquals(doc.getElementById(""2"").absUrl(""href""), ""http://foo.com/bar""); } "," public void testSimpleXmlParse() { String xml = ""Foo
OneTwo
""; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, ""http://foo.com/""); assertEquals(""Foo
OneTwo
"", 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 = ""OneTwoThree""; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, ""http://foo.com/""); assertEquals(""OneTwoThree"", TextUtil.stripNewlines(doc.html())); } "," public void testPopToClose() { // test: closes Two, ignored String xml = ""OneTwoThree""; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, ""http://foo.com/""); assertEquals(""OneTwoThree"", 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 = ""OneTwoThree""; Document doc = Jsoup.parse(xml, ""http://foo.com/"", Parser.xmlParser()); assertEquals(""OneTwoThree"", TextUtil.stripNewlines(doc.html())); } "," public void testSupplyParserToJsoupClass() { String xml = ""OneTwoThree""; Document doc = Jsoup.parse(xml, ""http://foo.com/"", Parser.xmlParser()); assertEquals(""OneTwoThree"", 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(""OneTwoThree"", 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(""OneTwoThree"", 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(""OneTwoThree"", 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(""OneTwoThree"", 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 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. "", 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 a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Query map was null.""); } } "," @Test public void queryMapRejectsNull() { class Example { @GET(""/"") // Call method(@QueryMap Map a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Query map was null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void queryMapRejectsNullKeys() { class Example { @GET(""/"") // Call method(@QueryMap Map a) { return null; } } Map queryParams = new LinkedHashMap<>(); queryParams.put(""ping"", ""pong""); queryParams.put(null, ""kat""); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Query map contained null key.""); } } "," @Test public void queryMapRejectsNullKeys() { class Example { @GET(""/"") // Call method(@QueryMap Map a) { return null; } } Map queryParams = new LinkedHashMap<>(); queryParams.put(""ping"", ""pong""); queryParams.put(null, ""kat""); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Query map contained null key.""); } } ",FALSE,RequestFactoryTest.java " @Test public void queryMapRejectsNullValues() { class Example { @GET(""/"") // Call method(@QueryMap Map a) { return null; } } Map queryParams = new LinkedHashMap<>(); queryParams.put(""ping"", ""pong""); queryParams.put(""kit"", null); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Query map contained null value for key 'kit'.""); } } "," @Test public void queryMapRejectsNullValues() { class Example { @GET(""/"") // Call method(@QueryMap Map a) { return null; } } Map queryParams = new LinkedHashMap<>(); queryParams.put(""ping"", ""pong""); queryParams.put(""kit"", null); try { buildRequest(Example.class, queryParams); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Query map contained null value for key 'kit'.""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithHeaderMap() { class Example { @GET(""/search"") Call method(@HeaderMap Map headers) { return null; } } Map headers = new LinkedHashMap<>(); headers.put(""Accept"", ""text/plain""); headers.put(""Accept-Charset"", ""utf-8""); Request request = buildRequest(Example.class, headers); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.url().toString()).isEqualTo(""http://example.com/search""); assertThat(request.body()).isNull(); assertThat(request.headers().size()).isEqualTo(2); assertThat(request.header(""Accept"")).isEqualTo(""text/plain""); assertThat(request.header(""Accept-Charset"")).isEqualTo(""utf-8""); } "," @Test public void getWithHeaderMap() { class Example { @GET(""/search"") Call method(@HeaderMap Map headers) { return null; } } Map headers = new LinkedHashMap<>(); headers.put(""Accept"", ""text/plain""); headers.put(""Accept-Charset"", ""utf-8""); Request request = buildRequest(Example.class, headers); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.url().toString()).isEqualTo(""http://example.com/search""); assertThat(request.body()).isNull(); assertThat(request.headers().size()).isEqualTo(2); assertThat(request.header(""Accept"")).isEqualTo(""text/plain""); assertThat(request.header(""Accept-Charset"")).isEqualTo(""utf-8""); } ",FALSE,RequestFactoryTest.java " @Test public void headerMapMustBeAMap() { class Example { @GET(""/"") Call method(@HeaderMap List headers) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@HeaderMap parameter type must be Map. (parameter #1)\n for method Example.method""); } } "," @Test public void headerMapMustBeAMap() { class Example { @GET(""/"") Call method(@HeaderMap List headers) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@HeaderMap parameter type must be Map. (parameter #1)\n for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void headerMapSupportsSubclasses() { class Foo extends HashMap { } class Example { @GET(""/search"") Call method(@HeaderMap Foo headers) { return null; } } Foo headers = new Foo(); headers.put(""Accept"", ""text/plain""); Request request = buildRequest(Example.class, headers); assertThat(request.url().toString()).isEqualTo(""http://example.com/search""); assertThat(request.headers().size()).isEqualTo(1); assertThat(request.header(""Accept"")).isEqualTo(""text/plain""); } "," @Test public void headerMapSupportsSubclasses() { class Foo extends HashMap { } class Example { @GET(""/search"") Call method(@HeaderMap Foo headers) { return null; } } Foo headers = new Foo(); headers.put(""Accept"", ""text/plain""); Request request = buildRequest(Example.class, headers); assertThat(request.url().toString()).isEqualTo(""http://example.com/search""); assertThat(request.headers().size()).isEqualTo(1); assertThat(request.header(""Accept"")).isEqualTo(""text/plain""); } ",FALSE,RequestFactoryTest.java " @Test public void headerMapRejectsNull() { class Example { @GET(""/"") Call method(@HeaderMap Map headers) { return null; } } try { buildRequest(Example.class, (Map) null); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Header map was null.""); } } "," @Test public void headerMapRejectsNull() { class Example { @GET(""/"") Call method(@HeaderMap Map headers) { return null; } } try { buildRequest(Example.class, (Map) null); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Header map was null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void headerMapRejectsNullKeys() { class Example { @GET(""/"") Call method(@HeaderMap Map headers) { return null; } } Map headers = new LinkedHashMap<>(); headers.put(""Accept"", ""text/plain""); headers.put(null, ""utf-8""); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Header map contained null key.""); } } "," @Test public void headerMapRejectsNullKeys() { class Example { @GET(""/"") Call method(@HeaderMap Map headers) { return null; } } Map headers = new LinkedHashMap<>(); headers.put(""Accept"", ""text/plain""); headers.put(null, ""utf-8""); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Header map contained null key.""); } } ",FALSE,RequestFactoryTest.java " @Test public void headerMapRejectsNullValues() { class Example { @GET(""/"") Call method(@HeaderMap Map headers) { return null; } } Map headers = new LinkedHashMap<>(); headers.put(""Accept"", ""text/plain""); headers.put(""Accept-Charset"", null); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Header map contained null value for key 'Accept-Charset'.""); } } "," @Test public void headerMapRejectsNullValues() { class Example { @GET(""/"") Call method(@HeaderMap Map headers) { return null; } } Map headers = new LinkedHashMap<>(); headers.put(""Accept"", ""text/plain""); headers.put(""Accept-Charset"", null); try { buildRequest(Example.class, headers); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Header map contained null value for key 'Accept-Charset'.""); } } ",FALSE,RequestFactoryTest.java " @Test public void twoBodies() { class Example { @PUT(""/"") // Call method(@Body String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""Multiple @Body method annotations found. (parameter #2)\n for method Example.method""); } } "," @Test public void twoBodies() { class Example { @PUT(""/"") // Call method(@Body String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""Multiple @Body method annotations found. (parameter #2)\n for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void bodyInNonBodyRequest() { class Example { @Multipart // @PUT(""/"") // Call method(@Part(""one"") String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Body parameters cannot be used with form or multi-part encoding. (parameter #2)\n for method Example.method""); } } "," @Test public void bodyInNonBodyRequest() { class Example { @Multipart // @PUT(""/"") // Call method(@Part(""one"") String o1, @Body String o2) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Body parameters cannot be used with form or multi-part encoding. (parameter #2)\n for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void get() { class Example { @GET(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void get() { class Example { @GET(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void delete() { class Example { @DELETE(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""DELETE""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertNull(request.body()); } "," @Test public void delete() { class Example { @DELETE(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""DELETE""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertNull(request.body()); } ",FALSE,RequestFactoryTest.java " @Test public void head() { class Example { @HEAD(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""HEAD""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void head() { class Example { @HEAD(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""HEAD""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void headWithoutVoidThrows() { class Example { @HEAD(""/foo/bar/"") // Call method() { return null; } } try { buildRequest(Example.class); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""HEAD method must use Void as response type.\n for method Example.method""); } } "," @Test public void headWithoutVoidThrows() { class Example { @HEAD(""/foo/bar/"") // Call method() { return null; } } try { buildRequest(Example.class); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""HEAD method must use Void as response type.\n for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void post() { class Example { @POST(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), ""hi""); } "," @Test public void post() { class Example { @POST(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), ""hi""); } ",FALSE,RequestFactoryTest.java " @Test public void put() { class Example { @PUT(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo(""PUT""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), ""hi""); } "," @Test public void put() { class Example { @PUT(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo(""PUT""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), ""hi""); } ",FALSE,RequestFactoryTest.java " @Test public void patch() { class Example { @PATCH(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo(""PATCH""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), ""hi""); } "," @Test public void patch() { class Example { @PATCH(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.method()).isEqualTo(""PATCH""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), ""hi""); } ",FALSE,RequestFactoryTest.java " @Test public void options() { class Example { @OPTIONS(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""OPTIONS""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void options() { class Example { @OPTIONS(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""OPTIONS""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithPathParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""po ng""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/po%20ng/""); assertThat(request.body()).isNull(); } "," @Test public void getWithPathParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""po ng""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/po%20ng/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithUnusedAndInvalidNamedPathParam() { class Example { @GET(""/foo/bar/{ping}/{kit,kat}/"") // Call method(@Path(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/%7Bkit,kat%7D/""); assertThat(request.body()).isNull(); } "," @Test public void getWithUnusedAndInvalidNamedPathParam() { class Example { @GET(""/foo/bar/{ping}/{kit,kat}/"") // Call method(@Path(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/%7Bkit,kat%7D/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithEncodedPathParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""po%20ng""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/po%20ng/""); assertThat(request.body()).isNull(); } "," @Test public void getWithEncodedPathParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""po%20ng""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/po%20ng/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithEncodedPathSegments() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""baz/pong/more""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/baz/pong/more/""); assertThat(request.body()).isNull(); } "," @Test public void getWithEncodedPathSegments() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""baz/pong/more""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/baz/pong/more/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithUnencodedPathSegmentsPreventsRequestSplitting() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = false) String ping) { return null; } } Request request = buildRequest(Example.class, ""baz/\r\nheader: blue""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/baz%2F%0D%0Aheader:%20blue/""); assertThat(request.body()).isNull(); } "," @Test public void getWithUnencodedPathSegmentsPreventsRequestSplitting() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = false) String ping) { return null; } } Request request = buildRequest(Example.class, ""baz/\r\nheader: blue""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/baz%2F%0D%0Aheader:%20blue/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithEncodedPathStillPreventsRequestSplitting() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""baz/\r\npong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/baz/pong/""); assertThat(request.body()).isNull(); } "," @Test public void getWithEncodedPathStillPreventsRequestSplitting() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""baz/\r\npong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/baz/pong/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " } "," @Test public void pathParametersAndPathTraversal() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"") String ping) { return null; } } assertMalformedRequest(Example.class, "".""); assertMalformedRequest(Example.class, ""..""); assertThat(buildRequest(Example.class, ""./a"").url().encodedPath()) .isEqualTo(""/foo/bar/.%2Fa/""); assertThat(buildRequest(Example.class, ""a/."").url().encodedPath()) .isEqualTo(""/foo/bar/a%2F./""); assertThat(buildRequest(Example.class, ""a/.."").url().encodedPath()) .isEqualTo(""/foo/bar/a%2F../""); assertThat(buildRequest(Example.class, ""../a"").url().encodedPath()) .isEqualTo(""/foo/bar/..%2Fa/""); assertThat(buildRequest(Example.class, ""..\\.."").url().encodedPath()) .isEqualTo(""/foo/bar/..%5C../""); assertThat(buildRequest(Example.class, ""%2E"").url().encodedPath()) .isEqualTo(""/foo/bar/%252E/""); assertThat(buildRequest(Example.class, ""%2E%2E"").url().encodedPath()) .isEqualTo(""/foo/bar/%252E%252E/""); } ",TRUE,RequestFactoryTest.java " } "," @Test public void encodedPathParametersAndPathTraversal() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } assertMalformedRequest(Example.class, "".""); assertMalformedRequest(Example.class, ""%2E""); assertMalformedRequest(Example.class, ""%2e""); assertMalformedRequest(Example.class, ""..""); assertMalformedRequest(Example.class, ""%2E.""); assertMalformedRequest(Example.class, ""%2e.""); assertMalformedRequest(Example.class, "".%2E""); assertMalformedRequest(Example.class, "".%2e""); assertMalformedRequest(Example.class, ""%2E%2e""); assertMalformedRequest(Example.class, ""%2e%2E""); assertMalformedRequest(Example.class, ""./a""); assertMalformedRequest(Example.class, ""a/.""); assertMalformedRequest(Example.class, ""../a""); assertMalformedRequest(Example.class, ""a/..""); assertMalformedRequest(Example.class, ""a/../b""); assertMalformedRequest(Example.class, ""a/%2e%2E/b""); assertThat(buildRequest(Example.class, ""..."").url().encodedPath()) .isEqualTo(""/foo/bar/.../""); assertThat(buildRequest(Example.class, ""a..b"").url().encodedPath()) .isEqualTo(""/foo/bar/a..b/""); assertThat(buildRequest(Example.class, ""a.."").url().encodedPath()) .isEqualTo(""/foo/bar/a../""); assertThat(buildRequest(Example.class, ""a..b"").url().encodedPath()) .isEqualTo(""/foo/bar/a..b/""); assertThat(buildRequest(Example.class, ""..b"").url().encodedPath()) .isEqualTo(""/foo/bar/..b/""); assertThat(buildRequest(Example.class, ""..\\.."").url().encodedPath()) .isEqualTo(""/foo/bar/..%5C../""); } ",TRUE,RequestFactoryTest.java " } "," @Test public void dotDotsOkayWhenNotFullPathSegment() { class Example { @GET(""/foo{ping}bar/"") // Call method(@Path(value = ""ping"", encoded = true) String ping) { return null; } } assertMalformedRequest(Example.class, ""/./""); assertMalformedRequest(Example.class, ""/../""); assertThat(buildRequest(Example.class, ""."").url().encodedPath()).isEqualTo(""/foo.bar/""); assertThat(buildRequest(Example.class, "".."").url().encodedPath()).isEqualTo(""/foo..bar/""); } ",TRUE,RequestFactoryTest.java " @Test public void pathParamRequired() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(""Path parameter \""ping\"" value must not be null.""); } } "," @Test public void pathParamRequired() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(""Path parameter \""ping\"" value must not be null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryParam() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?ping=pong""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryParam() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?ping=pong""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithEncodedQueryParam() { class Example { @GET(""/foo/bar/"") // Call method(@Query(value = ""pi%20ng"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""p%20o%20n%20g""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?pi%20ng=p%20o%20n%20g""); assertThat(request.body()).isNull(); } "," @Test public void getWithEncodedQueryParam() { class Example { @GET(""/foo/bar/"") // Call method(@Query(value = ""pi%20ng"", encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""p%20o%20n%20g""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?pi%20ng=p%20o%20n%20g""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void queryParamOptionalOmitsQuery() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); } "," @Test public void queryParamOptionalOmitsQuery() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); } ",FALSE,RequestFactoryTest.java " @Test public void queryParamOptional() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""foo"") String foo, @Query(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""bar"", null, ""kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?foo=bar&kit=kat""); } "," @Test public void queryParamOptional() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""foo"") String foo, @Query(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""bar"", null, ""kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?foo=bar&kit=kat""); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryUrlAndParam() { class Example { @GET(""/foo/bar/?hi=mom"") // Call method(@Query(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?hi=mom&ping=pong""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryUrlAndParam() { class Example { @GET(""/foo/bar/?hi=mom"") // Call method(@Query(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?hi=mom&ping=pong""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQuery() { class Example { @GET(""/foo/bar/?hi=mom"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?hi=mom""); assertThat(request.body()).isNull(); } "," @Test public void getWithQuery() { class Example { @GET(""/foo/bar/?hi=mom"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?hi=mom""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithPathAndQueryParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit, @Query(""riff"") String riff) { return null; } } Request request = buildRequest(Example.class, ""pong"", ""kat"", ""raff""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/?kit=kat&riff=raff""); assertThat(request.body()).isNull(); } "," @Test public void getWithPathAndQueryParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit, @Query(""riff"") String riff) { return null; } } Request request = buildRequest(Example.class, ""pong"", ""kat"", ""raff""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/?kit=kat&riff=raff""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryThenPathThrows() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Query(""kit"") String kit, @Path(""ping"") String ping) { return null; } } try { buildRequest(Example.class, ""kat"", ""pong""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Path parameter must not come after a @Query. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithQueryThenPathThrows() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Query(""kit"") String kit, @Path(""ping"") String ping) { return null; } } try { buildRequest(Example.class, ""kat"", ""pong""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Path parameter must not come after a @Query. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryNameThenPathThrows() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@QueryName String kit, @Path(""ping"") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, ""kat"", ""pong""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Path parameter must not come after a @QueryName. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithQueryNameThenPathThrows() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@QueryName String kit, @Path(""ping"") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, ""kat"", ""pong""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Path parameter must not come after a @QueryName. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryMapThenPathThrows() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@QueryMap Map queries, @Path(""ping"") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap(""kit"", ""kat""), ""pong""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Path parameter must not come after a @QueryMap. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithQueryMapThenPathThrows() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@QueryMap Map queries, @Path(""ping"") String ping) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap(""kit"", ""kat""), ""pong""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Path parameter must not come after a @QueryMap. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithPathAndQueryQuestionMarkParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""pong?"", ""kat?""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()) .isEqualTo(""http://example.com/foo/bar/pong%3F/?kit=kat%3F""); assertThat(request.body()).isNull(); } "," @Test public void getWithPathAndQueryQuestionMarkParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""pong?"", ""kat?""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()) .isEqualTo(""http://example.com/foo/bar/pong%3F/?kit=kat%3F""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithPathAndQueryAmpersandParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""pong&"", ""kat&""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong&/?kit=kat%26""); assertThat(request.body()).isNull(); } "," @Test public void getWithPathAndQueryAmpersandParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""pong&"", ""kat&""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong&/?kit=kat%26""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithPathAndQueryHashParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""pong#"", ""kat#""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong%23/?kit=kat%23""); assertThat(request.body()).isNull(); } "," @Test public void getWithPathAndQueryHashParam() { class Example { @GET(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Query(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""pong#"", ""kat#""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong%23/?kit=kat%23""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryParamList() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""key"") List keys) { return null; } } List values = Arrays.asList(1, 2, null, ""three"", ""1""); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?key=1&key=2&key=three&key=1""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryParamList() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""key"") List keys) { return null; } } List values = Arrays.asList(1, 2, null, ""three"", ""1""); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?key=1&key=2&key=three&key=1""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryParamArray() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""key"") Object[] keys) { return null; } } Object[] values = { 1, 2, null, ""three"", ""1"" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?key=1&key=2&key=three&key=1""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryParamArray() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""key"") Object[] keys) { return null; } } Object[] values = { 1, 2, null, ""three"", ""1"" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?key=1&key=2&key=three&key=1""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryParamPrimitiveArray() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""key"") int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?key=1&key=2&key=3&key=1""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryParamPrimitiveArray() { class Example { @GET(""/foo/bar/"") // Call method(@Query(""key"") int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?key=1&key=2&key=3&key=1""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryNameParam() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?pong""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryNameParam() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, ""pong""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?pong""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithEncodedQueryNameParam() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName(encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""p%20o%20n%20g""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?p%20o%20n%20g""); assertThat(request.body()).isNull(); } "," @Test public void getWithEncodedQueryNameParam() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName(encoded = true) String ping) { return null; } } Request request = buildRequest(Example.class, ""p%20o%20n%20g""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?p%20o%20n%20g""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void queryNameParamOptionalOmitsQuery() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); } "," @Test public void queryNameParamOptionalOmitsQuery() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName String ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { null }); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryNameParamList() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName List keys) { return null; } } List values = Arrays.asList(1, 2, null, ""three"", ""1""); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?1&2&three&1""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryNameParamList() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName List keys) { return null; } } List values = Arrays.asList(1, 2, null, ""three"", ""1""); Request request = buildRequest(Example.class, values); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?1&2&three&1""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryNameParamArray() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName Object[] keys) { return null; } } Object[] values = { 1, 2, null, ""three"", ""1"" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?1&2&three&1""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryNameParamArray() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName Object[] keys) { return null; } } Object[] values = { 1, 2, null, ""three"", ""1"" }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?1&2&three&1""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryNameParamPrimitiveArray() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?1&2&3&1""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryNameParamPrimitiveArray() { class Example { @GET(""/foo/bar/"") // Call method(@QueryName int[] keys) { return null; } } int[] values = { 1, 2, 3, 1 }; Request request = buildRequest(Example.class, new Object[] { values }); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?1&2&3&1""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryParamMap() { class Example { @GET(""/foo/bar/"") // Call method(@QueryMap Map query) { return null; } } Map params = new LinkedHashMap<>(); params.put(""kit"", ""kat""); params.put(""ping"", ""pong""); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?kit=kat&ping=pong""); assertThat(request.body()).isNull(); } "," @Test public void getWithQueryParamMap() { class Example { @GET(""/foo/bar/"") // Call method(@QueryMap Map query) { return null; } } Map params = new LinkedHashMap<>(); params.put(""kit"", ""kat""); params.put(""ping"", ""pong""); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?kit=kat&ping=pong""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithEncodedQueryParamMap() { class Example { @GET(""/foo/bar/"") // Call method(@QueryMap(encoded = true) Map query) { return null; } } Map params = new LinkedHashMap<>(); params.put(""kit"", ""k%20t""); params.put(""pi%20ng"", ""p%20g""); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?kit=k%20t&pi%20ng=p%20g""); assertThat(request.body()).isNull(); } "," @Test public void getWithEncodedQueryParamMap() { class Example { @GET(""/foo/bar/"") // Call method(@QueryMap(encoded = true) Map query) { return null; } } Map params = new LinkedHashMap<>(); params.put(""kit"", ""k%20t""); params.put(""pi%20ng"", ""p%20g""); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?kit=k%20t&pi%20ng=p%20g""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getAbsoluteUrl() { class Example { @GET(""http://example2.com/foo/bar/"") Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example2.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void getAbsoluteUrl() { class Example { @GET(""http://example2.com/foo/bar/"") Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example2.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithStringUrl() { class Example { @GET Call method(@Url String url) { return null; } } Request request = buildRequest(Example.class, ""foo/bar/""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void getWithStringUrl() { class Example { @GET Call method(@Url String url) { return null; } } Request request = buildRequest(Example.class, ""foo/bar/""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithJavaUriUrl() { class Example { @GET Call method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create(""foo/bar/"")); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void getWithJavaUriUrl() { class Example { @GET Call method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create(""foo/bar/"")); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithStringUrlAbsolute() { class Example { @GET Call method(@Url String url) { return null; } } Request request = buildRequest(Example.class, ""https://example2.com/foo/bar/""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""https://example2.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void getWithStringUrlAbsolute() { class Example { @GET Call method(@Url String url) { return null; } } Request request = buildRequest(Example.class, ""https://example2.com/foo/bar/""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""https://example2.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithJavaUriUrlAbsolute() { class Example { @GET Call method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create(""https://example2.com/foo/bar/"")); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""https://example2.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void getWithJavaUriUrlAbsolute() { class Example { @GET Call method(@Url URI url) { return null; } } Request request = buildRequest(Example.class, URI.create(""https://example2.com/foo/bar/"")); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""https://example2.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithUrlAbsoluteSameHost() { class Example { @GET Call method(@Url String url) { return null; } } Request request = buildRequest(Example.class, ""http://example.com/foo/bar/""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void getWithUrlAbsoluteSameHost() { class Example { @GET Call method(@Url String url) { return null; } } Request request = buildRequest(Example.class, ""http://example.com/foo/bar/""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithHttpUrl() { class Example { @GET Call method(@Url HttpUrl url) { return null; } } Request request = buildRequest(Example.class, HttpUrl.get(""http://example.com/foo/bar/"")); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url()).isEqualTo(HttpUrl.get(""http://example.com/foo/bar/"")); assertThat(request.body()).isNull(); } "," @Test public void getWithHttpUrl() { class Example { @GET Call method(@Url HttpUrl url) { return null; } } Request request = buildRequest(Example.class, HttpUrl.get(""http://example.com/foo/bar/"")); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url()).isEqualTo(HttpUrl.get(""http://example.com/foo/bar/"")); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void getWithNullUrl() { class Example { @GET Call method(@Url HttpUrl url) { return null; } } try { buildRequest(Example.class, (HttpUrl) null); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage(""@Url parameter is null.""); } } "," @Test public void getWithNullUrl() { class Example { @GET Call method(@Url HttpUrl url) { return null; } } try { buildRequest(Example.class, (HttpUrl) null); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage(""@Url parameter is null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithNonStringUrlThrows() { class Example { @GET Call method(@Url Object url) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type."" + "" (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void getWithNonStringUrlThrows() { class Example { @GET Call method(@Url Object url) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type."" + "" (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getUrlAndUrlParamThrows() { class Example { @GET(""foo/bar"") Call method(@Url Object url) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""@Url cannot be used with @GET URL (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void getUrlAndUrlParamThrows() { class Example { @GET(""foo/bar"") Call method(@Url Object url) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""@Url cannot be used with @GET URL (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithoutUrlThrows() { class Example { @GET Call method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Missing either @GET URL or @Url parameter.\n"" + "" for method Example.method""); } } "," @Test public void getWithoutUrlThrows() { class Example { @GET Call method() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Missing either @GET URL or @Url parameter.\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithUrlThenPathThrows() { class Example { @GET Call method(@Url String url, @Path(""hey"") String hey) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""@Path parameters may not be used with @Url. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithUrlThenPathThrows() { class Example { @GET Call method(@Url String url, @Path(""hey"") String hey) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""@Path parameters may not be used with @Url. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithPathThenUrlThrows() { class Example { @GET Call method(@Path(""hey"") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""@Path can only be used with relative url on @GET (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void getWithPathThenUrlThrows() { class Example { @GET Call method(@Path(""hey"") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, ""foo/bar""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""@Path can only be used with relative url on @GET (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryThenUrlThrows() { class Example { @GET(""foo/bar"") Call method(@Query(""hey"") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, ""hey"", ""foo/bar/""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Url parameter must not come after a @Query. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithQueryThenUrlThrows() { class Example { @GET(""foo/bar"") Call method(@Query(""hey"") String hey, @Url Object url) { return null; } } try { buildRequest(Example.class, ""hey"", ""foo/bar/""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Url parameter must not come after a @Query. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryNameThenUrlThrows() { class Example { @GET Call method(@QueryName String name, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap(""kit"", ""kat""), ""foo/bar/""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Url parameter must not come after a @QueryName. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithQueryNameThenUrlThrows() { class Example { @GET Call method(@QueryName String name, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap(""kit"", ""kat""), ""foo/bar/""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Url parameter must not come after a @QueryName. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithQueryMapThenUrlThrows() { class Example { @GET Call method(@QueryMap Map queries, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap(""kit"", ""kat""), ""foo/bar/""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Url parameter must not come after a @QueryMap. (parameter #2)\n"" + "" for method Example.method""); } } "," @Test public void getWithQueryMapThenUrlThrows() { class Example { @GET Call method(@QueryMap Map queries, @Url String url) { throw new AssertionError(); } } try { buildRequest(Example.class, Collections.singletonMap(""kit"", ""kat""), ""foo/bar/""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""A @Url parameter must not come after a @QueryMap. (parameter #2)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void getWithUrlThenQuery() { class Example { @GET Call method(@Url String url, @Query(""hey"") String hey) { return null; } } Request request = buildRequest(Example.class, ""foo/bar/"", ""hey!""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?hey=hey%21""); } "," @Test public void getWithUrlThenQuery() { class Example { @GET Call method(@Url String url, @Query(""hey"") String hey) { return null; } } Request request = buildRequest(Example.class, ""foo/bar/"", ""hey!""); assertThat(request.method()).isEqualTo(""GET""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/?hey=hey%21""); } ",FALSE,RequestFactoryTest.java " @Test public void postWithUrl() { class Example { @POST Call method(@Url String url, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, ""http://example.com/foo/bar"", body); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar""); assertBody(request.body(), ""hi""); } "," @Test public void postWithUrl() { class Example { @POST Call method(@Url String url, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, ""http://example.com/foo/bar"", body); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar""); assertBody(request.body(), ""hi""); } ",FALSE,RequestFactoryTest.java " @Test public void normalPostWithPathParam() { class Example { @POST(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""Hi!""); Request request = buildRequest(Example.class, ""pong"", body); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/""); assertBody(request.body(), ""Hi!""); } "," @Test public void normalPostWithPathParam() { class Example { @POST(""/foo/bar/{ping}/"") // Call method(@Path(""ping"") String ping, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""Hi!""); Request request = buildRequest(Example.class, ""pong"", body); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/""); assertBody(request.body(), ""Hi!""); } ",FALSE,RequestFactoryTest.java " @Test public void emptyBody() { class Example { @POST(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), """"); } "," @Test public void emptyBody() { class Example { @POST(""/foo/bar/"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), """"); } ",FALSE,RequestFactoryTest.java " @Test public void customMethodEmptyBody() { class Example { @HTTP(method = ""CUSTOM"", path = ""/foo/bar/"", hasBody = true) // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""CUSTOM""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), """"); } "," @Test public void customMethodEmptyBody() { class Example { @HTTP(method = ""CUSTOM"", path = ""/foo/bar/"", hasBody = true) // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""CUSTOM""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertBody(request.body(), """"); } ",FALSE,RequestFactoryTest.java " @Test public void bodyRequired() { class Example { @POST(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(""Body parameter value must not be null.""); } } "," @Test public void bodyRequired() { class Example { @POST(""/foo/bar/"") // Call method(@Body RequestBody body) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo(""Body parameter value must not be null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void bodyWithPathParams() { class Example { @POST(""/foo/bar/{ping}/{kit}/"") // Call method(@Path(""ping"") String ping, @Body RequestBody body, @Path(""kit"") String kit) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""Hi!""); Request request = buildRequest(Example.class, ""pong"", body, ""kat""); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/kat/""); assertBody(request.body(), ""Hi!""); } "," @Test public void bodyWithPathParams() { class Example { @POST(""/foo/bar/{ping}/{kit}/"") // Call method(@Path(""ping"") String ping, @Body RequestBody body, @Path(""kit"") String kit) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""Hi!""); Request request = buildRequest(Example.class, ""pong"", body, ""kat""); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/pong/kat/""); assertBody(request.body(), ""Hi!""); } ",FALSE,RequestFactoryTest.java " @Test public void simpleMultipart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") String ping, @Part(""kit"") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, ""pong"", RequestBody.create( TEXT_PLAIN, ""kat"")); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""\r\nkat\r\n--""); } "," @Test public void simpleMultipart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") String ping, @Part(""kit"") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, ""pong"", RequestBody.create( TEXT_PLAIN, ""kat"")); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartArray() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") String[] ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { new String[] { ""pong1"", ""pong2"" } }); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong1\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\"""") .contains(""\r\npong2\r\n--""); } "," @Test public void multipartArray() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") String[] ping) { return null; } } Request request = buildRequest(Example.class, new Object[] { new String[] { ""pong1"", ""pong2"" } }); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong1\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\"""") .contains(""\r\npong2\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartRequiresName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part RequestBody part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartRequiresName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part RequestBody part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartIterableRequiresName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part List part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartIterableRequiresName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part List part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartArrayRequiresName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part RequestBody[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartArrayRequiresName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part RequestBody[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartOkHttpPartForbidsName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""name"") MultipartBody.Part part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartOkHttpPartForbidsName() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""name"") MultipartBody.Part part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartOkHttpPart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData(""kit"", ""kat""); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""\r\n"") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartOkHttpPart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData(""kit"", ""kat""); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""\r\n"") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartOkHttpIterablePart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part List part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData(""foo"", ""bar""); MultipartBody.Part part2 = MultipartBody.Part.createFormData(""kit"", ""kat""); Request request = buildRequest(Example.class, Arrays.asList(part1, part2)); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""foo\""\r\n"") .contains(""\r\nbar\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""\r\n"") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartOkHttpIterablePart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part List part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData(""foo"", ""bar""); MultipartBody.Part part2 = MultipartBody.Part.createFormData(""kit"", ""kat""); Request request = buildRequest(Example.class, Arrays.asList(part1, part2)); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""foo\""\r\n"") .contains(""\r\nbar\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""\r\n"") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartOkHttpArrayPart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part MultipartBody.Part[] part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData(""foo"", ""bar""); MultipartBody.Part part2 = MultipartBody.Part.createFormData(""kit"", ""kat""); Request request = buildRequest(Example.class, new Object[] { new MultipartBody.Part[] { part1, part2 } }); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""foo\""\r\n"") .contains(""\r\nbar\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""\r\n"") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartOkHttpArrayPart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part MultipartBody.Part[] part) { return null; } } MultipartBody.Part part1 = MultipartBody.Part.createFormData(""foo"", ""bar""); MultipartBody.Part part2 = MultipartBody.Part.createFormData(""kit"", ""kat""); Request request = buildRequest(Example.class, new Object[] { new MultipartBody.Part[] { part1, part2 } }); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""foo\""\r\n"") .contains(""\r\nbar\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""\r\n"") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartOkHttpPartWithFilename() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData(""kit"", ""kit.txt"", RequestBody.create(null, ""kat"")); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""; filename=\""kit.txt\""\r\n"") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartOkHttpPartWithFilename() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part MultipartBody.Part part) { return null; } } MultipartBody.Part part = MultipartBody.Part.createFormData(""kit"", ""kit.txt"", RequestBody.create(null, ""kat"")); Request request = buildRequest(Example.class, part); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\""; filename=\""kit.txt\""\r\n"") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartIterable() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") List ping) { return null; } } Request request = buildRequest(Example.class, Arrays.asList(""pong1"", ""pong2"")); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong1\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\"""") .contains(""\r\npong2\r\n--""); } "," @Test public void multipartIterable() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") List ping) { return null; } } Request request = buildRequest(Example.class, Arrays.asList(""pong1"", ""pong2"")); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong1\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\"""") .contains(""\r\npong2\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartIterableOkHttpPart() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") List part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartIterableOkHttpPart() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") List part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartArrayOkHttpPart() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") MultipartBody.Part[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartArrayOkHttpPart() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") MultipartBody.Part[] part) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@Part parameters using the MultipartBody.Part must not include a part name in the annotation. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartWithEncoding() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(value = ""ping"", encoding = ""8-bit"") String ping, @Part(value = ""kit"", encoding = ""7-bit"") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, ""pong"", RequestBody.create( TEXT_PLAIN, ""kat"")); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""Content-Transfer-Encoding: 8-bit"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""Content-Transfer-Encoding: 7-bit"") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartWithEncoding() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(value = ""ping"", encoding = ""8-bit"") String ping, @Part(value = ""kit"", encoding = ""7-bit"") RequestBody kit) { return null; } } Request request = buildRequest(Example.class, ""pong"", RequestBody.create( TEXT_PLAIN, ""kat"")); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""Content-Transfer-Encoding: 8-bit"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""Content-Transfer-Encoding: 7-bit"") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMap() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(""kit"", RequestBody.create(null, ""kat"")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartPartMap() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(""kit"", RequestBody.create(null, ""kat"")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapWithEncoding() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap(encoding = ""8-bit"") Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(""kit"", RequestBody.create(null, ""kat"")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""Content-Transfer-Encoding: 8-bit"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""Content-Transfer-Encoding: 8-bit"") .contains(""\r\nkat\r\n--""); } "," @Test public void multipartPartMapWithEncoding() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap(encoding = ""8-bit"") Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(""kit"", RequestBody.create(null, ""kat"")); Request request = buildRequest(Example.class, params); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\""\r\n"") .contains(""Content-Transfer-Encoding: 8-bit"") .contains(""\r\npong\r\n--""); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""kit\"""") .contains(""Content-Transfer-Encoding: 8-bit"") .contains(""\r\nkat\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapRejectsNonStringKeys() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@PartMap keys must be of type String: class java.lang.Object (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartPartMapRejectsNonStringKeys() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@PartMap keys must be of type String: class java.lang.Object (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapRejectsOkHttpPartValues() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@PartMap values cannot be MultipartBody.Part. Use @Part List or a different value type instead. (parameter #1)\n"" + "" for method Example.method""); } } "," @Test public void multipartPartMapRejectsOkHttpPartValues() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@PartMap values cannot be MultipartBody.Part. Use @Part List or a different value type instead. (parameter #1)\n"" + "" for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapRejectsNull() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Part map was null.""); } } "," @Test public void multipartPartMapRejectsNull() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Part map was null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapRejectsNullKeys() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(null, RequestBody.create(null, ""kat"")); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Part map contained null key.""); } } "," @Test public void multipartPartMapRejectsNullKeys() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(null, RequestBody.create(null, ""kat"")); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Part map contained null key.""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapRejectsNullValues() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(""kit"", null); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Part map contained null value for key 'kit'.""); } } "," @Test public void multipartPartMapRejectsNullValues() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Map parts) { return null; } } Map params = new LinkedHashMap<>(); params.put(""ping"", RequestBody.create(null, ""pong"")); params.put(""kit"", null); try { buildRequest(Example.class, params); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Part map contained null value for key 'kit'.""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapMustBeMap() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap List parts) { return null; } } try { buildRequest(Example.class, Collections.emptyList()); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@PartMap parameter type must be Map. (parameter #1)\n for method Example.method""); } } "," @Test public void multipartPartMapMustBeMap() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap List parts) { return null; } } try { buildRequest(Example.class, Collections.emptyList()); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@PartMap parameter type must be Map. (parameter #1)\n for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartMapSupportsSubclasses() throws IOException { class Foo extends HashMap { } class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Foo parts) { return null; } } Foo foo = new Foo(); foo.put(""hello"", ""world""); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()) .contains(""name=\""hello\"""") .contains(""\r\n\r\nworld\r\n--""); } "," @Test public void multipartPartMapSupportsSubclasses() throws IOException { class Foo extends HashMap { } class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@PartMap Foo parts) { return null; } } Foo foo = new Foo(); foo.put(""hello"", ""world""); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()) .contains(""name=\""hello\"""") .contains(""\r\n\r\nworld\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartNullRemovesPart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") String ping, @Part(""fizz"") String fizz) { return null; } } Request request = buildRequest(Example.class, ""pong"", null); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\"""") .contains(""\r\npong\r\n--""); } "," @Test public void multipartNullRemovesPart() throws IOException { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") String ping, @Part(""fizz"") String fizz) { return null; } } Request request = buildRequest(Example.class, ""pong"", null); assertThat(request.method()).isEqualTo(""POST""); assertThat(request.headers().size()).isZero(); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); RequestBody body = request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String bodyString = buffer.readUtf8(); assertThat(bodyString) .contains(""Content-Disposition: form-data;"") .contains(""name=\""ping\"""") .contains(""\r\npong\r\n--""); } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartOptional() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") RequestBody ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo(""Multipart body must have at least one part.""); } } "," @Test public void multipartPartOptional() { class Example { @Multipart // @POST(""/foo/bar/"") // Call method(@Part(""ping"") RequestBody ping) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo(""Multipart body must have at least one part.""); } } ",FALSE,RequestFactoryTest.java " @Test public void simpleFormEncoded() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") String foo, @Field(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""bar"", ""pong""); assertBody(request.body(), ""foo=bar&ping=pong""); } "," @Test public void simpleFormEncoded() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") String foo, @Field(""ping"") String ping) { return null; } } Request request = buildRequest(Example.class, ""bar"", ""pong""); assertBody(request.body(), ""foo=bar&ping=pong""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedWithEncodedNameFieldParam() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(value = ""na%20me"", encoded = true) String foo) { return null; } } Request request = buildRequest(Example.class, ""ba%20r""); assertBody(request.body(), ""na%20me=ba%20r""); } "," @Test public void formEncodedWithEncodedNameFieldParam() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(value = ""na%20me"", encoded = true) String foo) { return null; } } Request request = buildRequest(Example.class, ""ba%20r""); assertBody(request.body(), ""na%20me=ba%20r""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedFieldOptional() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") String foo, @Field(""ping"") String ping, @Field(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""bar"", null, ""kat""); assertBody(request.body(), ""foo=bar&kit=kat""); } "," @Test public void formEncodedFieldOptional() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") String foo, @Field(""ping"") String ping, @Field(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""bar"", null, ""kat""); assertBody(request.body(), ""foo=bar&kit=kat""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedFieldList() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") List fields, @Field(""kit"") String kit) { return null; } } List values = Arrays.asList(""foo"", ""bar"", null, 3); Request request = buildRequest(Example.class, values, ""kat""); assertBody(request.body(), ""foo=foo&foo=bar&foo=3&kit=kat""); } "," @Test public void formEncodedFieldList() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") List fields, @Field(""kit"") String kit) { return null; } } List values = Arrays.asList(""foo"", ""bar"", null, 3); Request request = buildRequest(Example.class, values, ""kat""); assertBody(request.body(), ""foo=foo&foo=bar&foo=3&kit=kat""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedFieldArray() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") Object[] fields, @Field(""kit"") String kit) { return null; } } Object[] values = { 1, 2, null, ""three"" }; Request request = buildRequest(Example.class, values, ""kat""); assertBody(request.body(), ""foo=1&foo=2&foo=three&kit=kat""); } "," @Test public void formEncodedFieldArray() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") Object[] fields, @Field(""kit"") String kit) { return null; } } Object[] values = { 1, 2, null, ""three"" }; Request request = buildRequest(Example.class, values, ""kat""); assertBody(request.body(), ""foo=1&foo=2&foo=three&kit=kat""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedFieldPrimitiveArray() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") int[] fields, @Field(""kit"") String kit) { return null; } } int[] values = { 1, 2, 3 }; Request request = buildRequest(Example.class, values, ""kat""); assertBody(request.body(), ""foo=1&foo=2&foo=3&kit=kat""); } "," @Test public void formEncodedFieldPrimitiveArray() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@Field(""foo"") int[] fields, @Field(""kit"") String kit) { return null; } } int[] values = { 1, 2, 3 }; Request request = buildRequest(Example.class, values, ""kat""); assertBody(request.body(), ""foo=1&foo=2&foo=3&kit=kat""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedWithEncodedNameFieldParamMap() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@FieldMap(encoded = true) Map fieldMap) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""k%20it"", ""k%20at""); fieldMap.put(""pin%20g"", ""po%20ng""); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), ""k%20it=k%20at&pin%20g=po%20ng""); } "," @Test public void formEncodedWithEncodedNameFieldParamMap() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@FieldMap(encoded = true) Map fieldMap) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""k%20it"", ""k%20at""); fieldMap.put(""pin%20g"", ""po%20ng""); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), ""k%20it=k%20at&pin%20g=po%20ng""); } ",FALSE,RequestFactoryTest.java " @Test public void formEncodedFieldMap() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@FieldMap Map fieldMap) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""kit"", ""kat""); fieldMap.put(""ping"", ""pong""); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), ""kit=kat&ping=pong""); } "," @Test public void formEncodedFieldMap() { class Example { @FormUrlEncoded // @POST(""/foo"") // Call method(@FieldMap Map fieldMap) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""kit"", ""kat""); fieldMap.put(""ping"", ""pong""); Request request = buildRequest(Example.class, fieldMap); assertBody(request.body(), ""kit=kat&ping=pong""); } ",FALSE,RequestFactoryTest.java " @Test public void fieldMapRejectsNull() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Map a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Field map was null.""); } } "," @Test public void fieldMapRejectsNull() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Map a) { return null; } } try { buildRequest(Example.class, new Object[] { null }); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Field map was null.""); } } ",FALSE,RequestFactoryTest.java " @Test public void fieldMapRejectsNullKeys() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Map a) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""kit"", ""kat""); fieldMap.put(null, ""pong""); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Field map contained null key.""); } } "," @Test public void fieldMapRejectsNullKeys() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Map a) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""kit"", ""kat""); fieldMap.put(null, ""pong""); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Field map contained null key.""); } } ",FALSE,RequestFactoryTest.java " @Test public void fieldMapRejectsNullValues() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Map a) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""kit"", ""kat""); fieldMap.put(""foo"", null); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Field map contained null value for key 'foo'.""); } } "," @Test public void fieldMapRejectsNullValues() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Map a) { return null; } } Map fieldMap = new LinkedHashMap<>(); fieldMap.put(""kit"", ""kat""); fieldMap.put(""foo"", null); try { buildRequest(Example.class, fieldMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Field map contained null value for key 'foo'.""); } } ",FALSE,RequestFactoryTest.java " @Test public void fieldMapMustBeAMap() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap List a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@FieldMap parameter type must be Map. (parameter #1)\n for method Example.method""); } } "," @Test public void fieldMapMustBeAMap() { class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap List a) { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""@FieldMap parameter type must be Map. (parameter #1)\n for method Example.method""); } } ",FALSE,RequestFactoryTest.java " @Test public void fieldMapSupportsSubclasses() throws IOException { class Foo extends HashMap { } class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Foo a) { return null; } } Foo foo = new Foo(); foo.put(""hello"", ""world""); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(""hello=world""); } "," @Test public void fieldMapSupportsSubclasses() throws IOException { class Foo extends HashMap { } class Example { @FormUrlEncoded // @POST(""/"") // Call method(@FieldMap Foo a) { return null; } } Foo foo = new Foo(); foo.put(""hello"", ""world""); Request request = buildRequest(Example.class, foo); Buffer buffer = new Buffer(); request.body().writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(""hello=world""); } ",FALSE,RequestFactoryTest.java " @Test public void simpleHeaders() { class Example { @GET(""/foo/bar/"") @Headers({ ""ping: pong"", ""kit: kat"" }) Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get(""ping"")).isEqualTo(""pong""); assertThat(headers.get(""kit"")).isEqualTo(""kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void simpleHeaders() { class Example { @GET(""/foo/bar/"") @Headers({ ""ping: pong"", ""kit: kat"" }) Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get(""ping"")).isEqualTo(""pong""); assertThat(headers.get(""kit"")).isEqualTo(""kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void headersDoNotOverwriteEachOther() { class Example { @GET(""/foo/bar/"") @Headers({ ""ping: pong"", ""kit: kat"", ""kit: -kat"", }) Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(3); assertThat(headers.get(""ping"")).isEqualTo(""pong""); assertThat(headers.values(""kit"")).containsOnly(""kat"", ""-kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void headersDoNotOverwriteEachOther() { class Example { @GET(""/foo/bar/"") @Headers({ ""ping: pong"", ""kit: kat"", ""kit: -kat"", }) Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(3); assertThat(headers.get(""ping"")).isEqualTo(""pong""); assertThat(headers.values(""kit"")).containsOnly(""kat"", ""-kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void headerParamToString() { class Example { @GET(""/foo/bar/"") // Call method(@Header(""kit"") BigInteger kit) { return null; } } Request request = buildRequest(Example.class, new BigInteger(""1234"")); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(1); assertThat(headers.get(""kit"")).isEqualTo(""1234""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void headerParamToString() { class Example { @GET(""/foo/bar/"") // Call method(@Header(""kit"") BigInteger kit) { return null; } } Request request = buildRequest(Example.class, new BigInteger(""1234"")); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(1); assertThat(headers.get(""kit"")).isEqualTo(""1234""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void headerParam() { class Example { @GET(""/foo/bar/"") // @Headers(""ping: pong"") // Call method(@Header(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""kat""); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get(""ping"")).isEqualTo(""pong""); assertThat(headers.get(""kit"")).isEqualTo(""kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void headerParam() { class Example { @GET(""/foo/bar/"") // @Headers(""ping: pong"") // Call method(@Header(""kit"") String kit) { return null; } } Request request = buildRequest(Example.class, ""kat""); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.get(""ping"")).isEqualTo(""pong""); assertThat(headers.get(""kit"")).isEqualTo(""kat""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void headerParamList() { class Example { @GET(""/foo/bar/"") // Call method(@Header(""foo"") List kit) { return null; } } Request request = buildRequest(Example.class, Arrays.asList(""bar"", null, ""baz"")); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values(""foo"")).containsExactly(""bar"", ""baz""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void headerParamList() { class Example { @GET(""/foo/bar/"") // Call method(@Header(""foo"") List kit) { return null; } } Request request = buildRequest(Example.class, Arrays.asList(""bar"", null, ""baz"")); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values(""foo"")).containsExactly(""bar"", ""baz""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void headerParamArray() { class Example { @GET(""/foo/bar/"") // Call method(@Header(""foo"") String[] kit) { return null; } } Request request = buildRequest(Example.class, (Object) new String[] { ""bar"", null, ""baz"" }); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values(""foo"")).containsExactly(""bar"", ""baz""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } "," @Test public void headerParamArray() { class Example { @GET(""/foo/bar/"") // Call method(@Header(""foo"") String[] kit) { return null; } } Request request = buildRequest(Example.class, (Object) new String[] { ""bar"", null, ""baz"" }); assertThat(request.method()).isEqualTo(""GET""); okhttp3.Headers headers = request.headers(); assertThat(headers.size()).isEqualTo(2); assertThat(headers.values(""foo"")).containsExactly(""bar"", ""baz""); assertThat(request.url().toString()).isEqualTo(""http://example.com/foo/bar/""); assertThat(request.body()).isNull(); } ",FALSE,RequestFactoryTest.java " @Test public void contentTypeAnnotationHeaderOverrides() { class Example { @POST(""/"") // @Headers(""Content-Type: text/not-plain"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.body().contentType().toString()).isEqualTo(""text/not-plain""); } "," @Test public void contentTypeAnnotationHeaderOverrides() { class Example { @POST(""/"") // @Headers(""Content-Type: text/not-plain"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); Request request = buildRequest(Example.class, body); assertThat(request.body().contentType().toString()).isEqualTo(""text/not-plain""); } ",FALSE,RequestFactoryTest.java " @Test public void malformedContentTypeHeaderThrows() { class Example { @POST(""/"") // @Headers(""Content-Type: hello, world!"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); try { buildRequest(Example.class, body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Malformed content type: hello, world!\n"" + "" for method Example.method""); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } "," @Test public void malformedContentTypeHeaderThrows() { class Example { @POST(""/"") // @Headers(""Content-Type: hello, world!"") // Call method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); try { buildRequest(Example.class, body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Malformed content type: hello, world!\n"" + "" for method Example.method""); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } ",FALSE,RequestFactoryTest.java " @Test public void contentTypeAnnotationHeaderAddsHeaderWithNoBody() { class Example { @DELETE(""/"") // @Headers(""Content-Type: text/not-plain"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.headers().get(""Content-Type"")).isEqualTo(""text/not-plain""); } "," @Test public void contentTypeAnnotationHeaderAddsHeaderWithNoBody() { class Example { @DELETE(""/"") // @Headers(""Content-Type: text/not-plain"") // Call method() { return null; } } Request request = buildRequest(Example.class); assertThat(request.headers().get(""Content-Type"")).isEqualTo(""text/not-plain""); } ",FALSE,RequestFactoryTest.java " @Test public void contentTypeParameterHeaderOverrides() { class Example { @POST(""/"") // Call method(@Header(""Content-Type"") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""Plain""); Request request = buildRequest(Example.class, ""text/not-plain"", body); assertThat(request.body().contentType().toString()).isEqualTo(""text/not-plain""); } "," @Test public void contentTypeParameterHeaderOverrides() { class Example { @POST(""/"") // Call method(@Header(""Content-Type"") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""Plain""); Request request = buildRequest(Example.class, ""text/not-plain"", body); assertThat(request.body().contentType().toString()).isEqualTo(""text/not-plain""); } ",FALSE,RequestFactoryTest.java " @Test public void malformedContentTypeParameterThrows() { class Example { @POST(""/"") // Call method(@Header(""Content-Type"") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); try { buildRequest(Example.class, ""hello, world!"", body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Malformed content type: hello, world!""); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } "," @Test public void malformedContentTypeParameterThrows() { class Example { @POST(""/"") // Call method(@Header(""Content-Type"") String contentType, @Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, ""hi""); try { buildRequest(Example.class, ""hello, world!"", body); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(""Malformed content type: hello, world!""); assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); // OkHttp's cause. } } ",FALSE,RequestFactoryTest.java " @Test public void malformedAnnotationRelativeUrlThrows() { class Example { @GET(""ftp://example.org"") Call get() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""Malformed URL. Base: http://example.com/, Relative: ftp://example.org""); } } "," @Test public void malformedAnnotationRelativeUrlThrows() { class Example { @GET(""ftp://example.org"") Call get() { return null; } } try { buildRequest(Example.class); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""Malformed URL. Base: http://example.com/, Relative: ftp://example.org""); } } ",FALSE,RequestFactoryTest.java " @Test public void malformedParameterRelativeUrlThrows() { class Example { @GET Call get(@Url String relativeUrl) { return null; } } try { buildRequest(Example.class, ""ftp://example.org""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""Malformed URL. Base: http://example.com/, Relative: ftp://example.org""); } } "," @Test public void malformedParameterRelativeUrlThrows() { class Example { @GET Call get(@Url String relativeUrl) { return null; } } try { buildRequest(Example.class, ""ftp://example.org""); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage( ""Malformed URL. Base: http://example.com/, Relative: ftp://example.org""); } } ",FALSE,RequestFactoryTest.java " @Test public void multipartPartsShouldBeInOrder() throws IOException { class Example { @Multipart @POST(""/foo"") Call get(@Part(""first"") String data, @Part(""second"") String dataTwo, @Part(""third"") String dataThree) { return null; } } Request request = buildRequest(Example.class, ""firstParam"", ""secondParam"", ""thirdParam""); MultipartBody body = (MultipartBody) request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String readBody = buffer.readUtf8(); assertThat(readBody.indexOf(""firstParam"")).isLessThan(readBody.indexOf(""secondParam"")); assertThat(readBody.indexOf(""secondParam"")).isLessThan(readBody.indexOf(""thirdParam"")); } "," @Test public void multipartPartsShouldBeInOrder() throws IOException { class Example { @Multipart @POST(""/foo"") Call get(@Part(""first"") String data, @Part(""second"") String dataTwo, @Part(""third"") String dataThree) { return null; } } Request request = buildRequest(Example.class, ""firstParam"", ""secondParam"", ""thirdParam""); MultipartBody body = (MultipartBody) request.body(); Buffer buffer = new Buffer(); body.writeTo(buffer); String readBody = buffer.readUtf8(); assertThat(readBody.indexOf(""firstParam"")).isLessThan(readBody.indexOf(""secondParam"")); assertThat(readBody.indexOf(""secondParam"")).isLessThan(readBody.indexOf(""thirdParam"")); } ",FALSE,RequestFactoryTest.java " @Test public void queryParamsSkippedIfConvertedToNull() throws Exception { class Example { @GET(""/query"") Call queryPath(@Query(""a"") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, ""Ignored""); assertThat(request.url().toString()).doesNotContain(""Ignored""); } "," @Test public void queryParamsSkippedIfConvertedToNull() throws Exception { class Example { @GET(""/query"") Call queryPath(@Query(""a"") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, ""Ignored""); assertThat(request.url().toString()).doesNotContain(""Ignored""); } ",FALSE,RequestFactoryTest.java " @Test public void queryParamMapsConvertedToNullShouldError() throws Exception { class Example { @GET(""/query"") Call queryPath(@QueryMap Map a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Map queryMap = Collections.singletonMap(""kit"", ""kat""); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( ""Query map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'.""); } } "," @Test public void queryParamMapsConvertedToNullShouldError() throws Exception { class Example { @GET(""/query"") Call queryPath(@QueryMap Map a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Map queryMap = Collections.singletonMap(""kit"", ""kat""); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( ""Query map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'.""); } } ",FALSE,RequestFactoryTest.java " @Test public void fieldParamsSkippedIfConvertedToNull() throws Exception { class Example { @FormUrlEncoded @POST(""/query"") Call queryPath(@Field(""a"") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, ""Ignored""); assertThat(request.url().toString()).doesNotContain(""Ignored""); } "," @Test public void fieldParamsSkippedIfConvertedToNull() throws Exception { class Example { @FormUrlEncoded @POST(""/query"") Call queryPath(@Field(""a"") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, ""Ignored""); assertThat(request.url().toString()).doesNotContain(""Ignored""); } ",FALSE,RequestFactoryTest.java " @Test public void fieldParamMapsConvertedToNullShouldError() throws Exception { class Example { @FormUrlEncoded @POST(""/query"") Call queryPath(@FieldMap Map a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Map queryMap = Collections.singletonMap(""kit"", ""kat""); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( ""Field map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'.""); } } "," @Test public void fieldParamMapsConvertedToNullShouldError() throws Exception { class Example { @FormUrlEncoded @POST(""/query"") Call queryPath(@FieldMap Map a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com"") .addConverterFactory(new NullObjectConverterFactory()); Map queryMap = Collections.singletonMap(""kit"", ""kat""); try { buildRequest(Example.class, retrofitBuilder, queryMap); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessageContaining( ""Field map value 'kat' converted to null by retrofit2.helpers.NullObjectConverterFactory$1 for key 'kit'.""); } } ",FALSE,RequestFactoryTest.java " private static void assertBody(RequestBody body, String expected) { assertThat(body).isNotNull(); Buffer buffer = new Buffer(); try { body.writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(expected); } catch (IOException e) { throw new RuntimeException(e); } } "," private static void assertBody(RequestBody body, String expected) { assertThat(body).isNotNull(); Buffer buffer = new Buffer(); try { body.writeTo(buffer); assertThat(buffer.readUtf8()).isEqualTo(expected); } catch (IOException e) { throw new RuntimeException(e); } } ",FALSE,RequestFactoryTest.java " static Request buildRequest(Class cls, Retrofit.Builder builder, Object... args) { okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() { @Override public okhttp3.Call newCall(Request request) { throw new UnsupportedOperationException(""Not implemented""); } }; Retrofit retrofit = builder.callFactory(callFactory).build(); Method method = TestingUtils.onlyMethod(cls); try { return RequestFactory.parseAnnotations(retrofit, method).create(args); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } } "," static Request buildRequest(Class cls, Retrofit.Builder builder, Object... args) { okhttp3.Call.Factory callFactory = new okhttp3.Call.Factory() { @Override public okhttp3.Call newCall(Request request) { throw new UnsupportedOperationException(""Not implemented""); } }; Retrofit retrofit = builder.callFactory(callFactory).build(); Method method = TestingUtils.onlyMethod(cls); try { return RequestFactory.parseAnnotations(retrofit, method).create(args); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new AssertionError(e); } } ",FALSE,RequestFactoryTest.java " static Request buildRequest(Class cls, Object... args) { Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com/"") .addConverterFactory(new ToStringConverterFactory()); return buildRequest(cls, retrofitBuilder, args); } "," static Request buildRequest(Class cls, Object... args) { Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(""http://example.com/"") .addConverterFactory(new ToStringConverterFactory()); return buildRequest(cls, retrofitBuilder, args); } ",FALSE,RequestFactoryTest.java " } "," static void assertMalformedRequest(Class cls, Object... args) { try { Request request = buildRequest(cls, args); fail(""expected a malformed request but was "" + request); } catch (IllegalArgumentException expected) { } } ",TRUE,RequestFactoryTest.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()).matcher((String) 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()).matcher((String) value).matches()) { addFieldError(fieldName, object); } } ",FALSE,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+)?"" + "")(((\\/+([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})*)?"" + ""$""; } } ",TRUE,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 " public void testAcceptNullValueForMutualExclusionOfValidators() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl1""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } "," public void testAcceptNullValueForMutualExclusionOfValidators() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl1""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } ",FALSE,URLValidatorTest.java " public void testInvalidEmptyValue() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl2""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } "," public void testInvalidEmptyValue() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl2""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } ",FALSE,URLValidatorTest.java " public void testInvalidValue() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl3""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertTrue(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertTrue(validator.getValidatorContext().hasFieldErrors()); } "," public void testInvalidValue() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl3""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertTrue(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertTrue(validator.getValidatorContext().hasFieldErrors()); } ",FALSE,URLValidatorTest.java " public void testValidUrl1() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl4""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } "," public void testValidUrl1() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl4""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } ",FALSE,URLValidatorTest.java " public void testValidUrl2() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl5""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } "," public void testValidUrl2() throws Exception { URLValidator validator = new URLValidator(); validator.setValidatorContext(new GenericValidatorContext(new Object())); validator.setFieldName(""testingUrl5""); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.validate(new MyObject()); assertFalse(validator.getValidatorContext().hasErrors()); assertFalse(validator.getValidatorContext().hasActionErrors()); assertFalse(validator.getValidatorContext().hasActionMessages()); assertFalse(validator.getValidatorContext().hasFieldErrors()); } ",FALSE,URLValidatorTest.java " public void testValidUrlWithRegex() throws Exception { URLValidator validator = new URLValidator(); validator.setUrlRegex(""^myapp:\\/\\/[a-z]*\\.com$""); Pattern pattern = Pattern.compile(validator.getUrlRegex()); assertTrue(pattern.matcher(""myapp://test.com"").matches()); assertFalse(pattern.matcher(""myap://test.com"").matches()); } "," public void testValidUrlWithRegex() throws Exception { URLValidator validator = new URLValidator(); validator.setUrlRegex(""^myapp:\\/\\/[a-z]*\\.com$""); Pattern pattern = Pattern.compile(validator.getUrlRegex()); assertTrue(pattern.matcher(""myapp://test.com"").matches()); assertFalse(pattern.matcher(""myap://test.com"").matches()); } ",FALSE,URLValidatorTest.java " public void testValidUrlWithRegexExpression() throws Exception { URLValidator validator = new URLValidator(); ActionContext.getContext().getValueStack().push(new MyAction()); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.setUrlRegexExpression(""${urlRegex}""); Pattern pattern = Pattern.compile(validator.getUrlRegex()); assertTrue(pattern.matcher(""myapp://test.com"").matches()); assertFalse(pattern.matcher(""myap://test.com"").matches()); } "," public void testValidUrlWithRegexExpression() throws Exception { URLValidator validator = new URLValidator(); ActionContext.getContext().getValueStack().push(new MyAction()); validator.setValueStack(ActionContext.getContext().getValueStack()); validator.setUrlRegexExpression(""${urlRegex}""); Pattern pattern = Pattern.compile(validator.getUrlRegex()); assertTrue(pattern.matcher(""myapp://test.com"").matches()); assertFalse(pattern.matcher(""myap://test.com"").matches()); } ",FALSE,URLValidatorTest.java " public void testValidUrlWithDefaultRegex() throws Exception { URLValidator validator = new URLValidator(); Pattern pattern = Pattern.compile(validator.getUrlRegex()); assertFalse(pattern.matcher(""myapp://test.com"").matches()); assertFalse(pattern.matcher(""myap://test.com"").matches()); assertFalse(pattern.matcher("""").matches()); assertFalse(pattern.matcher("" "").matches()); assertFalse(pattern.matcher(""no url"").matches()); assertTrue(pattern.matcher(""http://www.opensymphony.com"").matches()); assertTrue(pattern.matcher(""https://www.opensymphony.com"").matches()); assertTrue(pattern.matcher(""https://www.opensymphony.com:443/login"").matches()); assertTrue(pattern.matcher(""http://localhost:8080/myapp"").matches()); } "," public void testValidUrlWithDefaultRegex() throws Exception { URLValidator validator = new URLValidator(); Pattern pattern = Pattern.compile(validator.getUrlRegex()); assertFalse(pattern.matcher(""myapp://test.com"").matches()); assertFalse(pattern.matcher(""myap://test.com"").matches()); assertFalse(pattern.matcher("""").matches()); assertFalse(pattern.matcher("" "").matches()); assertFalse(pattern.matcher(""no url"").matches()); assertFalse(pattern.matcher(""http://example.com////////////////////////////////////////////////////////////////////////////////////??"").matches()); assertTrue(pattern.matcher(""http://www.opensymphony.com"").matches()); assertTrue(pattern.matcher(""https://www.opensymphony.com"").matches()); assertTrue(pattern.matcher(""https://www.opensymphony.com:443/login"").matches()); assertTrue(pattern.matcher(""http://localhost:8080/myapp"").matches()); } ",TRUE,URLValidatorTest.java " protected void setUp() throws Exception { super.setUp(); stack = ActionContext.getContext().getValueStack(); actionContext = ActionContext.getContext(); } "," protected void setUp() throws Exception { super.setUp(); stack = ActionContext.getContext().getValueStack(); actionContext = ActionContext.getContext(); } ",FALSE,URLValidatorTest.java " protected void tearDown() throws Exception { super.tearDown(); stack = null; actionContext = null; } "," protected void tearDown() throws Exception { super.tearDown(); stack = null; actionContext = null; } ",FALSE,URLValidatorTest.java " public String getTestingUrl1() { return null; } "," public String getTestingUrl1() { return null; } ",FALSE,URLValidatorTest.java " public String getTestingUrl2() { return """"; } "," public String getTestingUrl2() { return """"; } ",FALSE,URLValidatorTest.java " public String getTestingUrl3() { return ""sasdasd@asddd""; } "," public String getTestingUrl3() { return ""sasdasd@asddd""; } ",FALSE,URLValidatorTest.java " public String getTestingUrl4() { //return ""http://yahoo.com/""; return ""http://www.jroller.com1?qwe=qwe""; } "," public String getTestingUrl4() { //return ""http://yahoo.com/""; return ""http://www.jroller.com1?qwe=qwe""; } ",FALSE,URLValidatorTest.java " public String getTestingUrl5() { return ""http://yahoo.com/articles?id=123""; } "," public String getTestingUrl5() { return ""http://yahoo.com/articles?id=123""; } ",FALSE,URLValidatorTest.java " public String getUrlRegex() { return ""myapp:\\/\\/[a-z]*\\.com""; } "," public String getUrlRegex() { return ""myapp:\\/\\/[a-z]*\\.com""; } ",FALSE,URLValidatorTest.java " 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); } Map config = new HashMap<>(); config.put(""org.apache.johnzon.supports-comments"", true); jsonReaderFactory = Json.createReaderFactory(config); } "," 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); } Map config = new HashMap<>(); config.put(""org.apache.johnzon.supports-comments"", true); jsonReaderFactory = Json.createReaderFactory(config); } ",FALSE,XSSAPIImpl.java " protected void deactivate() { factory = null; jsonReaderFactory = null; } "," protected void deactivate() { factory = null; jsonReaderFactory = 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 (StringUtils.isNotEmpty(url)) { try { String unescapedURL = URLDecoder.decode(url, StandardCharsets.UTF_8.name()); /* StringEscapeUtils is deprecated starting with version 3.6 of commons-lang3, however the indicated replacement comes from commons-text, which is not an OSGi bundle */ unescapedURL = StringEscapeUtils.unescapeXml(unescapedURL); // 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 = unescapedURL.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; } } catch (UnsupportedEncodingException e) { LOGGER.error(""Unable to decode url: {}."", url); } } // fall through to empty string return """"; } "," public String getValidHref(final String url) { if (StringUtils.isNotEmpty(url)) { // 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 """"; } ",TRUE,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 { StringWriter output = new StringWriter(); Json.createGenerator(output).write(jsonReaderFactory.createReader(new StringReader(json)).readObject()).close(); return output.getBuffer().toString(); } catch (Exception e) { LOGGER.debug(""JSON validation failed: "" + e.getMessage(), e); } } else { try { StringWriter output = new StringWriter(); Json.createGenerator(output).write(jsonReaderFactory.createReader(new StringReader(json)).readArray()).close(); return output.getBuffer().toString(); } catch (Exception 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 { StringWriter output = new StringWriter(); Json.createGenerator(output).write(jsonReaderFactory.createReader(new StringReader(json)).readObject()).close(); return output.getBuffer().toString(); } catch (Exception e) { LOGGER.debug(""JSON validation failed: "" + e.getMessage(), e); } } else { try { StringWriter output = new StringWriter(); Json.createGenerator(output).write(jsonReaderFactory.createReader(new StringReader(json)).readArray()).close(); return output.getBuffer().toString(); } catch (Exception 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 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_""); } }); } 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_""); } }); } 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

""}, {"""", """"}, {"""", """"}, {""
  • 1
  • 2
"", ""
  • 1
  • 2
""}, {""günter"", ""günter""}, {""strike"", ""strike""}, {""s"", ""s""}, {""empty href"", ""empty href""}, {""space"",""space""}, {""
"", ""
""}, }; 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

""}, {"""", """"}, {"""", """"}, {""
  • 1
  • 2
"", ""
  • 1
  • 2
""}, {""günter"", ""günter""}, {""strike"", ""strike""}, {""s"", ""s""}, {""empty href"", ""empty href""}, {""space"",""space""}, {""
"", ""
""}, }; 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 // { ""/base?backHref=%26%23x6a%3b%26%23x61%3b%26%23x76%3b%26%23x61%3b%26%23x73%3b%26%23x63%3b%26%23x72%3b%26%23x69%3b%26%23x70%3b%26%23x74%3b%26%23x3a%3balert%281%29"", ""/base?backHref=javascript%3Aalert(1)"" }, { ""%26%23x6a%3b%26%23x61%3b%26%23x76%3b%26%23x61%3b%26%23x73%3b%26%23x63%3b%26%23x72%3b%26%23x69%3b%26%23x70%3b%26%23x74%3b%26%23x3a%3balert%281%29"", """" }, { ""javascript:alert(1)"", """" }, {""%2Fscripts%2Ftest.js"", ""/scripts/test.js""}, {""/etc/commerce/collections/中文"", ""/etc/commerce/collections/中文""}, {""/etc/commerce/collections/\u09aa\u09b0\u09c0\u0995\u09cd\u09b7\u09be\u09ae\u09c2\u09b2\u0995"", ""/etc/commerce/collections/\u09aa\u09b0\u09c0\u0995\u09cd\u09b7\u09be\u09ae\u09c2\u09b2\u0995""}, {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 + ""'""); } } } ",FALSE,XSSAPIImplTest.java " public SandboxTransformer() { super(CompilePhase.CANONICALIZATION); } "," public SandboxTransformer() { super(CompilePhase.CANONICALIZATION); } ",FALSE,SandboxTransformer.java " public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode) { if (classNode == null) { // TODO is this even possible? CpsTransformer implies it is not. return; } ClassCodeExpressionTransformer visitor = createVisitor(source, classNode); processConstructors(visitor, classNode); for (MethodNode m : classNode.getMethods()) { visitor.visitMethod(m); } for (Statement s : classNode.getObjectInitializerStatements()) { s.visit(visitor); } for (FieldNode f : classNode.getFields()) { visitor.visitField(f); } } "," public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode) { if (classNode == null) { // TODO is this even possible? CpsTransformer implies it is not. return; } ClassCodeExpressionTransformer visitor = createVisitor(source, classNode); processConstructors(visitor, classNode); for (MethodNode m : classNode.getMethods()) { forbidIfFinalizer(m); visitor.visitMethod(m); } for (Statement s : classNode.getObjectInitializerStatements()) { s.visit(visitor); } for (FieldNode f : classNode.getFields()) { visitor.visitField(f); } } ",TRUE,SandboxTransformer.java " } "," public void forbidIfFinalizer(MethodNode m) { if (m.getName().equals(""finalize"") && m.isVoidMethod() && !m.isPrivate() && !m.isStatic()) { boolean safe = false; // There must be at least one parameter without an initial expression for the method to be acceptable. for (Parameter p : m.getParameters()) { if (!p.hasInitialExpression()) { safe = true; break; } } if (!safe) { throw new SecurityException(""Sandboxed code may not override Object.finalize()""); } } } ",TRUE,SandboxTransformer.java " public void processConstructors(final ClassCodeExpressionTransformer visitor, ClassNode classNode) { ClassNode superClass = classNode.getSuperClass(); List declaredConstructors = classNode.getDeclaredConstructors(); if (TRIVIAL_CONSTRUCTORS.contains(superClass.getName())) { for (ConstructorNode c : declaredConstructors) { visitor.visitMethod(c); } } else { if (declaredConstructors.isEmpty()) { ConstructorNode syntheticConstructor = new ConstructorNode(Modifier.PUBLIC, new BlockStatement()); declaredConstructors = Collections.singletonList(syntheticConstructor); classNode.addConstructor(syntheticConstructor); } else { declaredConstructors = new ArrayList<>(declaredConstructors); } for (ConstructorNode c : declaredConstructors) { Statement code = c.getCode(); List body; if (code instanceof BlockStatement) { body = ((BlockStatement) code).getStatements(); } else { body = Collections.singletonList(code); } TupleExpression superArgs = new TupleExpression(); if (!body.isEmpty() && body.get(0) instanceof ExpressionStatement && ((ExpressionStatement) body.get(0)).getExpression() instanceof ConstructorCallExpression) { ConstructorCallExpression cce = (ConstructorCallExpression) ((ExpressionStatement) body.get(0)).getExpression(); if (cce.isThisCall()) { // these are fine as is visitor.visitMethod(c); continue; } else if (cce.isSuperCall()) { body = body.subList(1, body.size()); superArgs = ((TupleExpression) cce.getArguments()); } } List thisArgs = new ArrayList<>(); final TupleExpression _superArgs = superArgs; final AtomicReference superArgsTransformed = new AtomicReference<>(); ((ScopeTrackingClassCodeExpressionTransformer) visitor).withMethod(c, new Runnable() { @Override public void run() { superArgsTransformed.set(((VisitorImpl) visitor).transformArguments(_superArgs)); } }); thisArgs.add(((VisitorImpl) visitor).makeCheckedCall(""checkedSuperConstructor"", new ClassExpression(superClass), superArgsTransformed.get())); Parameter[] origParams = c.getParameters(); for (Parameter p : origParams) { thisArgs.add(new VariableExpression(p)); } c.setCode(new BlockStatement(new Statement[] {new ExpressionStatement(new ConstructorCallExpression(ClassNode.THIS, new TupleExpression(thisArgs)))}, c.getVariableScope())); Parameter[] params = new Parameter[origParams.length + 1]; params[0] = new Parameter(new ClassNode(Checker.SuperConstructorWrapper.class), ""$scw""); System.arraycopy(origParams, 0, params, 1, origParams.length); List scwArgs = new ArrayList<>(); int x = 0; for (Expression superArg : superArgs) { scwArgs.add(/*new CastExpression(superArg.getType(), */new MethodCallExpression(new VariableExpression(""$scw""), ""arg"", new ConstantExpression(x++))/*)*/); } List body2 = new ArrayList<>(); body2.add(0, new ExpressionStatement(new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(scwArgs)))); for (final Statement s : body) { ((ScopeTrackingClassCodeExpressionTransformer) visitor).withMethod(c, new Runnable() { @Override public void run() { s.visit(visitor); } }); body2.add(s); } ConstructorNode c2 = new ConstructorNode(Modifier.PRIVATE, params, c.getExceptions(), new BlockStatement(body2, c.getVariableScope())); // perhaps more misleading than helpful: c2.setSourcePosition(c); classNode.addConstructor(c2); } } } "," public void processConstructors(final ClassCodeExpressionTransformer visitor, ClassNode classNode) { ClassNode superClass = classNode.getSuperClass(); List declaredConstructors = classNode.getDeclaredConstructors(); if (TRIVIAL_CONSTRUCTORS.contains(superClass.getName())) { for (ConstructorNode c : declaredConstructors) { visitor.visitMethod(c); } } else { if (declaredConstructors.isEmpty()) { ConstructorNode syntheticConstructor = new ConstructorNode(Modifier.PUBLIC, new BlockStatement()); declaredConstructors = Collections.singletonList(syntheticConstructor); classNode.addConstructor(syntheticConstructor); } else { declaredConstructors = new ArrayList<>(declaredConstructors); } for (ConstructorNode c : declaredConstructors) { Statement code = c.getCode(); List body; if (code instanceof BlockStatement) { body = ((BlockStatement) code).getStatements(); } else { body = Collections.singletonList(code); } TupleExpression superArgs = new TupleExpression(); if (!body.isEmpty() && body.get(0) instanceof ExpressionStatement && ((ExpressionStatement) body.get(0)).getExpression() instanceof ConstructorCallExpression) { ConstructorCallExpression cce = (ConstructorCallExpression) ((ExpressionStatement) body.get(0)).getExpression(); if (cce.isThisCall()) { // these are fine as is visitor.visitMethod(c); continue; } else if (cce.isSuperCall()) { body = body.subList(1, body.size()); superArgs = ((TupleExpression) cce.getArguments()); } } List thisArgs = new ArrayList<>(); final TupleExpression _superArgs = superArgs; final AtomicReference superArgsTransformed = new AtomicReference<>(); ((ScopeTrackingClassCodeExpressionTransformer) visitor).withMethod(c, new Runnable() { @Override public void run() { superArgsTransformed.set(((VisitorImpl) visitor).transformArguments(_superArgs)); } }); thisArgs.add(((VisitorImpl) visitor).makeCheckedCall(""checkedSuperConstructor"", new ClassExpression(superClass), superArgsTransformed.get())); Parameter[] origParams = c.getParameters(); for (Parameter p : origParams) { thisArgs.add(new VariableExpression(p)); } c.setCode(new BlockStatement(new Statement[] {new ExpressionStatement(new ConstructorCallExpression(ClassNode.THIS, new TupleExpression(thisArgs)))}, c.getVariableScope())); Parameter[] params = new Parameter[origParams.length + 1]; params[0] = new Parameter(new ClassNode(Checker.SuperConstructorWrapper.class), ""$scw""); System.arraycopy(origParams, 0, params, 1, origParams.length); List scwArgs = new ArrayList<>(); int x = 0; for (Expression superArg : superArgs) { scwArgs.add(/*new CastExpression(superArg.getType(), */new MethodCallExpression(new VariableExpression(""$scw""), ""arg"", new ConstantExpression(x++))/*)*/); } List body2 = new ArrayList<>(); body2.add(0, new ExpressionStatement(new ConstructorCallExpression(ClassNode.SUPER, new ArgumentListExpression(scwArgs)))); for (final Statement s : body) { ((ScopeTrackingClassCodeExpressionTransformer) visitor).withMethod(c, new Runnable() { @Override public void run() { s.visit(visitor); } }); body2.add(s); } ConstructorNode c2 = new ConstructorNode(Modifier.PRIVATE, params, c.getExceptions(), new BlockStatement(body2, c.getVariableScope())); // perhaps more misleading than helpful: c2.setSourcePosition(c); classNode.addConstructor(c2); } } } ",FALSE,SandboxTransformer.java " public ClassCodeExpressionTransformer createVisitor(SourceUnit source) { return createVisitor(source, null); } "," public ClassCodeExpressionTransformer createVisitor(SourceUnit source) { return createVisitor(source, null); } ",FALSE,SandboxTransformer.java " public ClassCodeExpressionTransformer createVisitor(SourceUnit source, ClassNode clazz) { return new VisitorImpl(source, clazz); } "," public ClassCodeExpressionTransformer createVisitor(SourceUnit source, ClassNode clazz) { return new VisitorImpl(source, clazz); } ",FALSE,SandboxTransformer.java " VisitorImpl(SourceUnit sourceUnit, ClassNode clazz) { this.sourceUnit = sourceUnit; this.clazz = clazz; } "," VisitorImpl(SourceUnit sourceUnit, ClassNode clazz) { this.sourceUnit = sourceUnit; this.clazz = clazz; } ",FALSE,SandboxTransformer.java " public void visitMethod(MethodNode node) { if (clazz == null) { // compatibility clazz = node.getDeclaringClass(); } super.visitMethod(node); } "," public void visitMethod(MethodNode node) { if (clazz == null) { // compatibility clazz = node.getDeclaringClass(); } super.visitMethod(node); } ",FALSE,SandboxTransformer.java " Expression transformArguments(Expression e) { List l; if (e instanceof TupleExpression) { List expressions = ((TupleExpression) e).getExpressions(); l = new ArrayList<>(expressions.size()); for (Expression expression : expressions) { l.add(transform(expression)); } } else { l = Collections.singletonList(transform(e)); } // checkdCall expects an array return withLoc(e,new MethodCallExpression(new ListExpression(l),""toArray"",new ArgumentListExpression())); } "," Expression transformArguments(Expression e) { List l; if (e instanceof TupleExpression) { List expressions = ((TupleExpression) e).getExpressions(); l = new ArrayList<>(expressions.size()); for (Expression expression : expressions) { l.add(transform(expression)); } } else { l = Collections.singletonList(transform(e)); } // checkdCall expects an array return withLoc(e,new MethodCallExpression(new ListExpression(l),""toArray"",new ArgumentListExpression())); } ",FALSE,SandboxTransformer.java " Expression makeCheckedCall(String name, Expression... arguments) { return new StaticMethodCallExpression(checkerClass,name, new ArgumentListExpression(arguments)); } "," Expression makeCheckedCall(String name, Expression... arguments) { return new StaticMethodCallExpression(checkerClass,name, new ArgumentListExpression(arguments)); } ",FALSE,SandboxTransformer.java " public Expression transform(Expression exp) { Expression o = innerTransform(exp); if (o!=exp) { o.setSourcePosition(exp); } return o; } "," public Expression transform(Expression exp) { Expression o = innerTransform(exp); if (o!=exp) { o.setSourcePosition(exp); } return o; } ",FALSE,SandboxTransformer.java " private Expression innerTransform(Expression exp) { if (exp instanceof ClosureExpression) { // ClosureExpression.transformExpression doesn't visit the code inside ClosureExpression ce = (ClosureExpression)exp; try (StackVariableSet scope = new StackVariableSet(this)) { Parameter[] parameters = ce.getParameters(); if (parameters != null) { // Explicitly defined parameters, i.e., "".findAll { i -> i == 'bar' }"" if (parameters.length > 0) { for (Parameter p : parameters) { declareVariable(p); } } else { // Implicit parameter - i.e., "".findAll { it == 'bar' }"" declareVariable(new Parameter(ClassHelper.DYNAMIC_TYPE, ""it"")); } } boolean old = visitingClosureBody; visitingClosureBody = true; try { ce.getCode().visit(this); } finally { visitingClosureBody = old; } } } if (exp instanceof MethodCallExpression && interceptMethodCall) { // lhs.foo(arg1,arg2) => checkedCall(lhs,""foo"",arg1,arg2) // lhs+rhs => lhs.plus(rhs) // Integer.plus(Integer) => DefaultGroovyMethods.plus // lhs || rhs => lhs.or(rhs) MethodCallExpression call = (MethodCallExpression) exp; Expression objExp; if (call.isImplicitThis() && visitingClosureBody && !isLocalVariableExpression(call.getObjectExpression())) objExp = CLOSURE_THIS; else objExp = transform(call.getObjectExpression()); Expression arg1 = call.getMethod(); Expression arg2 = transformArguments(call.getArguments()); if (call.getObjectExpression() instanceof VariableExpression && ((VariableExpression) call.getObjectExpression()).getName().equals(""super"")) { if (clazz == null) { throw new IllegalStateException(""owning class not defined""); } return makeCheckedCall(""checkedSuperCall"", new ClassExpression(clazz), objExp, arg1, arg2); } else { return makeCheckedCall(""checkedCall"", objExp, boolExp(call.isSafe()), boolExp(call.isSpreadSafe()), arg1, arg2); } } if (exp instanceof StaticMethodCallExpression && interceptMethodCall) { /* Groovy doesn't use StaticMethodCallExpression as much as it could in compilation. For example, ""Math.max(1,2)"" results in a regular MethodCallExpression. Static import handling uses StaticMethodCallExpression, and so are some ASTTransformations like ToString,EqualsAndHashCode, etc. */ StaticMethodCallExpression call = (StaticMethodCallExpression) exp; return makeCheckedCall(""checkedStaticCall"", new ClassExpression(call.getOwnerType()), new ConstantExpression(call.getMethod()), transformArguments(call.getArguments()) ); } if (exp instanceof MethodPointerExpression && interceptMethodCall) { MethodPointerExpression mpe = (MethodPointerExpression) exp; return new ConstructorCallExpression( new ClassNode(SandboxedMethodClosure.class), new ArgumentListExpression(mpe.getExpression(), mpe.getMethodName()) ); } if (exp instanceof ConstructorCallExpression && interceptConstructor) { if (!((ConstructorCallExpression) exp).isSpecialCall()) { // creating a new instance, like ""new Foo(...)"" return makeCheckedCall(""checkedConstructor"", new ClassExpression(exp.getType()), transformArguments(((ConstructorCallExpression) exp).getArguments()) ); } else { // we can't really intercept constructor calling super(...) or this(...), // since it has to be the first method call in a constructor. // but see SECURITY-582 fix above } } if (exp instanceof AttributeExpression && interceptAttribute) { AttributeExpression ae = (AttributeExpression) exp; return makeCheckedCall(""checkedGetAttribute"", transform(ae.getObjectExpression()), boolExp(ae.isSafe()), boolExp(ae.isSpreadSafe()), transform(ae.getProperty()) ); } if (exp instanceof PropertyExpression && interceptProperty) { PropertyExpression pe = (PropertyExpression) exp; return makeCheckedCall(""checkedGetProperty"", transformObjectExpression(pe), boolExp(pe.isSafe()), boolExp(pe.isSpreadSafe()), transform(pe.getProperty()) ); } if (exp instanceof VariableExpression && interceptProperty) { VariableExpression vexp = (VariableExpression) exp; if (isLocalVariable(vexp.getName()) || vexp.getName().equals(""this"") || vexp.getName().equals(""super"")) { // We don't care what sandboxed code does to itself until it starts interacting with outside world return super.transform(exp); } else { // if the variable is not in-scope local variable, it gets treated as a property access with implicit this. // see AsmClassGenerator.visitVariableExpression and processClassVariable. PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, vexp.getName()); pexp.setImplicitThis(true); withLoc(exp,pexp); return transform(pexp); } } if (exp instanceof DeclarationExpression) { handleDeclarations((DeclarationExpression) exp); } if (exp instanceof BinaryExpression) { BinaryExpression be = (BinaryExpression) exp; // this covers everything from a+b to a=b if (ofType(be.getOperation().getType(),ASSIGNMENT_OPERATOR)) { // simple assignment like '=' as well as compound assignments like ""+="",""-="", etc. // How we dispatch this depends on the type of left expression. // // What can be LHS? // according to AsmClassGenerator, PropertyExpression, AttributeExpression, FieldExpression, VariableExpression Expression lhs = be.getLeftExpression(); if (lhs instanceof VariableExpression) { VariableExpression vexp = (VariableExpression) lhs; if (isLocalVariable(vexp.getName()) || vexp.getName().equals(""this"") || vexp.getName().equals(""super"")) { // We don't care what sandboxed code does to itself until it starts interacting with outside world return super.transform(exp); } else { // if the variable is not in-scope local variable, it gets treated as a property access with implicit this. // see AsmClassGenerator.visitVariableExpression and processClassVariable. PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, vexp.getName()); pexp.setImplicitThis(true); pexp.setSourcePosition(vexp); lhs = pexp; } } // no else here if (lhs instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) lhs; String name = null; if (lhs instanceof AttributeExpression) { if (interceptAttribute) name = ""checkedSetAttribute""; } else { Expression receiver = pe.getObjectExpression(); if (receiver instanceof VariableExpression && ((VariableExpression) receiver).getName().equals(""this"")) { FieldNode field = clazz != null ? clazz.getField(pe.getPropertyAsString()) : null; if (field != null) { // could also verify that it is final, but not necessary // cf. BinaryExpression.transformExpression; super.transform(exp) transforms the LHS to checkedGetProperty return new BinaryExpression(lhs, be.getOperation(), transform(be.getRightExpression())); } // else this is a property which we need to check } if (interceptProperty) name = ""checkedSetProperty""; } if (name==null) // not intercepting? return super.transform(exp); return makeCheckedCall(name, transformObjectExpression(pe), pe.getProperty(), boolExp(pe.isSafe()), boolExp(pe.isSpreadSafe()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } else if (lhs instanceof FieldExpression) { // while javadoc of FieldExpression isn't very clear, // AsmClassGenerator maps this to GETSTATIC/SETSTATIC/GETFIELD/SETFIELD access. // not sure how we can intercept this, so skipping this for now return super.transform(exp); } else if (lhs instanceof BinaryExpression) { BinaryExpression lbe = (BinaryExpression) lhs; if (lbe.getOperation().getType()==Types.LEFT_SQUARE_BRACKET && interceptArray) {// expression of the form ""x[y] = z"" return makeCheckedCall(""checkedSetArray"", transform(lbe.getLeftExpression()), transform(lbe.getRightExpression()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } } else throw new AssertionError(""Unexpected LHS of an assignment: "" + lhs.getClass()); } if (be.getOperation().getType()==Types.LEFT_SQUARE_BRACKET) {// array reference if (interceptArray) return makeCheckedCall(""checkedGetArray"", transform(be.getLeftExpression()), transform(be.getRightExpression()) ); } else if (be.getOperation().getType()==Types.KEYWORD_INSTANCEOF) {// instanceof operator return super.transform(exp); } else if (Ops.isLogicalOperator(be.getOperation().getType())) { return super.transform(exp); } else if (be.getOperation().getType()==Types.KEYWORD_IN) {// membership operator: JENKINS-28154 // This requires inverted operand order: // ""a in [...]"" -> ""[...].isCase(a)"" if (interceptMethodCall) return makeCheckedCall(""checkedCall"", transform(be.getRightExpression()), boolExp(false), boolExp(false), stringExp(""isCase""), transform(be.getLeftExpression()) ); } else if (Ops.isRegexpComparisonOperator(be.getOperation().getType())) { if (interceptMethodCall) return makeCheckedCall(""checkedStaticCall"", classExp(ScriptBytecodeAdapterClass), stringExp(Ops.binaryOperatorMethods(be.getOperation().getType())), transform(be.getLeftExpression()), transform(be.getRightExpression()) ); } else if (Ops.isComparisionOperator(be.getOperation().getType())) { if (interceptMethodCall) { return makeCheckedCall(""checkedComparison"", transform(be.getLeftExpression()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } } else if (interceptMethodCall) { // normally binary operators like a+b // TODO: check what other weird binary operators land here return makeCheckedCall(""checkedBinaryOp"", transform(be.getLeftExpression()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } } if (exp instanceof PostfixExpression) { PostfixExpression pe = (PostfixExpression) exp; return prefixPostfixExp(exp, pe.getExpression(), pe.getOperation(), ""Postfix""); } if (exp instanceof PrefixExpression) { PrefixExpression pe = (PrefixExpression) exp; return prefixPostfixExp(exp, pe.getExpression(), pe.getOperation(), ""Prefix""); } if (exp instanceof CastExpression) { CastExpression ce = (CastExpression) exp; return makeCheckedCall(""checkedCast"", classExp(exp.getType()), transform(ce.getExpression()), boolExp(ce.isIgnoringAutoboxing()), boolExp(ce.isCoerce()), boolExp(ce.isStrict()) ); } return super.transform(exp); } "," private Expression innerTransform(Expression exp) { if (exp instanceof ClosureExpression) { // ClosureExpression.transformExpression doesn't visit the code inside ClosureExpression ce = (ClosureExpression)exp; try (StackVariableSet scope = new StackVariableSet(this)) { Parameter[] parameters = ce.getParameters(); if (parameters != null) { // Explicitly defined parameters, i.e., "".findAll { i -> i == 'bar' }"" if (parameters.length > 0) { for (Parameter p : parameters) { declareVariable(p); } } else { // Implicit parameter - i.e., "".findAll { it == 'bar' }"" declareVariable(new Parameter(ClassHelper.DYNAMIC_TYPE, ""it"")); } } boolean old = visitingClosureBody; visitingClosureBody = true; try { ce.getCode().visit(this); } finally { visitingClosureBody = old; } } } if (exp instanceof MethodCallExpression && interceptMethodCall) { // lhs.foo(arg1,arg2) => checkedCall(lhs,""foo"",arg1,arg2) // lhs+rhs => lhs.plus(rhs) // Integer.plus(Integer) => DefaultGroovyMethods.plus // lhs || rhs => lhs.or(rhs) MethodCallExpression call = (MethodCallExpression) exp; Expression objExp; if (call.isImplicitThis() && visitingClosureBody && !isLocalVariableExpression(call.getObjectExpression())) objExp = CLOSURE_THIS; else objExp = transform(call.getObjectExpression()); Expression arg1 = call.getMethod(); Expression arg2 = transformArguments(call.getArguments()); if (call.getObjectExpression() instanceof VariableExpression && ((VariableExpression) call.getObjectExpression()).getName().equals(""super"")) { if (clazz == null) { throw new IllegalStateException(""owning class not defined""); } return makeCheckedCall(""checkedSuperCall"", new ClassExpression(clazz), objExp, arg1, arg2); } else { return makeCheckedCall(""checkedCall"", objExp, boolExp(call.isSafe()), boolExp(call.isSpreadSafe()), arg1, arg2); } } if (exp instanceof StaticMethodCallExpression && interceptMethodCall) { /* Groovy doesn't use StaticMethodCallExpression as much as it could in compilation. For example, ""Math.max(1,2)"" results in a regular MethodCallExpression. Static import handling uses StaticMethodCallExpression, and so are some ASTTransformations like ToString,EqualsAndHashCode, etc. */ StaticMethodCallExpression call = (StaticMethodCallExpression) exp; return makeCheckedCall(""checkedStaticCall"", new ClassExpression(call.getOwnerType()), new ConstantExpression(call.getMethod()), transformArguments(call.getArguments()) ); } if (exp instanceof MethodPointerExpression && interceptMethodCall) { MethodPointerExpression mpe = (MethodPointerExpression) exp; return new ConstructorCallExpression( new ClassNode(SandboxedMethodClosure.class), new ArgumentListExpression(mpe.getExpression(), mpe.getMethodName()) ); } if (exp instanceof ConstructorCallExpression && interceptConstructor) { if (!((ConstructorCallExpression) exp).isSpecialCall()) { // creating a new instance, like ""new Foo(...)"" return makeCheckedCall(""checkedConstructor"", new ClassExpression(exp.getType()), transformArguments(((ConstructorCallExpression) exp).getArguments()) ); } else { // we can't really intercept constructor calling super(...) or this(...), // since it has to be the first method call in a constructor. // but see SECURITY-582 fix above } } if (exp instanceof AttributeExpression && interceptAttribute) { AttributeExpression ae = (AttributeExpression) exp; return makeCheckedCall(""checkedGetAttribute"", transform(ae.getObjectExpression()), boolExp(ae.isSafe()), boolExp(ae.isSpreadSafe()), transform(ae.getProperty()) ); } if (exp instanceof PropertyExpression && interceptProperty) { PropertyExpression pe = (PropertyExpression) exp; return makeCheckedCall(""checkedGetProperty"", transformObjectExpression(pe), boolExp(pe.isSafe()), boolExp(pe.isSpreadSafe()), transform(pe.getProperty()) ); } if (exp instanceof VariableExpression && interceptProperty) { VariableExpression vexp = (VariableExpression) exp; if (isLocalVariable(vexp.getName()) || vexp.getName().equals(""this"") || vexp.getName().equals(""super"")) { // We don't care what sandboxed code does to itself until it starts interacting with outside world return super.transform(exp); } else { // if the variable is not in-scope local variable, it gets treated as a property access with implicit this. // see AsmClassGenerator.visitVariableExpression and processClassVariable. PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, vexp.getName()); pexp.setImplicitThis(true); withLoc(exp,pexp); return transform(pexp); } } if (exp instanceof DeclarationExpression) { handleDeclarations((DeclarationExpression) exp); } if (exp instanceof BinaryExpression) { BinaryExpression be = (BinaryExpression) exp; // this covers everything from a+b to a=b if (ofType(be.getOperation().getType(),ASSIGNMENT_OPERATOR)) { // simple assignment like '=' as well as compound assignments like ""+="",""-="", etc. // How we dispatch this depends on the type of left expression. // // What can be LHS? // according to AsmClassGenerator, PropertyExpression, AttributeExpression, FieldExpression, VariableExpression Expression lhs = be.getLeftExpression(); if (lhs instanceof VariableExpression) { VariableExpression vexp = (VariableExpression) lhs; if (isLocalVariable(vexp.getName()) || vexp.getName().equals(""this"") || vexp.getName().equals(""super"")) { // We don't care what sandboxed code does to itself until it starts interacting with outside world return super.transform(exp); } else { // if the variable is not in-scope local variable, it gets treated as a property access with implicit this. // see AsmClassGenerator.visitVariableExpression and processClassVariable. PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, vexp.getName()); pexp.setImplicitThis(true); pexp.setSourcePosition(vexp); lhs = pexp; } } // no else here if (lhs instanceof PropertyExpression) { PropertyExpression pe = (PropertyExpression) lhs; String name = null; if (lhs instanceof AttributeExpression) { if (interceptAttribute) name = ""checkedSetAttribute""; } else { Expression receiver = pe.getObjectExpression(); if (receiver instanceof VariableExpression && ((VariableExpression) receiver).getName().equals(""this"")) { FieldNode field = clazz != null ? clazz.getField(pe.getPropertyAsString()) : null; if (field != null) { // could also verify that it is final, but not necessary // cf. BinaryExpression.transformExpression; super.transform(exp) transforms the LHS to checkedGetProperty return new BinaryExpression(lhs, be.getOperation(), transform(be.getRightExpression())); } // else this is a property which we need to check } if (interceptProperty) name = ""checkedSetProperty""; } if (name==null) // not intercepting? return super.transform(exp); return makeCheckedCall(name, transformObjectExpression(pe), pe.getProperty(), boolExp(pe.isSafe()), boolExp(pe.isSpreadSafe()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } else if (lhs instanceof FieldExpression) { // while javadoc of FieldExpression isn't very clear, // AsmClassGenerator maps this to GETSTATIC/SETSTATIC/GETFIELD/SETFIELD access. // not sure how we can intercept this, so skipping this for now return super.transform(exp); } else if (lhs instanceof BinaryExpression) { BinaryExpression lbe = (BinaryExpression) lhs; if (lbe.getOperation().getType()==Types.LEFT_SQUARE_BRACKET && interceptArray) {// expression of the form ""x[y] = z"" return makeCheckedCall(""checkedSetArray"", transform(lbe.getLeftExpression()), transform(lbe.getRightExpression()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } } else throw new AssertionError(""Unexpected LHS of an assignment: "" + lhs.getClass()); } if (be.getOperation().getType()==Types.LEFT_SQUARE_BRACKET) {// array reference if (interceptArray) return makeCheckedCall(""checkedGetArray"", transform(be.getLeftExpression()), transform(be.getRightExpression()) ); } else if (be.getOperation().getType()==Types.KEYWORD_INSTANCEOF) {// instanceof operator return super.transform(exp); } else if (Ops.isLogicalOperator(be.getOperation().getType())) { return super.transform(exp); } else if (be.getOperation().getType()==Types.KEYWORD_IN) {// membership operator: JENKINS-28154 // This requires inverted operand order: // ""a in [...]"" -> ""[...].isCase(a)"" if (interceptMethodCall) return makeCheckedCall(""checkedCall"", transform(be.getRightExpression()), boolExp(false), boolExp(false), stringExp(""isCase""), transform(be.getLeftExpression()) ); } else if (Ops.isRegexpComparisonOperator(be.getOperation().getType())) { if (interceptMethodCall) return makeCheckedCall(""checkedStaticCall"", classExp(ScriptBytecodeAdapterClass), stringExp(Ops.binaryOperatorMethods(be.getOperation().getType())), transform(be.getLeftExpression()), transform(be.getRightExpression()) ); } else if (Ops.isComparisionOperator(be.getOperation().getType())) { if (interceptMethodCall) { return makeCheckedCall(""checkedComparison"", transform(be.getLeftExpression()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } } else if (interceptMethodCall) { // normally binary operators like a+b // TODO: check what other weird binary operators land here return makeCheckedCall(""checkedBinaryOp"", transform(be.getLeftExpression()), intExp(be.getOperation().getType()), transform(be.getRightExpression()) ); } } if (exp instanceof PostfixExpression) { PostfixExpression pe = (PostfixExpression) exp; return prefixPostfixExp(exp, pe.getExpression(), pe.getOperation(), ""Postfix""); } if (exp instanceof PrefixExpression) { PrefixExpression pe = (PrefixExpression) exp; return prefixPostfixExp(exp, pe.getExpression(), pe.getOperation(), ""Prefix""); } if (exp instanceof CastExpression) { CastExpression ce = (CastExpression) exp; return makeCheckedCall(""checkedCast"", classExp(exp.getType()), transform(ce.getExpression()), boolExp(ce.isIgnoringAutoboxing()), boolExp(ce.isCoerce()), boolExp(ce.isStrict()) ); } return super.transform(exp); } ",FALSE,SandboxTransformer.java " private Expression prefixPostfixExp(Expression whole, Expression atom, Token opToken, String mode) { String op = opToken.getText().equals(""++"") ? ""next"" : ""previous""; // a[b]++ if (atom instanceof BinaryExpression && ((BinaryExpression) atom).getOperation().getType()==Types.LEFT_SQUARE_BRACKET && interceptArray) { return makeCheckedCall(""checked"" + mode + ""Array"", transform(((BinaryExpression) atom).getLeftExpression()), transform(((BinaryExpression) atom).getRightExpression()), stringExp(op) ); } // a++ if (atom instanceof VariableExpression) { VariableExpression ve = (VariableExpression) atom; if (isLocalVariable(ve.getName())) { if (mode.equals(""Postfix"")) { // a trick to rewrite a++ without introducing a new local variable // a++ -> [a,a=a.next()][0] return transform(withLoc(whole,new BinaryExpression( new ListExpression(Arrays.asList( atom, new BinaryExpression(atom, ASSIGNMENT_OP, withLoc(atom,new MethodCallExpression(atom,op,EMPTY_ARGUMENTS))) )), new Token(Types.LEFT_SQUARE_BRACKET, ""["", -1,-1), new ConstantExpression(0) ))); } else { // ++a -> a=a.next() return transform(withLoc(whole,new BinaryExpression(atom,ASSIGNMENT_OP, withLoc(atom,new MethodCallExpression(atom,op,EMPTY_ARGUMENTS))) )); } } else { // if the variable is not in-scope local variable, it gets treated as a property access with implicit this. // see AsmClassGenerator.visitVariableExpression and processClassVariable. PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, ve.getName()); pexp.setImplicitThis(true); pexp.setSourcePosition(atom); atom = pexp; // fall through to the ""a.b++"" case below } } // a.b++ if (atom instanceof PropertyExpression && interceptProperty) { PropertyExpression pe = (PropertyExpression) atom; return makeCheckedCall(""checked"" + mode + ""Property"", transformObjectExpression(pe), pe.getProperty(), boolExp(pe.isSafe()), boolExp(pe.isSpreadSafe()), stringExp(op) ); } return whole; } "," private Expression prefixPostfixExp(Expression whole, Expression atom, Token opToken, String mode) { String op = opToken.getText().equals(""++"") ? ""next"" : ""previous""; // a[b]++ if (atom instanceof BinaryExpression && ((BinaryExpression) atom).getOperation().getType()==Types.LEFT_SQUARE_BRACKET && interceptArray) { return makeCheckedCall(""checked"" + mode + ""Array"", transform(((BinaryExpression) atom).getLeftExpression()), transform(((BinaryExpression) atom).getRightExpression()), stringExp(op) ); } // a++ if (atom instanceof VariableExpression) { VariableExpression ve = (VariableExpression) atom; if (isLocalVariable(ve.getName())) { if (mode.equals(""Postfix"")) { // a trick to rewrite a++ without introducing a new local variable // a++ -> [a,a=a.next()][0] return transform(withLoc(whole,new BinaryExpression( new ListExpression(Arrays.asList( atom, new BinaryExpression(atom, ASSIGNMENT_OP, withLoc(atom,new MethodCallExpression(atom,op,EMPTY_ARGUMENTS))) )), new Token(Types.LEFT_SQUARE_BRACKET, ""["", -1,-1), new ConstantExpression(0) ))); } else { // ++a -> a=a.next() return transform(withLoc(whole,new BinaryExpression(atom,ASSIGNMENT_OP, withLoc(atom,new MethodCallExpression(atom,op,EMPTY_ARGUMENTS))) )); } } else { // if the variable is not in-scope local variable, it gets treated as a property access with implicit this. // see AsmClassGenerator.visitVariableExpression and processClassVariable. PropertyExpression pexp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, ve.getName()); pexp.setImplicitThis(true); pexp.setSourcePosition(atom); atom = pexp; // fall through to the ""a.b++"" case below } } // a.b++ if (atom instanceof PropertyExpression && interceptProperty) { PropertyExpression pe = (PropertyExpression) atom; return makeCheckedCall(""checked"" + mode + ""Property"", transformObjectExpression(pe), pe.getProperty(), boolExp(pe.isSafe()), boolExp(pe.isSpreadSafe()), stringExp(op) ); } return whole; } ",FALSE,SandboxTransformer.java " private T withLoc(ASTNode src, T t) { t.setSourcePosition(src); return t; } "," private T withLoc(ASTNode src, T t) { t.setSourcePosition(src); return t; } ",FALSE,SandboxTransformer.java " private Expression transformObjectExpression(PropertyExpression exp) { if (exp.isImplicitThis() && visitingClosureBody && !isLocalVariableExpression(exp.getObjectExpression())) { return CLOSURE_THIS; } else { return transform(exp.getObjectExpression()); } } "," private Expression transformObjectExpression(PropertyExpression exp) { if (exp.isImplicitThis() && visitingClosureBody && !isLocalVariableExpression(exp.getObjectExpression())) { return CLOSURE_THIS; } else { return transform(exp.getObjectExpression()); } } ",FALSE,SandboxTransformer.java " private boolean isLocalVariableExpression(Expression exp) { if (exp != null && exp instanceof VariableExpression) { return isLocalVariable(((VariableExpression) exp).getName()); } return false; } "," private boolean isLocalVariableExpression(Expression exp) { if (exp != null && exp instanceof VariableExpression) { return isLocalVariable(((VariableExpression) exp).getName()); } return false; } ",FALSE,SandboxTransformer.java " ConstantExpression boolExp(boolean v) { return v ? ConstantExpression.PRIM_TRUE : ConstantExpression.PRIM_FALSE; } "," ConstantExpression boolExp(boolean v) { return v ? ConstantExpression.PRIM_TRUE : ConstantExpression.PRIM_FALSE; } ",FALSE,SandboxTransformer.java " ConstantExpression intExp(int v) { return new ConstantExpression(v,true); } "," ConstantExpression intExp(int v) { return new ConstantExpression(v,true); } ",FALSE,SandboxTransformer.java " ClassExpression classExp(ClassNode c) { return new ClassExpression(c); } "," ClassExpression classExp(ClassNode c) { return new ClassExpression(c); } ",FALSE,SandboxTransformer.java " ConstantExpression stringExp(String v) { return new ConstantExpression(v); } "," ConstantExpression stringExp(String v) { return new ConstantExpression(v); } ",FALSE,SandboxTransformer.java " public void visitExpressionStatement(ExpressionStatement es) { Expression exp = es.getExpression(); if (exp instanceof DeclarationExpression) { DeclarationExpression de = (DeclarationExpression) exp; Expression leftExpression = de.getLeftExpression(); if (leftExpression instanceof VariableExpression) { // Only cast and transform if the RHS is *not* an EmptyExpression, i.e., ""String foo;"" would not be cast/transformed. if (!(de.getRightExpression() instanceof EmptyExpression) && mightBePositionalArgumentConstructor((VariableExpression) leftExpression)) { CastExpression ce = new CastExpression(leftExpression.getType(), de.getRightExpression()); ce.setCoerce(true); es.setExpression(transform(new DeclarationExpression(leftExpression, de.getOperation(), ce))); return; } } else { throw new UnsupportedOperationException(""not supporting tuples yet""); // cf. ""Unexpected LHS of an assignment"" above } } super.visitExpressionStatement(es); } "," public void visitExpressionStatement(ExpressionStatement es) { Expression exp = es.getExpression(); if (exp instanceof DeclarationExpression) { DeclarationExpression de = (DeclarationExpression) exp; Expression leftExpression = de.getLeftExpression(); if (leftExpression instanceof VariableExpression) { // Only cast and transform if the RHS is *not* an EmptyExpression, i.e., ""String foo;"" would not be cast/transformed. if (!(de.getRightExpression() instanceof EmptyExpression) && mightBePositionalArgumentConstructor((VariableExpression) leftExpression)) { CastExpression ce = new CastExpression(leftExpression.getType(), de.getRightExpression()); ce.setCoerce(true); es.setExpression(transform(new DeclarationExpression(leftExpression, de.getOperation(), ce))); return; } } else { throw new UnsupportedOperationException(""not supporting tuples yet""); // cf. ""Unexpected LHS of an assignment"" above } } super.visitExpressionStatement(es); } ",FALSE,SandboxTransformer.java " protected SourceUnit getSourceUnit() { return sourceUnit; } "," protected SourceUnit getSourceUnit() { return sourceUnit; } ",FALSE,SandboxTransformer.java " public static boolean mightBePositionalArgumentConstructor(VariableExpression ve) { ClassNode type = ve.getType(); if (type.isArray()) { return false; // do not care about componentType } Class clazz; try { clazz = type.getTypeClass(); } catch (GroovyBugError x) { return false; // ""ClassNode#getTypeClass for … is called before the type class is set"" when assigning to a type defined in Groovy source } return clazz != null && clazz != Object.class && !Modifier.isAbstract(clazz.getModifiers()); } "," public static boolean mightBePositionalArgumentConstructor(VariableExpression ve) { ClassNode type = ve.getType(); if (type.isArray()) { return false; // do not care about componentType } Class clazz; try { clazz = type.getTypeClass(); } catch (GroovyBugError x) { return false; // ""ClassNode#getTypeClass for … is called before the type class is set"" when assigning to a type defined in Groovy source } return clazz != null && clazz != Object.class && !Modifier.isAbstract(clazz.getModifiers()); } ",FALSE,SandboxTransformer.java " public DiskFileItem(String fieldName, String contentType, boolean isFormField, String fileName, int sizeThreshold, File repository) { this.fieldName = fieldName; this.contentType = contentType; this.isFormField = isFormField; this.fileName = fileName; this.sizeThreshold = sizeThreshold; this.repository = repository; } "," public DiskFileItem(String fieldName, String contentType, boolean isFormField, String fileName, int sizeThreshold, File repository) { this.fieldName = fieldName; this.contentType = contentType; this.isFormField = isFormField; this.fileName = fileName; this.sizeThreshold = sizeThreshold; this.repository = repository; } ",FALSE,DiskFileItem.java " public InputStream getInputStream() throws IOException { if (!isInMemory()) { return new FileInputStream(dfos.getFile()); } if (cachedContent == null) { cachedContent = dfos.getData(); } return new ByteArrayInputStream(cachedContent); } "," public InputStream getInputStream() throws IOException { if (!isInMemory()) { return new FileInputStream(dfos.getFile()); } if (cachedContent == null) { cachedContent = dfos.getData(); } return new ByteArrayInputStream(cachedContent); } ",FALSE,DiskFileItem.java " public String getContentType() { return contentType; } "," public String getContentType() { return contentType; } ",FALSE,DiskFileItem.java " public String getCharSet() { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(getContentType(), ';'); return params.get(""charset""); } "," public String getCharSet() { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(getContentType(), ';'); return params.get(""charset""); } ",FALSE,DiskFileItem.java " public String getName() { return Streams.checkFileName(fileName); } "," public String getName() { return Streams.checkFileName(fileName); } ",FALSE,DiskFileItem.java " public boolean isInMemory() { if (cachedContent != null) { return true; } return dfos.isInMemory(); } "," public boolean isInMemory() { if (cachedContent != null) { return true; } return dfos.isInMemory(); } ",FALSE,DiskFileItem.java " public long getSize() { if (size >= 0) { return size; } else if (cachedContent != null) { return cachedContent.length; } else if (dfos.isInMemory()) { return dfos.getData().length; } else { return dfos.getFile().length(); } } "," public long getSize() { if (size >= 0) { return size; } else if (cachedContent != null) { return cachedContent.length; } else if (dfos.isInMemory()) { return dfos.getData().length; } else { return dfos.getFile().length(); } } ",FALSE,DiskFileItem.java " public byte[] get() { if (isInMemory()) { if (cachedContent == null) { cachedContent = dfos.getData(); } return cachedContent; } byte[] fileData = new byte[(int) getSize()]; InputStream fis = null; try { fis = new BufferedInputStream(new FileInputStream(dfos.getFile())); fis.read(fileData); } catch (IOException e) { fileData = null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } return fileData; } "," public byte[] get() { if (isInMemory()) { if (cachedContent == null) { cachedContent = dfos.getData(); } return cachedContent; } byte[] fileData = new byte[(int) getSize()]; InputStream fis = null; try { fis = new BufferedInputStream(new FileInputStream(dfos.getFile())); fis.read(fileData); } catch (IOException e) { fileData = null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } return fileData; } ",FALSE,DiskFileItem.java " public String getString(final String charset) throws UnsupportedEncodingException { return new String(get(), charset); } "," public String getString(final String charset) throws UnsupportedEncodingException { return new String(get(), charset); } ",FALSE,DiskFileItem.java " public String getString() { byte[] rawdata = get(); String charset = getCharSet(); if (charset == null) { charset = DEFAULT_CHARSET; } try { return new String(rawdata, charset); } catch (UnsupportedEncodingException e) { return new String(rawdata); } } "," public String getString() { byte[] rawdata = get(); String charset = getCharSet(); if (charset == null) { charset = DEFAULT_CHARSET; } try { return new String(rawdata, charset); } catch (UnsupportedEncodingException e) { return new String(rawdata); } } ",FALSE,DiskFileItem.java " public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(outputFile)); out = new BufferedOutputStream( new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( ""Cannot write uploaded file to disk!""); } } } "," public void write(File file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else { File outputFile = getStoreLocation(); if (outputFile != null) { // Save the length of the file size = outputFile.length(); /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (!outputFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(outputFile)); out = new BufferedOutputStream( new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( ""Cannot write uploaded file to disk!""); } } } ",FALSE,DiskFileItem.java " public void delete() { cachedContent = null; File outputFile = getStoreLocation(); if (outputFile != null && outputFile.exists()) { outputFile.delete(); } } "," public void delete() { cachedContent = null; File outputFile = getStoreLocation(); if (outputFile != null && outputFile.exists()) { outputFile.delete(); } } ",FALSE,DiskFileItem.java " public String getFieldName() { return fieldName; } "," public String getFieldName() { return fieldName; } ",FALSE,DiskFileItem.java " public void setFieldName(String fieldName) { this.fieldName = fieldName; } "," public void setFieldName(String fieldName) { this.fieldName = fieldName; } ",FALSE,DiskFileItem.java " public boolean isFormField() { return isFormField; } "," public boolean isFormField() { return isFormField; } ",FALSE,DiskFileItem.java " public void setFormField(boolean state) { isFormField = state; } "," public void setFormField(boolean state) { isFormField = state; } ",FALSE,DiskFileItem.java " public OutputStream getOutputStream() throws IOException { if (dfos == null) { File outputFile = getTempFile(); dfos = new DeferredFileOutputStream(sizeThreshold, outputFile); } return dfos; } "," public OutputStream getOutputStream() throws IOException { if (dfos == null) { File outputFile = getTempFile(); dfos = new DeferredFileOutputStream(sizeThreshold, outputFile); } return dfos; } ",FALSE,DiskFileItem.java " public File getStoreLocation() { if (dfos == null) { return null; } return dfos.getFile(); } "," public File getStoreLocation() { if (dfos == null) { return null; } return dfos.getFile(); } ",FALSE,DiskFileItem.java " protected void finalize() { File outputFile = dfos.getFile(); if (outputFile != null && outputFile.exists()) { outputFile.delete(); } } "," protected void finalize() { File outputFile = dfos.getFile(); if (outputFile != null && outputFile.exists()) { outputFile.delete(); } } ",FALSE,DiskFileItem.java " protected File getTempFile() { if (tempFile == null) { File tempDir = repository; if (tempDir == null) { tempDir = new File(System.getProperty(""java.io.tmpdir"")); } String tempFileName = format(""upload_%s_%s.tmp"", UID, getUniqueId()); tempFile = new File(tempDir, tempFileName); } return tempFile; } "," protected File getTempFile() { if (tempFile == null) { File tempDir = repository; if (tempDir == null) { tempDir = new File(System.getProperty(""java.io.tmpdir"")); } String tempFileName = format(""upload_%s_%s.tmp"", UID, getUniqueId()); tempFile = new File(tempDir, tempFileName); } return tempFile; } ",FALSE,DiskFileItem.java " private static String getUniqueId() { final int limit = 100000000; int current = COUNTER.getAndIncrement(); String id = Integer.toString(current); // If you manage to get more than 100 million of ids, you'll // start getting ids longer than 8 characters. if (current < limit) { id = (""00000000"" + id).substring(id.length()); } return id; } "," private static String getUniqueId() { final int limit = 100000000; int current = COUNTER.getAndIncrement(); String id = Integer.toString(current); // If you manage to get more than 100 million of ids, you'll // start getting ids longer than 8 characters. if (current < limit) { id = (""00000000"" + id).substring(id.length()); } return id; } ",FALSE,DiskFileItem.java " public String toString() { return format(""name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s"", getName(), getStoreLocation(), getSize(), isFormField(), getFieldName()); } "," public String toString() { return format(""name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s"", getName(), getStoreLocation(), getSize(), isFormField(), getFieldName()); } ",FALSE,DiskFileItem.java " private void writeObject(ObjectOutputStream out) throws IOException { // Read the data if (dfos.isInMemory()) { cachedContent = get(); } else { cachedContent = null; dfosFile = dfos.getFile(); } // write out values out.defaultWriteObject(); } "," private void writeObject(ObjectOutputStream out) throws IOException { // Read the data if (dfos.isInMemory()) { cachedContent = get(); } else { cachedContent = null; dfosFile = dfos.getFile(); } // write out values out.defaultWriteObject(); } ",FALSE,DiskFileItem.java " private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read values in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } "," private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // read values in.defaultReadObject(); /* One expected use of serialization is to migrate HTTP sessions * containing a DiskFileItem between JVMs. Particularly if the JVMs are * on different machines It is possible that the repository location is * not valid so validate it. */ if (repository != null) { if (repository.isDirectory()) { // Check path for nulls if (repository.getPath().contains(""\0"")) { throw new IOException(format( ""The repository [%s] contains a null character"", repository.getPath())); } } else { throw new IOException(format( ""The repository [%s] is not a directory"", repository.getAbsolutePath())); } } OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } ",TRUE,DiskFileItem.java " public FileItemHeaders getHeaders() { return headers; } "," public FileItemHeaders getHeaders() { return headers; } ",FALSE,DiskFileItem.java " public void setHeaders(FileItemHeaders pHeaders) { headers = pHeaders; } "," public void setHeaders(FileItemHeaders pHeaders) { headers = pHeaders; } ",FALSE,DiskFileItem.java " "," public void testInMemoryObject(byte[] testFieldValueBytes, File repository) { FileItem item = createFileItem(testFieldValueBytes, repository); // Check state is as expected assertTrue(""Initial: in memory"", item.isInMemory()); assertEquals(""Initial: size"", item.getSize(), testFieldValueBytes.length); compareBytes(""Initial"", item.get(), testFieldValueBytes); // Serialize & Deserialize FileItem newItem = (FileItem)serializeDeserialize(item); // Test deserialized content is as expected assertTrue(""Check in memory"", newItem.isInMemory()); compareBytes(""Check"", testFieldValueBytes, newItem.get()); // Compare FileItem's (except byte[]) compareFileItems(item, newItem); } ",TRUE,DiskFileItemSerializeTest.java " "," private void testInMemoryObject(byte[] testFieldValueBytes) { testInMemoryObject(testFieldValueBytes, null); } ",TRUE,DiskFileItemSerializeTest.java " public void testBelowThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold - 1); FileItem item = createFileItem(testFieldValueBytes); // Check state is as expected assertTrue(""Initial: in memory"", item.isInMemory()); assertEquals(""Initial: size"", item.getSize(), testFieldValueBytes.length); compareBytes(""Initial"", item.get(), testFieldValueBytes); // Serialize & Deserialize FileItem newItem = (FileItem)serializeDeserialize(item); // Test deserialized content is as expected assertTrue(""Check in memory"", newItem.isInMemory()); compareBytes(""Check"", testFieldValueBytes, newItem.get()); // Compare FileItem's (except byte[]) compareFileItems(item, newItem); } "," public void testBelowThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold - 1); testInMemoryObject(testFieldValueBytes); } ",TRUE,DiskFileItemSerializeTest.java " public void testThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold); FileItem item = createFileItem(testFieldValueBytes); // Check state is as expected assertTrue(""Initial: in memory"", item.isInMemory()); assertEquals(""Initial: size"", item.getSize(), testFieldValueBytes.length); compareBytes(""Initial"", item.get(), testFieldValueBytes); // Serialize & Deserialize FileItem newItem = (FileItem)serializeDeserialize(item); // Test deserialized content is as expected assertTrue(""Check in memory"", newItem.isInMemory()); compareBytes(""Check"", testFieldValueBytes, newItem.get()); // Compare FileItem's (except byte[]) compareFileItems(item, newItem); } "," public void testThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold); testInMemoryObject(testFieldValueBytes); } ",TRUE,DiskFileItemSerializeTest.java " public void testAboveThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold + 1); FileItem item = createFileItem(testFieldValueBytes); // Check state is as expected assertFalse(""Initial: in memory"", item.isInMemory()); assertEquals(""Initial: size"", item.getSize(), testFieldValueBytes.length); compareBytes(""Initial"", item.get(), testFieldValueBytes); // Serialize & Deserialize FileItem newItem = (FileItem)serializeDeserialize(item); // Test deserialized content is as expected assertFalse(""Check in memory"", newItem.isInMemory()); compareBytes(""Check"", testFieldValueBytes, newItem.get()); // Compare FileItem's (except byte[]) compareFileItems(item, newItem); } "," public void testAboveThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold + 1); FileItem item = createFileItem(testFieldValueBytes); // Check state is as expected assertFalse(""Initial: in memory"", item.isInMemory()); assertEquals(""Initial: size"", item.getSize(), testFieldValueBytes.length); compareBytes(""Initial"", item.get(), testFieldValueBytes); // Serialize & Deserialize FileItem newItem = (FileItem)serializeDeserialize(item); // Test deserialized content is as expected assertFalse(""Check in memory"", newItem.isInMemory()); compareBytes(""Check"", testFieldValueBytes, newItem.get()); // Compare FileItem's (except byte[]) compareFileItems(item, newItem); } ",FALSE,DiskFileItemSerializeTest.java " "," public void testValidRepository() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold); File repository = new File(System.getProperty(""java.io.tmpdir"")); testInMemoryObject(testFieldValueBytes, repository); } ",TRUE,DiskFileItemSerializeTest.java " "," public void testInvalidRepository() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold); File repository = new File(System.getProperty(""java.io.tmpdir"") + ""file""); FileItem item = createFileItem(testFieldValueBytes, repository); deserialize(serialize(item)); } ",TRUE,DiskFileItemSerializeTest.java " "," public void testInvalidRepositoryWithNullChar() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold); File repository = new File(System.getProperty(""java.io.tmpdir"") + ""\0""); FileItem item = createFileItem(testFieldValueBytes, repository); deserialize(serialize(item)); } ",TRUE,DiskFileItemSerializeTest.java " private void compareFileItems(FileItem origItem, FileItem newItem) { assertTrue(""Compare: is in Memory"", origItem.isInMemory() == newItem.isInMemory()); assertTrue(""Compare: is Form Field"", origItem.isFormField() == newItem.isFormField()); assertEquals(""Compare: Field Name"", origItem.getFieldName(), newItem.getFieldName()); assertEquals(""Compare: Content Type"", origItem.getContentType(), newItem.getContentType()); assertEquals(""Compare: File Name"", origItem.getName(), newItem.getName()); } "," private void compareFileItems(FileItem origItem, FileItem newItem) { assertTrue(""Compare: is in Memory"", origItem.isInMemory() == newItem.isInMemory()); assertTrue(""Compare: is Form Field"", origItem.isFormField() == newItem.isFormField()); assertEquals(""Compare: Field Name"", origItem.getFieldName(), newItem.getFieldName()); assertEquals(""Compare: Content Type"", origItem.getContentType(), newItem.getContentType()); assertEquals(""Compare: File Name"", origItem.getName(), newItem.getName()); } ",FALSE,DiskFileItemSerializeTest.java " private void compareBytes(String text, byte[] origBytes, byte[] newBytes) { assertNotNull(""origBytes must not be null"", origBytes); assertNotNull(""newBytes must not be null"", newBytes); assertEquals(text + "" byte[] length"", origBytes.length, newBytes.length); for (int i = 0; i < origBytes.length; i++) { assertEquals(text + "" byte["" + i + ""]"", origBytes[i], newBytes[i]); } } "," private void compareBytes(String text, byte[] origBytes, byte[] newBytes) { assertNotNull(""origBytes must not be null"", origBytes); assertNotNull(""newBytes must not be null"", newBytes); assertEquals(text + "" byte[] length"", origBytes.length, newBytes.length); for (int i = 0; i < origBytes.length; i++) { assertEquals(text + "" byte["" + i + ""]"", origBytes[i], newBytes[i]); } } ",FALSE,DiskFileItemSerializeTest.java " private byte[] createContentBytes(int size) { StringBuilder buffer = new StringBuilder(size); byte count = 0; for (int i = 0; i < size; i++) { buffer.append(count+""""); count++; if (count > 9) { count = 0; } } return buffer.toString().getBytes(); } "," private byte[] createContentBytes(int size) { StringBuilder buffer = new StringBuilder(size); byte count = 0; for (int i = 0; i < size; i++) { buffer.append(count+""""); count++; if (count > 9) { count = 0; } } return buffer.toString().getBytes(); } ",FALSE,DiskFileItemSerializeTest.java " "," private FileItem createFileItem(byte[] contentBytes, File repository) { FileItemFactory factory = new DiskFileItemFactory(threshold, repository); String textFieldName = ""textField""; FileItem item = factory.createItem( textFieldName, textContentType, true, ""My File Name"" ); try { OutputStream os = item.getOutputStream(); os.write(contentBytes); os.close(); } catch(IOException e) { fail(""Unexpected IOException"" + e); } return item; } ",TRUE,DiskFileItemSerializeTest.java " private FileItem createFileItem(byte[] contentBytes) { FileItemFactory factory = new DiskFileItemFactory(threshold, null); String textFieldName = ""textField""; FileItem item = factory.createItem( textFieldName, textContentType, true, ""My File Name"" ); try { OutputStream os = item.getOutputStream(); os.write(contentBytes); os.close(); } catch(IOException e) { fail(""Unexpected IOException"" + e); } return item; } "," private FileItem createFileItem(byte[] contentBytes) { return createFileItem(contentBytes, null); } ",TRUE,DiskFileItemSerializeTest.java " "," private ByteArrayOutputStream serialize(Object target) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(target); oos.flush(); oos.close(); return baos; } ",TRUE,DiskFileItemSerializeTest.java " "," private Object deserialize(ByteArrayOutputStream baos) throws Exception { Object result = null; ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); return result; } ",TRUE,DiskFileItemSerializeTest.java " private Object serializeDeserialize(Object target) { // Serialize the test object ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(target); oos.flush(); oos.close(); } catch (Exception e) { fail(""Exception during serialization: "" + e); } // Deserialize the test object Object result = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); } catch (Exception e) { fail(""Exception during deserialization: "" + e); } return result; } "," private Object serializeDeserialize(Object target) { // Serialize the test object ByteArrayOutputStream baos = null; try { baos = serialize(target); } catch (Exception e) { fail(""Exception during serialization: "" + e); } // Deserialize the test object Object result = null; try { result = deserialize(baos); } catch (Exception e) { fail(""Exception during deserialization: "" + e); } return result; } ",TRUE,DiskFileItemSerializeTest.java " public static JsonNode deserializeIntoTree(String contents, String fileOrHost) { JsonNode result; try { if (isJson(contents)) { result = Json.mapper().readTree(contents); } else { result = readYamlTree(contents); } } catch (IOException e) { throw new RuntimeException(""An exception was thrown while trying to deserialize the contents of "" + fileOrHost + "" into a JsonNode tree"", e); } return result; } "," public static JsonNode deserializeIntoTree(String contents, String fileOrHost) { JsonNode result; try { if (isJson(contents)) { result = Json.mapper().readTree(contents); } else { result = readYamlTree(contents); } } catch (IOException e) { throw new RuntimeException(""An exception was thrown while trying to deserialize the contents of "" + fileOrHost + "" into a JsonNode tree"", e); } return result; } ",FALSE,DeserializationUtils.java " public static T deserialize(Object contents, String fileOrHost, Class expectedType) { T result; boolean isJson = false; if(contents instanceof String && isJson((String)contents)) { isJson = true; } try { if (contents instanceof String) { if (isJson) { result = Json.mapper().readValue((String) contents, expectedType); } else { result = Yaml.mapper().readValue((String) contents, expectedType); } } else { result = Json.mapper().convertValue(contents, expectedType); } } catch (Exception e) { throw new RuntimeException(""An exception was thrown while trying to deserialize the contents of "" + fileOrHost + "" into type "" + expectedType, e); } return result; } "," public static T deserialize(Object contents, String fileOrHost, Class expectedType) { T result; boolean isJson = false; if(contents instanceof String && isJson((String)contents)) { isJson = true; } try { if (contents instanceof String) { if (isJson) { result = Json.mapper().readValue((String) contents, expectedType); } else { result = Yaml.mapper().readValue((String) contents, expectedType); } } else { result = Json.mapper().convertValue(contents, expectedType); } } catch (Exception e) { throw new RuntimeException(""An exception was thrown while trying to deserialize the contents of "" + fileOrHost + "" into type "" + expectedType, e); } return result; } ",FALSE,DeserializationUtils.java " private static boolean isJson(String contents) { return contents.toString().trim().startsWith(""{""); } "," private static boolean isJson(String contents) { return contents.toString().trim().startsWith(""{""); } ",FALSE,DeserializationUtils.java " public static JsonNode readYamlTree(String contents) { org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml(); return Json.mapper().convertValue(yaml.load(contents), JsonNode.class); } "," public static JsonNode readYamlTree(String contents) { org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml(new SafeConstructor()); return Json.mapper().convertValue(yaml.load(contents), JsonNode.class); } ",TRUE,DeserializationUtils.java " public static T readYamlValue(String contents, Class expectedType) { org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml(); return Json.mapper().convertValue(yaml.load(contents), expectedType); } "," public static T readYamlValue(String contents, Class expectedType) { org.yaml.snakeyaml.Yaml yaml = new org.yaml.snakeyaml.Yaml(new SafeConstructor()); return Json.mapper().convertValue(yaml.load(contents), expectedType); } ",TRUE,DeserializationUtils.java " public Commandline( String toProcess, Shell shell ) { this.shell = shell; String[] tmp = new String[0]; try { tmp = CommandLineUtils.translateCommandline( toProcess ); } catch ( Exception e ) { System.err.println( ""Error translating Commandline."" ); } if ( ( tmp != null ) && ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) { createArgument().setValue( tmp[i] ); } } } "," public Commandline( String toProcess, Shell shell ) { this.shell = shell; String[] tmp = new String[0]; try { tmp = CommandLineUtils.translateCommandline( toProcess ); } catch ( Exception e ) { System.err.println( ""Error translating Commandline."" ); } if ( ( tmp != null ) && ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) { createArgument().setValue( tmp[i] ); } } } ",FALSE,Commandline.java " public Commandline( Shell shell ) { this.shell = shell; } "," public Commandline( Shell shell ) { this.shell = shell; } ",FALSE,Commandline.java " public Commandline( String toProcess ) { setDefaultShell(); String[] tmp = new String[0]; try { tmp = CommandLineUtils.translateCommandline( toProcess ); } catch ( Exception e ) { System.err.println( ""Error translating Commandline."" ); } if ( ( tmp != null ) && ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) { createArgument().setValue( tmp[i] ); } } } "," public Commandline( String toProcess ) { setDefaultShell(); String[] tmp = new String[0]; try { tmp = CommandLineUtils.translateCommandline( toProcess ); } catch ( Exception e ) { System.err.println( ""Error translating Commandline."" ); } if ( ( tmp != null ) && ( tmp.length > 0 ) ) { setExecutable( tmp[0] ); for ( int i = 1; i < tmp.length; i++ ) { createArgument().setValue( tmp[i] ); } } } ",FALSE,Commandline.java " public Commandline() { setDefaultShell(); } "," public Commandline() { setDefaultShell(); } ",FALSE,Commandline.java " public long getPid() { if ( pid == -1 ) { pid = Long.parseLong( String.valueOf( System.currentTimeMillis() ) ); } return pid; } "," public long getPid() { if ( pid == -1 ) { pid = Long.parseLong( String.valueOf( System.currentTimeMillis() ) ); } return pid; } ",FALSE,Commandline.java " public void setPid( long pid ) { this.pid = pid; } "," public void setPid( long pid ) { this.pid = pid; } ",FALSE,Commandline.java " Marker( int position ) { this.position = position; } "," Marker( int position ) { this.position = position; } ",FALSE,Commandline.java " public int getPosition() { if ( realPos == -1 ) { realPos = ( getExecutable() == null ? 0 : 1 ); for ( int i = 0; i < position; i++ ) { Arg arg = (Arg) arguments.elementAt( i ); realPos += arg.getParts().length; } } return realPos; } "," public int getPosition() { if ( realPos == -1 ) { realPos = ( getLiteralExecutable() == null ? 0 : 1 ); for ( int i = 0; i < position; i++ ) { Arg arg = (Arg) arguments.elementAt( i ); realPos += arg.getParts().length; } } return realPos; } ",TRUE,Commandline.java " private void setDefaultShell() { //If this is windows set the shell to command.com or cmd.exe with correct arguments. if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { if ( Os.isFamily( Os.FAMILY_WIN9X ) ) { setShell( new CommandShell() ); } else { setShell( new CmdShell() ); } } else { setShell( new BourneShell() ); } } "," private void setDefaultShell() { //If this is windows set the shell to command.com or cmd.exe with correct arguments. if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { if ( Os.isFamily( Os.FAMILY_WIN9X ) ) { setShell( new CommandShell() ); } else { setShell( new CmdShell() ); } } else { setShell( new BourneShell() ); } } ",FALSE,Commandline.java " public Argument createArgument() { return this.createArgument( false ); } "," public Argument createArgument() { return this.createArgument( false ); } ",FALSE,Commandline.java " public Argument createArgument( boolean insertAtStart ) { Argument argument = new Argument(); if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } return argument; } "," public Argument createArgument( boolean insertAtStart ) { Argument argument = new Argument(); if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } return argument; } ",FALSE,Commandline.java " public Arg createArg() { return this.createArg( false ); } "," public Arg createArg() { return this.createArg( false ); } ",FALSE,Commandline.java " public Arg createArg( boolean insertAtStart ) { Arg argument = new Argument(); if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } return argument; } "," public Arg createArg( boolean insertAtStart ) { Arg argument = new Argument(); if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } return argument; } ",FALSE,Commandline.java " public void addArg( Arg argument ) { this.addArg( argument, false ); } "," public void addArg( Arg argument ) { this.addArg( argument, false ); } ",FALSE,Commandline.java " public void addArg( Arg argument, boolean insertAtStart ) { if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } } "," public void addArg( Arg argument, boolean insertAtStart ) { if ( insertAtStart ) { arguments.insertElementAt( argument, 0 ); } else { arguments.addElement( argument ); } } ",FALSE,Commandline.java " public void setExecutable( String executable ) { shell.setExecutable( executable ); this.executable = executable; } "," public void setExecutable( String executable ) { shell.setExecutable( executable ); this.executable = executable; } ",FALSE,Commandline.java " } "," public String getLiteralExecutable() { return executable; } ",TRUE,Commandline.java " public String getExecutable() { String exec = shell.getExecutable(); if ( exec == null ) { exec = executable; } return exec; } "," public String getExecutable() { String exec = shell.getExecutable(); if ( exec == null ) { exec = executable; } return exec; } ",FALSE,Commandline.java " public void addArguments( String[] line ) { for ( int i = 0; i < line.length; i++ ) { createArgument().setValue( line[i] ); } } "," public void addArguments( String[] line ) { for ( int i = 0; i < line.length; i++ ) { createArgument().setValue( line[i] ); } } ",FALSE,Commandline.java " public void addEnvironment( String name, String value ) { //envVars.add( name + ""="" + value ); envVars.put( name, value ); } "," public void addEnvironment( String name, String value ) { //envVars.add( name + ""="" + value ); envVars.put( name, value ); } ",FALSE,Commandline.java " public void addSystemEnvironment() throws Exception { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); for ( Iterator i = systemEnvVars.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); if ( !envVars.containsKey( key ) ) { addEnvironment( key, systemEnvVars.getProperty( key ) ); } } } "," public void addSystemEnvironment() throws Exception { Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); for ( Iterator i = systemEnvVars.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); if ( !envVars.containsKey( key ) ) { addEnvironment( key, systemEnvVars.getProperty( key ) ); } } } ",FALSE,Commandline.java " public String[] getEnvironmentVariables() throws CommandLineException { try { addSystemEnvironment(); } catch ( Exception e ) { throw new CommandLineException( ""Error setting up environmental variables"", e ); } String[] environmentVars = new String[envVars.size()]; int i = 0; for ( Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); ) { String name = (String) iterator.next(); String value = (String) envVars.get( name ); environmentVars[i] = name + ""="" + value; i++; } return environmentVars; } "," public String[] getEnvironmentVariables() throws CommandLineException { try { addSystemEnvironment(); } catch ( Exception e ) { throw new CommandLineException( ""Error setting up environmental variables"", e ); } String[] environmentVars = new String[envVars.size()]; int i = 0; for ( Iterator iterator = envVars.keySet().iterator(); iterator.hasNext(); ) { String name = (String) iterator.next(); String value = (String) envVars.get( name ); environmentVars[i] = name + ""="" + value; i++; } return environmentVars; } ",FALSE,Commandline.java " public String[] getCommandline() { final String[] args = getArguments(); String executable = getExecutable(); if ( executable == null ) { return args; } final String[] result = new String[args.length + 1]; result[0] = executable; System.arraycopy( args, 0, result, 1, args.length ); return result; } "," public String[] getCommandline() { final String[] args = getArguments(); String executable = getLiteralExecutable(); if ( executable == null ) { return args; } final String[] result = new String[args.length + 1]; result[0] = executable; System.arraycopy( args, 0, result, 1, args.length ); return result; } ",TRUE,Commandline.java " public String[] getShellCommandline() { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); return (String[]) getShell().getShellCommandLine( getArguments() ).toArray( new String[0] ); } "," public String[] getShellCommandline() { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); return (String[]) getShell().getShellCommandLine( getArguments() ).toArray( new String[0] ); } ",FALSE,Commandline.java " public String[] getArguments() { Vector result = new Vector( arguments.size() * 2 ); for ( int i = 0; i < arguments.size(); i++ ) { Argument arg = (Argument) arguments.elementAt( i ); String[] s = arg.getParts(); if ( s != null ) { for ( int j = 0; j < s.length; j++ ) { result.addElement( s[j] ); } } } String[] res = new String[result.size()]; result.copyInto( res ); return res; } "," public String[] getArguments() { Vector result = new Vector( arguments.size() * 2 ); for ( int i = 0; i < arguments.size(); i++ ) { Argument arg = (Argument) arguments.elementAt( i ); String[] s = arg.getParts(); if ( s != null ) { for ( int j = 0; j < s.length; j++ ) { result.addElement( s[j] ); } } } String[] res = new String[result.size()]; result.copyInto( res ); return res; } ",FALSE,Commandline.java " public String toString() { return StringUtils.join( getShellCommandline(), "" "" ); } "," public String toString() { return StringUtils.join( getShellCommandline(), "" "" ); } ",FALSE,Commandline.java " public int size() { return getCommandline().length; } "," public int size() { return getCommandline().length; } ",FALSE,Commandline.java " public Object clone() { Commandline c = new Commandline( (Shell) shell.clone() ); c.executable = executable; c.workingDir = workingDir; c.addArguments( getArguments() ); return c; } "," public Object clone() { Commandline c = new Commandline( (Shell) shell.clone() ); c.executable = executable; c.workingDir = workingDir; c.addArguments( getArguments() ); return c; } ",FALSE,Commandline.java " public void clear() { executable = null; workingDir = null; shell.setExecutable( null ); shell.clearArguments(); arguments.removeAllElements(); } "," public void clear() { executable = null; workingDir = null; shell.setExecutable( null ); shell.clearArguments(); arguments.removeAllElements(); } ",FALSE,Commandline.java " public void clearArgs() { arguments.removeAllElements(); } "," public void clearArgs() { arguments.removeAllElements(); } ",FALSE,Commandline.java " public Marker createMarker() { return new Marker( arguments.size() ); } "," public Marker createMarker() { return new Marker( arguments.size() ); } ",FALSE,Commandline.java " public void setWorkingDirectory( String path ) { shell.setWorkingDirectory( path ); workingDir = new File( path ); } "," public void setWorkingDirectory( String path ) { shell.setWorkingDirectory( path ); workingDir = new File( path ); } ",FALSE,Commandline.java " public void setWorkingDirectory( File workingDirectory ) { shell.setWorkingDirectory( workingDirectory ); workingDir = workingDirectory; } "," public void setWorkingDirectory( File workingDirectory ) { shell.setWorkingDirectory( workingDirectory ); workingDir = workingDirectory; } ",FALSE,Commandline.java " public File getWorkingDirectory() { File workDir = shell.getWorkingDirectory(); if ( workDir == null ) { workDir = workingDir; } return workDir; } "," public File getWorkingDirectory() { File workDir = shell.getWorkingDirectory(); if ( workDir == null ) { workDir = workingDir; } return workDir; } ",FALSE,Commandline.java " public Process execute() throws CommandLineException { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); Process process; //addEnvironment( ""MAVEN_TEST_ENVAR"", ""MAVEN_TEST_ENVAR_VALUE"" ); String[] environment = getEnvironmentVariables(); File workingDir = shell.getWorkingDirectory(); try { if ( workingDir == null ) { process = Runtime.getRuntime().exec( getShellCommandline(), environment ); } else { if ( !workingDir.exists() ) { throw new CommandLineException( ""Working directory \"""" + workingDir.getPath() + ""\"" does not exist!"" ); } else if ( !workingDir.isDirectory() ) { throw new CommandLineException( ""Path \"""" + workingDir.getPath() + ""\"" does not specify a directory."" ); } process = Runtime.getRuntime().exec( getShellCommandline(), environment, workingDir ); } } catch ( IOException ex ) { throw new CommandLineException( ""Error while executing process."", ex ); } return process; } "," public Process execute() throws CommandLineException { // TODO: Provided only for backward compat. with <= 1.4 verifyShellState(); Process process; //addEnvironment( ""MAVEN_TEST_ENVAR"", ""MAVEN_TEST_ENVAR_VALUE"" ); String[] environment = getEnvironmentVariables(); File workingDir = shell.getWorkingDirectory(); try { if ( workingDir == null ) { process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir ); } else { if ( !workingDir.exists() ) { throw new CommandLineException( ""Working directory \"""" + workingDir.getPath() + ""\"" does not exist!"" ); } else if ( !workingDir.isDirectory() ) { throw new CommandLineException( ""Path \"""" + workingDir.getPath() + ""\"" does not specify a directory."" ); } process = Runtime.getRuntime().exec( getCommandline(), environment, workingDir ); } } catch ( IOException ex ) { throw new CommandLineException( ""Error while executing process."", ex ); } return process; } ",TRUE,Commandline.java " private void verifyShellState() { if ( shell.getWorkingDirectory() == null ) { shell.setWorkingDirectory( workingDir ); } if ( shell.getExecutable() == null ) { shell.setExecutable( executable ); } } "," private void verifyShellState() { if ( shell.getWorkingDirectory() == null ) { shell.setWorkingDirectory( workingDir ); } if ( shell.getOriginalExecutable() == null ) { shell.setExecutable( executable ); } } ",TRUE,Commandline.java " public Properties getSystemEnvVars() throws Exception { return CommandLineUtils.getSystemEnvVars(); } "," public Properties getSystemEnvVars() throws Exception { return CommandLineUtils.getSystemEnvVars(); } ",FALSE,Commandline.java " public void setShell( Shell shell ) { this.shell = shell; } "," public void setShell( Shell shell ) { this.shell = shell; } ",FALSE,Commandline.java " public Shell getShell() { return shell; } "," public Shell getShell() { return shell; } ",FALSE,Commandline.java " public static String[] translateCommandline( String toProcess ) throws Exception { return CommandLineUtils.translateCommandline( toProcess ); } "," public static String[] translateCommandline( String toProcess ) throws Exception { return CommandLineUtils.translateCommandline( toProcess ); } ",FALSE,Commandline.java " public static String quoteArgument( String argument ) throws CommandLineException { return CommandLineUtils.quote( argument ); } "," public static String quoteArgument( String argument ) throws CommandLineException { return CommandLineUtils.quote( argument ); } ",FALSE,Commandline.java " public static String toString( String[] line ) { return CommandLineUtils.toString( line ); } "," public static String toString( String[] line ) { return CommandLineUtils.toString( line ); } ",FALSE,Commandline.java " public void setValue( String value ) { if ( value != null ) { parts = new String[] { value }; } } "," public void setValue( String value ) { if ( value != null ) { parts = new String[] { value }; } } ",FALSE,Commandline.java " public void setLine( String line ) { if ( line == null ) { return; } try { parts = CommandLineUtils.translateCommandline( line ); } catch ( Exception e ) { System.err.println( ""Error translating Commandline."" ); } } "," public void setLine( String line ) { if ( line == null ) { return; } try { parts = CommandLineUtils.translateCommandline( line ); } catch ( Exception e ) { System.err.println( ""Error translating Commandline."" ); } } ",FALSE,Commandline.java " public void setFile( File value ) { parts = new String[] { value.getAbsolutePath() }; } "," public void setFile( File value ) { parts = new String[] { value.getAbsolutePath() }; } ",FALSE,Commandline.java " public String[] getParts() { return parts; } "," public String[] getParts() { return parts; } ",FALSE,Commandline.java " public BourneShell() { this( false ); } "," public BourneShell() { this(false); } ",TRUE,BourneShell.java " public BourneShell( boolean isLoginShell ) { setShellCommand( ""/bin/sh"" ); setArgumentQuoteDelimiter( '\'' ); setExecutableQuoteDelimiter( '\""' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); setArgumentEscapePattern(""'\\%s'""); if ( isLoginShell ) { addShellArg( ""-l"" ); } } "," public BourneShell( boolean isLoginShell ) { setUnconditionalQuoting( true ); setShellCommand( ""/bin/sh"" ); setArgumentQuoteDelimiter( '\'' ); setExecutableQuoteDelimiter( '\'' ); setSingleQuotedArgumentEscaped( true ); setSingleQuotedExecutableEscaped( false ); setQuotedExecutableEnabled( true ); setArgumentEscapePattern(""'\\%s'""); if ( isLoginShell ) { addShellArg( ""-l"" ); } } ",TRUE,BourneShell.java " public String getExecutable() { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { return super.getExecutable(); } return unifyQuotes( super.getExecutable()); } "," public String getExecutable() { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { return super.getExecutable(); } return quoteOneItem( super.getOriginalExecutable(), true ); } ",TRUE,BourneShell.java " public List getShellArgsList() { List shellArgs = new ArrayList(); List existingShellArgs = super.getShellArgsList(); if ( ( existingShellArgs != null ) && !existingShellArgs.isEmpty() ) { shellArgs.addAll( existingShellArgs ); } shellArgs.add( ""-c"" ); return shellArgs; } "," public List getShellArgsList() { List shellArgs = new ArrayList(); List existingShellArgs = super.getShellArgsList(); if ( ( existingShellArgs != null ) && !existingShellArgs.isEmpty() ) { shellArgs.addAll( existingShellArgs ); } shellArgs.add( ""-c"" ); return shellArgs; } ",FALSE,BourneShell.java " public String[] getShellArgs() { String[] shellArgs = super.getShellArgs(); if ( shellArgs == null ) { shellArgs = new String[0]; } if ( ( shellArgs.length > 0 ) && !shellArgs[shellArgs.length - 1].equals( ""-c"" ) ) { String[] newArgs = new String[shellArgs.length + 1]; System.arraycopy( shellArgs, 0, newArgs, 0, shellArgs.length ); newArgs[shellArgs.length] = ""-c""; shellArgs = newArgs; } return shellArgs; } "," public String[] getShellArgs() { String[] shellArgs = super.getShellArgs(); if ( shellArgs == null ) { shellArgs = new String[0]; } if ( ( shellArgs.length > 0 ) && !shellArgs[shellArgs.length - 1].equals( ""-c"" ) ) { String[] newArgs = new String[shellArgs.length + 1]; System.arraycopy( shellArgs, 0, newArgs, 0, shellArgs.length ); newArgs[shellArgs.length] = ""-c""; shellArgs = newArgs; } return shellArgs; } ",FALSE,BourneShell.java " protected String getExecutionPreamble() { if ( getWorkingDirectoryAsString() == null ) { return null; } String dir = getWorkingDirectoryAsString(); StringBuilder sb = new StringBuilder(); sb.append( ""cd "" ); sb.append( unifyQuotes( dir ) ); sb.append( "" && "" ); return sb.toString(); } "," protected String getExecutionPreamble() { if ( getWorkingDirectoryAsString() == null ) { return null; } String dir = getWorkingDirectoryAsString(); StringBuilder sb = new StringBuilder(); sb.append( ""cd "" ); sb.append( quoteOneItem( dir, false ) ); sb.append( "" && "" ); return sb.toString(); } ",TRUE,BourneShell.java " } "," protected String quoteOneItem( String path, boolean isExecutable ) { if ( path == null ) { return null; } StringBuilder sb = new StringBuilder(); sb.append( ""'"" ); sb.append( path.replace( ""'"", ""'\""'\""'"" ) ); sb.append( ""'"" ); return sb.toString(); } ",TRUE,BourneShell.java " } "," public void setUnconditionalQuoting(boolean unconditionallyQuote) { this.unconditionallyQuote = unconditionallyQuote; } ",TRUE,Shell.java " public void setShellCommand( String shellCommand ) { this.shellCommand = shellCommand; } "," public void setShellCommand( String shellCommand ) { this.shellCommand = shellCommand; } ",FALSE,Shell.java " public String getShellCommand() { return shellCommand; } "," public String getShellCommand() { return shellCommand; } ",FALSE,Shell.java " public void setShellArgs( String[] shellArgs ) { this.shellArgs.clear(); this.shellArgs.addAll( Arrays.asList( shellArgs ) ); } "," public void setShellArgs( String[] shellArgs ) { this.shellArgs.clear(); this.shellArgs.addAll( Arrays.asList( shellArgs ) ); } ",FALSE,Shell.java " public String[] getShellArgs() { if ( ( shellArgs == null ) || shellArgs.isEmpty() ) { return null; } else { return (String[]) shellArgs.toArray( new String[shellArgs.size()] ); } } "," public String[] getShellArgs() { if ( ( shellArgs == null ) || shellArgs.isEmpty() ) { return null; } else { return (String[]) shellArgs.toArray( new String[shellArgs.size()] ); } } ",FALSE,Shell.java " public List getCommandLine( String executable, String[] arguments ) { return getRawCommandLine( executable, arguments ); } "," public List getCommandLine( String executable, String[] arguments ) { return getRawCommandLine( executable, arguments ); } ",FALSE,Shell.java " } "," protected String quoteOneItem(String inputString, boolean isExecutable) { char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); return StringUtils.quoteAndEscape( inputString, isExecutable ? getExecutableQuoteDelimiter() : getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', unconditionallyQuote ); } ",TRUE,Shell.java " protected List getRawCommandLine( String executable, String[] arguments ) { List commandLine = new ArrayList(); StringBuilder sb = new StringBuilder(); if ( executable != null ) { String preamble = getExecutionPreamble(); if ( preamble != null ) { sb.append( preamble ); } if ( isQuotedExecutableEnabled() ) { char[] escapeChars = getEscapeChars( isSingleQuotedExecutableEscaped(), isDoubleQuotedExecutableEscaped() ); sb.append( StringUtils.quoteAndEscape( getExecutable(), getExecutableQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), '\\', false ) ); } else { sb.append( getExecutable() ); } } for ( int i = 0; i < arguments.length; i++ ) { if ( sb.length() > 0 ) { sb.append( "" "" ); } if ( isQuotedArgumentsEnabled() ) { char[] escapeChars = getEscapeChars( isSingleQuotedArgumentEscaped(), isDoubleQuotedArgumentEscaped() ); sb.append( StringUtils.quoteAndEscape( arguments[i], getArgumentQuoteDelimiter(), escapeChars, getQuotingTriggerChars(), getArgumentEscapePattern(), false ) ); } else { sb.append( arguments[i] ); } } commandLine.add( sb.toString() ); return commandLine; } "," protected List getRawCommandLine( String executable, String[] arguments ) { List commandLine = new ArrayList(); StringBuilder sb = new StringBuilder(); if ( executable != null ) { String preamble = getExecutionPreamble(); if ( preamble != null ) { sb.append( preamble ); } if ( isQuotedExecutableEnabled() ) { sb.append( quoteOneItem( getOriginalExecutable(), true ) ); } else { sb.append( getExecutable() ); } } for ( int i = 0; i < arguments.length; i++ ) { if ( sb.length() > 0 ) { sb.append( "" "" ); } if ( isQuotedArgumentsEnabled() ) { sb.append( quoteOneItem( arguments[i], false ) ); } else { sb.append( arguments[i] ); } } commandLine.add( sb.toString() ); return commandLine; } ",TRUE,Shell.java " protected char[] getQuotingTriggerChars() { return DEFAULT_QUOTING_TRIGGER_CHARS; } "," protected char[] getQuotingTriggerChars() { return DEFAULT_QUOTING_TRIGGER_CHARS; } ",FALSE,Shell.java " protected String getExecutionPreamble() { return null; } "," protected String getExecutionPreamble() { return null; } ",FALSE,Shell.java " protected char[] getEscapeChars( boolean includeSingleQuote, boolean includeDoubleQuote ) { StringBuilder buf = new StringBuilder( 2 ); if ( includeSingleQuote ) { buf.append( '\'' ); } if ( includeDoubleQuote ) { buf.append( '\""' ); } char[] result = new char[buf.length()]; buf.getChars( 0, buf.length(), result, 0 ); return result; } "," protected char[] getEscapeChars( boolean includeSingleQuote, boolean includeDoubleQuote ) { StringBuilder buf = new StringBuilder( 2 ); if ( includeSingleQuote ) { buf.append( '\'' ); } if ( includeDoubleQuote ) { buf.append( '\""' ); } char[] result = new char[buf.length()]; buf.getChars( 0, buf.length(), result, 0 ); return result; } ",FALSE,Shell.java " protected boolean isDoubleQuotedArgumentEscaped() { return doubleQuotedArgumentEscaped; } "," protected boolean isDoubleQuotedArgumentEscaped() { return doubleQuotedArgumentEscaped; } ",FALSE,Shell.java " protected boolean isSingleQuotedArgumentEscaped() { return singleQuotedArgumentEscaped; } "," protected boolean isSingleQuotedArgumentEscaped() { return singleQuotedArgumentEscaped; } ",FALSE,Shell.java " protected boolean isDoubleQuotedExecutableEscaped() { return doubleQuotedExecutableEscaped; } "," protected boolean isDoubleQuotedExecutableEscaped() { return doubleQuotedExecutableEscaped; } ",FALSE,Shell.java " protected boolean isSingleQuotedExecutableEscaped() { return singleQuotedExecutableEscaped; } "," protected boolean isSingleQuotedExecutableEscaped() { return singleQuotedExecutableEscaped; } ",FALSE,Shell.java " protected void setArgumentQuoteDelimiter( char argQuoteDelimiter ) { this.argQuoteDelimiter = argQuoteDelimiter; } "," protected void setArgumentQuoteDelimiter( char argQuoteDelimiter ) { this.argQuoteDelimiter = argQuoteDelimiter; } ",FALSE,Shell.java " protected char getArgumentQuoteDelimiter() { return argQuoteDelimiter; } "," protected char getArgumentQuoteDelimiter() { return argQuoteDelimiter; } ",FALSE,Shell.java " protected void setExecutableQuoteDelimiter( char exeQuoteDelimiter ) { this.exeQuoteDelimiter = exeQuoteDelimiter; } "," protected void setExecutableQuoteDelimiter( char exeQuoteDelimiter ) { this.exeQuoteDelimiter = exeQuoteDelimiter; } ",FALSE,Shell.java " protected char getExecutableQuoteDelimiter() { return exeQuoteDelimiter; } "," protected char getExecutableQuoteDelimiter() { return exeQuoteDelimiter; } ",FALSE,Shell.java " protected void setArgumentEscapePattern(String argumentEscapePattern) { this.argumentEscapePattern = argumentEscapePattern; } "," protected void setArgumentEscapePattern(String argumentEscapePattern) { this.argumentEscapePattern = argumentEscapePattern; } ",FALSE,Shell.java " protected String getArgumentEscapePattern() { return argumentEscapePattern; } "," protected String getArgumentEscapePattern() { return argumentEscapePattern; } ",FALSE,Shell.java " public List getShellCommandLine( String[] arguments ) { List commandLine = new ArrayList(); if ( getShellCommand() != null ) { commandLine.add( getShellCommand() ); } if ( getShellArgs() != null ) { commandLine.addAll( getShellArgsList() ); } commandLine.addAll( getCommandLine( getExecutable(), arguments ) ); return commandLine; } "," public List getShellCommandLine( String[] arguments ) { List commandLine = new ArrayList(); if ( getShellCommand() != null ) { commandLine.add( getShellCommand() ); } if ( getShellArgs() != null ) { commandLine.addAll( getShellArgsList() ); } commandLine.addAll( getCommandLine( getOriginalExecutable(), arguments ) ); return commandLine; } ",TRUE,Shell.java " public List getShellArgsList() { return shellArgs; } "," public List getShellArgsList() { return shellArgs; } ",FALSE,Shell.java " public void addShellArg( String arg ) { shellArgs.add( arg ); } "," public void addShellArg( String arg ) { shellArgs.add( arg ); } ",FALSE,Shell.java " public void setQuotedArgumentsEnabled( boolean quotedArgumentsEnabled ) { this.quotedArgumentsEnabled = quotedArgumentsEnabled; } "," public void setQuotedArgumentsEnabled( boolean quotedArgumentsEnabled ) { this.quotedArgumentsEnabled = quotedArgumentsEnabled; } ",FALSE,Shell.java " public boolean isQuotedArgumentsEnabled() { return quotedArgumentsEnabled; } "," public boolean isQuotedArgumentsEnabled() { return quotedArgumentsEnabled; } ",FALSE,Shell.java " public void setQuotedExecutableEnabled( boolean quotedExecutableEnabled ) { this.quotedExecutableEnabled = quotedExecutableEnabled; } "," public void setQuotedExecutableEnabled( boolean quotedExecutableEnabled ) { this.quotedExecutableEnabled = quotedExecutableEnabled; } ",FALSE,Shell.java " public boolean isQuotedExecutableEnabled() { return quotedExecutableEnabled; } "," public boolean isQuotedExecutableEnabled() { return quotedExecutableEnabled; } ",FALSE,Shell.java " public void setExecutable( String executable ) { if ( ( executable == null ) || ( executable.length() == 0 ) ) { return; } this.executable = executable.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); } "," public void setExecutable( String executable ) { if ( ( executable == null ) || ( executable.length() == 0 ) ) { return; } this.executable = executable.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); } ",FALSE,Shell.java " public String getExecutable() { return executable; } "," public String getExecutable() { return executable; } ",FALSE,Shell.java " public void setWorkingDirectory( String path ) { if ( path != null ) { workingDir = path; } } "," public void setWorkingDirectory( String path ) { if ( path != null ) { workingDir = path; } } ",FALSE,Shell.java " public void setWorkingDirectory( File workingDir ) { if ( workingDir != null ) { this.workingDir = workingDir.getAbsolutePath(); } } "," public void setWorkingDirectory( File workingDir ) { if ( workingDir != null ) { this.workingDir = workingDir.getAbsolutePath(); } } ",FALSE,Shell.java " public File getWorkingDirectory() { return workingDir == null ? null : new File( workingDir ); } "," public File getWorkingDirectory() { return workingDir == null ? null : new File( workingDir ); } ",FALSE,Shell.java " public String getWorkingDirectoryAsString() { return workingDir; } "," public String getWorkingDirectoryAsString() { return workingDir; } ",FALSE,Shell.java " public void clearArguments() { shellArgs.clear(); } "," public void clearArguments() { shellArgs.clear(); } ",FALSE,Shell.java " public Object clone() { Shell shell = new Shell(); shell.setExecutable( getExecutable() ); shell.setWorkingDirectory( getWorkingDirectory() ); shell.setShellArgs( getShellArgs() ); return shell; } "," public Object clone() { Shell shell = new Shell(); shell.setExecutable( getExecutable() ); shell.setWorkingDirectory( getWorkingDirectory() ); shell.setShellArgs( getShellArgs() ); return shell; } ",FALSE,Shell.java " public String getOriginalExecutable() { return executable; } "," public String getOriginalExecutable() { return executable; } ",FALSE,Shell.java " public List getOriginalCommandLine( String executable, String[] arguments ) { return getRawCommandLine( executable, arguments ); } "," public List getOriginalCommandLine( String executable, String[] arguments ) { return getRawCommandLine( executable, arguments ); } ",FALSE,Shell.java " protected void setDoubleQuotedArgumentEscaped( boolean doubleQuotedArgumentEscaped ) { this.doubleQuotedArgumentEscaped = doubleQuotedArgumentEscaped; } "," protected void setDoubleQuotedArgumentEscaped( boolean doubleQuotedArgumentEscaped ) { this.doubleQuotedArgumentEscaped = doubleQuotedArgumentEscaped; } ",FALSE,Shell.java " protected void setDoubleQuotedExecutableEscaped( boolean doubleQuotedExecutableEscaped ) { this.doubleQuotedExecutableEscaped = doubleQuotedExecutableEscaped; } "," protected void setDoubleQuotedExecutableEscaped( boolean doubleQuotedExecutableEscaped ) { this.doubleQuotedExecutableEscaped = doubleQuotedExecutableEscaped; } ",FALSE,Shell.java " protected void setSingleQuotedArgumentEscaped( boolean singleQuotedArgumentEscaped ) { this.singleQuotedArgumentEscaped = singleQuotedArgumentEscaped; } "," protected void setSingleQuotedArgumentEscaped( boolean singleQuotedArgumentEscaped ) { this.singleQuotedArgumentEscaped = singleQuotedArgumentEscaped; } ",FALSE,Shell.java " protected void setSingleQuotedExecutableEscaped( boolean singleQuotedExecutableEscaped ) { this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped; } "," protected void setSingleQuotedExecutableEscaped( boolean singleQuotedExecutableEscaped ) { this.singleQuotedExecutableEscaped = singleQuotedExecutableEscaped; } ",FALSE,Shell.java " public CommandlineTest( final String testName ) { super( testName ); } "," public CommandlineTest( final String testName ) { super( testName ); } ",FALSE,CommandlineTest.java " public void setUp() throws Exception { super.setUp(); baseDir = System.getProperty( ""basedir"" ); if ( baseDir == null ) { baseDir = new File( ""."" ).getCanonicalPath(); } } "," public void setUp() throws Exception { super.setUp(); baseDir = System.getProperty( ""basedir"" ); if ( baseDir == null ) { baseDir = new File( ""."" ).getCanonicalPath(); } } ",FALSE,CommandlineTest.java " public void testCommandlineWithoutCommandInConstructor() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.createArgument().setValue( ""cd"" ); cmd.createArgument().setValue( ""."" ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""cd ."", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } "," public void testCommandlineWithoutCommandInConstructor() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.createArgument().setValue( ""cd"" ); cmd.createArgument().setValue( ""."" ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""cd ."", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } ",FALSE,CommandlineTest.java " public void testCommandlineWithCommandInConstructor() { try { Commandline cmd = new Commandline( ""cd ."", new Shell() ); cmd.setWorkingDirectory( baseDir ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""cd ."", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } "," public void testCommandlineWithCommandInConstructor() { try { Commandline cmd = new Commandline( ""cd ."", new Shell() ); cmd.setWorkingDirectory( baseDir ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""cd ."", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } ",FALSE,CommandlineTest.java " public void testExecute() { try { // allow it to detect the proper shell here. Commandline cmd = new Commandline(); cmd.setWorkingDirectory( baseDir ); cmd.setExecutable( ""echo"" ); assertEquals( ""echo"", cmd.getShell().getOriginalExecutable() ); cmd.createArgument().setValue( ""Hello"" ); StringWriter swriter = new StringWriter(); Process process = cmd.execute(); Reader reader = new InputStreamReader( process.getInputStream() ); char[] chars = new char[16]; int read = -1; while ( ( read = reader.read( chars ) ) > -1 ) { swriter.write( chars, 0, read ); } String output = swriter.toString().trim(); assertEquals( ""Hello"", output ); } catch ( Exception e ) { fail( e.getMessage() ); } } "," public void testExecute() { try { // allow it to detect the proper shell here. Commandline cmd = new Commandline(); cmd.setWorkingDirectory( baseDir ); cmd.setExecutable( ""echo"" ); assertEquals( ""echo"", cmd.getShell().getOriginalExecutable() ); cmd.createArgument().setValue( ""Hello"" ); StringWriter swriter = new StringWriter(); Process process = cmd.execute(); Reader reader = new InputStreamReader( process.getInputStream() ); char[] chars = new char[16]; int read = -1; while ( ( read = reader.read( chars ) ) > -1 ) { swriter.write( chars, 0, read ); } String output = swriter.toString().trim(); assertEquals( ""Hello"", output ); } catch ( Exception e ) { fail( e.getMessage() ); } } ",FALSE,CommandlineTest.java " public void testSetLine() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.setExecutable( ""echo"" ); cmd.createArgument().setLine( null ); cmd.createArgument().setLine( ""Hello"" ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""echo Hello"", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } "," public void testSetLine() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.setExecutable( ""echo"" ); cmd.createArgument().setLine( null ); cmd.createArgument().setLine( ""Hello"" ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""echo Hello"", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } ",FALSE,CommandlineTest.java " public void testCreateCommandInReverseOrder() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.createArgument().setValue( ""."" ); cmd.createArgument( true ).setValue( ""cd"" ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""cd ."", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } "," public void testCreateCommandInReverseOrder() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.createArgument().setValue( ""."" ); cmd.createArgument( true ).setValue( ""cd"" ); // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""cd ."", cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } ",FALSE,CommandlineTest.java " public void testSetFile() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.createArgument().setValue( ""more"" ); File f = new File( ""test.txt"" ); cmd.createArgument().setFile( f ); String fileName = f.getAbsolutePath(); if ( fileName.indexOf( "" "" ) >= 0 ) { fileName = ""\"""" + fileName + ""\""""; } // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""more "" + fileName, cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } "," public void testSetFile() { try { Commandline cmd = new Commandline( new Shell() ); cmd.setWorkingDirectory( baseDir ); cmd.createArgument().setValue( ""more"" ); File f = new File( ""test.txt"" ); cmd.createArgument().setFile( f ); String fileName = f.getAbsolutePath(); if ( fileName.indexOf( "" "" ) >= 0 ) { fileName = ""\"""" + fileName + ""\""""; } // NOTE: cmd.toString() uses CommandLineUtils.toString( String[] ), which *quotes* the result. assertEquals( ""more "" + fileName, cmd.toString() ); } catch ( Exception e ) { fail( e.getMessage() ); } } ",FALSE,CommandlineTest.java " public void testGetShellCommandLineWindows() throws Exception { Commandline cmd = new Commandline( new CmdShell() ); cmd.setExecutable( ""c:\\Program Files\\xxx"" ); cmd.addArguments( new String[] { ""a"", ""b"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 4, shellCommandline.length ); assertEquals( ""cmd.exe"", shellCommandline[0] ); assertEquals( ""/X"", shellCommandline[1] ); assertEquals( ""/C"", shellCommandline[2] ); String expectedShellCmd = ""\""c:"" + File.separator + ""Program Files"" + File.separator + ""xxx\"" a b""; expectedShellCmd = ""\"""" + expectedShellCmd + ""\""""; assertEquals( expectedShellCmd, shellCommandline[3] ); } "," public void testGetShellCommandLineWindows() throws Exception { Commandline cmd = new Commandline( new CmdShell() ); cmd.setExecutable( ""c:\\Program Files\\xxx"" ); cmd.addArguments( new String[] { ""a"", ""b"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 4, shellCommandline.length ); assertEquals( ""cmd.exe"", shellCommandline[0] ); assertEquals( ""/X"", shellCommandline[1] ); assertEquals( ""/C"", shellCommandline[2] ); String expectedShellCmd = ""\""c:"" + File.separator + ""Program Files"" + File.separator + ""xxx\"" a b""; expectedShellCmd = ""\"""" + expectedShellCmd + ""\""""; assertEquals( expectedShellCmd, shellCommandline[3] ); } ",FALSE,CommandlineTest.java " public void testGetShellCommandLineWindowsWithSeveralQuotes() throws Exception { Commandline cmd = new Commandline( new CmdShell() ); cmd.setExecutable( ""c:\\Program Files\\xxx"" ); cmd.addArguments( new String[] { ""c:\\Documents and Settings\\whatever"", ""b"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 4, shellCommandline.length ); assertEquals( ""cmd.exe"", shellCommandline[0] ); assertEquals( ""/X"", shellCommandline[1] ); assertEquals( ""/C"", shellCommandline[2] ); String expectedShellCmd = ""\""c:"" + File.separator + ""Program Files"" + File.separator + ""xxx\"" \""c:\\Documents and Settings\\whatever\"" b""; expectedShellCmd = ""\"""" + expectedShellCmd + ""\""""; assertEquals( expectedShellCmd, shellCommandline[3] ); } "," public void testGetShellCommandLineWindowsWithSeveralQuotes() throws Exception { Commandline cmd = new Commandline( new CmdShell() ); cmd.setExecutable( ""c:\\Program Files\\xxx"" ); cmd.addArguments( new String[] { ""c:\\Documents and Settings\\whatever"", ""b"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 4, shellCommandline.length ); assertEquals( ""cmd.exe"", shellCommandline[0] ); assertEquals( ""/X"", shellCommandline[1] ); assertEquals( ""/C"", shellCommandline[2] ); String expectedShellCmd = ""\""c:"" + File.separator + ""Program Files"" + File.separator + ""xxx\"" \""c:\\Documents and Settings\\whatever\"" b""; expectedShellCmd = ""\"""" + expectedShellCmd + ""\""""; assertEquals( expectedShellCmd, shellCommandline[3] ); } ",FALSE,CommandlineTest.java " public void testGetShellCommandLineBash() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/bin/echo"" ); cmd.addArguments( new String[] { ""hello world"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); String expectedShellCmd = ""/bin/echo \'hello world\'""; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = ""\\bin\\echo \'hello world\'""; } assertEquals( expectedShellCmd, shellCommandline[2] ); } "," public void testGetShellCommandLineBash() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/bin/echo"" ); cmd.addArguments( new String[] { ""hello world"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); String expectedShellCmd = ""'/bin/echo' 'hello world'""; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = ""\\bin\\echo \'hello world\'""; } assertEquals( expectedShellCmd, shellCommandline[2] ); } ",TRUE,CommandlineTest.java " public void testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/bin/echo"" ); cmd.addArguments( new String[] { ""hello world"" } ); File root = File.listRoots()[0]; File workingDirectory = new File( root, ""path with spaces"" ); cmd.setWorkingDirectory( workingDirectory ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); String expectedShellCmd = ""cd \"""" + root.getAbsolutePath() + ""path with spaces\"" && /bin/echo \'hello world\'""; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = ""cd \"""" + root.getAbsolutePath() + ""path with spaces\"" && \\bin\\echo \'hello world\'""; } assertEquals( expectedShellCmd, shellCommandline[2] ); } "," public void testGetShellCommandLineBash_WithWorkingDirectory() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/bin/echo"" ); cmd.addArguments( new String[] { ""hello world"" } ); File root = File.listRoots()[0]; File workingDirectory = new File( root, ""path with spaces"" ); cmd.setWorkingDirectory( workingDirectory ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); String expectedShellCmd = ""cd '"" + root.getAbsolutePath() + ""path with spaces' && '/bin/echo' 'hello world'""; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = ""cd '"" + root.getAbsolutePath() + ""path with spaces' && '\\bin\\echo' 'hello world'""; } assertEquals( expectedShellCmd, shellCommandline[2] ); } ",TRUE,CommandlineTest.java " public void testGetShellCommandLineBash_WithSingleQuotedArg() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/bin/echo"" ); cmd.addArguments( new String[] { ""\'hello world\'"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); String expectedShellCmd = ""/bin/echo \'hello world\'""; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = ""\\bin\\echo \'hello world\'""; } assertEquals( expectedShellCmd, shellCommandline[2] ); } "," public void testGetShellCommandLineBash_WithSingleQuotedArg() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/bin/echo"" ); cmd.addArguments( new String[] { ""\'hello world\'"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); String expectedShellCmd = ""'/bin/echo' ''\""'\""'hello world'\""'\""''""; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { expectedShellCmd = ""\\bin\\echo \'hello world\'""; } assertEquals( expectedShellCmd, shellCommandline[2] ); } ",TRUE,CommandlineTest.java " public void testGetShellCommandLineNonWindows() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/usr/bin"" ); cmd.addArguments( new String[] { ""a"", ""b"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { assertEquals( ""\\usr\\bin a b"", shellCommandline[2] ); } else { assertEquals( ""/usr/bin a b"", shellCommandline[2] ); } } "," public void testGetShellCommandLineNonWindows() throws Exception { Commandline cmd = new Commandline( new BourneShell() ); cmd.setExecutable( ""/usr/bin"" ); cmd.addArguments( new String[] { ""a"", ""b"" } ); String[] shellCommandline = cmd.getShellCommandline(); assertEquals( ""Command line size"", 3, shellCommandline.length ); assertEquals( ""/bin/sh"", shellCommandline[0] ); assertEquals( ""-c"", shellCommandline[1] ); if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { assertEquals( ""\\usr\\bin a b"", shellCommandline[2] ); } else { assertEquals( ""'/usr/bin' 'a' 'b'"", shellCommandline[2] ); } } ",TRUE,CommandlineTest.java " public void testEnvironment() throws Exception { Commandline cmd = new Commandline(); cmd.addEnvironment( ""name"", ""value"" ); assertEquals( ""name=value"", cmd.getEnvironmentVariables()[0] ); } "," public void testEnvironment() throws Exception { Commandline cmd = new Commandline(); cmd.addEnvironment( ""name"", ""value"" ); assertEquals( ""name=value"", cmd.getEnvironmentVariables()[0] ); } ",FALSE,CommandlineTest.java " public void testEnvironmentWitOverrideSystemEnvironment() throws Exception { Commandline cmd = new Commandline(); cmd.addSystemEnvironment(); cmd.addEnvironment( ""JAVA_HOME"", ""/usr/jdk1.5"" ); String[] environmentVariables = cmd.getEnvironmentVariables(); for ( int i = 0, size = environmentVariables.length; i < size; i++ ) { if ( ""JAVA_HOME=/usr/jdk1.5"".equals( environmentVariables[i] ) ) { return; } } fail( ""can't find JAVA_HOME=/usr/jdk1.5"" ); } "," public void testEnvironmentWitOverrideSystemEnvironment() throws Exception { Commandline cmd = new Commandline(); cmd.addSystemEnvironment(); cmd.addEnvironment( ""JAVA_HOME"", ""/usr/jdk1.5"" ); String[] environmentVariables = cmd.getEnvironmentVariables(); for ( int i = 0, size = environmentVariables.length; i < size; i++ ) { if ( ""JAVA_HOME=/usr/jdk1.5"".equals( environmentVariables[i] ) ) { return; } } fail( ""can't find JAVA_HOME=/usr/jdk1.5"" ); } ",FALSE,CommandlineTest.java " public void testQuotedPathWithSingleApostrophe() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath'test"" ); createAndCallScript( dir, ""echo Quoted"" ); dir = new File( System.getProperty( ""basedir"" ), ""target/test/quoted path'test"" ); createAndCallScript( dir, ""echo Quoted"" ); } "," public void testQuotedPathWithSingleApostrophe() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath'test"" ); createAndCallScript( dir, ""echo Quoted"" ); dir = new File( System.getProperty( ""basedir"" ), ""target/test/quoted path'test"" ); createAndCallScript( dir, ""echo Quoted"" ); } ",FALSE,CommandlineTest.java " } "," public void testPathWithShellExpansionStrings() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test/dollar$test"" ); createAndCallScript( dir, ""echo Quoted"" ); } ",TRUE,CommandlineTest.java " public void testQuotedPathWithQuotationMark() throws Exception { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { System.out.println( ""testQuotedPathWithQuotationMark() skipped on Windows"" ); return; } File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath\""test"" ); createAndCallScript( dir, ""echo Quoted"" ); dir = new File( System.getProperty( ""basedir"" ), ""target/test/quoted path\""test"" ); createAndCallScript( dir, ""echo Quoted"" ); } "," public void testQuotedPathWithQuotationMark() throws Exception { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { System.out.println( ""testQuotedPathWithQuotationMark() skipped on Windows"" ); return; } File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath\""test"" ); createAndCallScript( dir, ""echo Quoted"" ); dir = new File( System.getProperty( ""basedir"" ), ""target/test/quoted path\""test"" ); createAndCallScript( dir, ""echo Quoted"" ); } ",FALSE,CommandlineTest.java " public void testQuotedPathWithQuotationMarkAndApostrophe() throws Exception { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { System.out.println( ""testQuotedPathWithQuotationMarkAndApostrophe() skipped on Windows"" ); return; } File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath\""'test"" ); createAndCallScript( dir, ""echo Quoted"" ); dir = new File( System.getProperty( ""basedir"" ), ""target/test/quoted path\""'test"" ); createAndCallScript( dir, ""echo Quoted"" ); } "," public void testQuotedPathWithQuotationMarkAndApostrophe() throws Exception { if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { System.out.println( ""testQuotedPathWithQuotationMarkAndApostrophe() skipped on Windows"" ); return; } File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath\""'test"" ); createAndCallScript( dir, ""echo Quoted"" ); dir = new File( System.getProperty( ""basedir"" ), ""target/test/quoted path\""'test"" ); createAndCallScript( dir, ""echo Quoted"" ); } ",FALSE,CommandlineTest.java " public void testOnlyQuotedPath() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath\'test"" ); File javaHome = new File( System.getProperty( ""java.home"" ) ); File java; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { java = new File( javaHome, ""/bin/java.exe"" ); } else { java = new File( javaHome, ""/bin/java"" ); } if ( !java.exists() ) { throw new IOException( java.getAbsolutePath() + "" doesn't exist"" ); } createAndCallScript( dir, java.getAbsolutePath() + "" -version"" ); } "," public void testOnlyQuotedPath() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test/quotedpath\'test"" ); File javaHome = new File( System.getProperty( ""java.home"" ) ); File java; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { java = new File( javaHome, ""/bin/java.exe"" ); } else { java = new File( javaHome, ""/bin/java"" ); } if ( !java.exists() ) { throw new IOException( java.getAbsolutePath() + "" doesn't exist"" ); } createAndCallScript( dir, java.getAbsolutePath() + "" -version"" ); } ",FALSE,CommandlineTest.java " public void testDollarSignInArgumentPath() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test"" ); if ( !dir.exists() ) { assertTrue( ""Can't create dir:"" + dir.getAbsolutePath(), dir.mkdirs() ); } FileWriter writer = null; try { writer = new FileWriter( new File( dir, ""test$1.txt"" ) ); IOUtil.copy( ""Success"", writer ); } finally { IOUtil.close( writer ); } Commandline cmd = new Commandline(); //cmd.getShell().setShellCommand( ""/bin/sh"" ); cmd.getShell().setQuotedArgumentsEnabled( true ); cmd.setExecutable( ""cat"" ); if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { cmd.setExecutable( ""dir"" ); } cmd.setWorkingDirectory( dir ); cmd.createArg().setLine( ""test$1.txt"" ); executeCommandLine( cmd ); } "," public void testDollarSignInArgumentPath() throws Exception { File dir = new File( System.getProperty( ""basedir"" ), ""target/test"" ); if ( !dir.exists() ) { assertTrue( ""Can't create dir:"" + dir.getAbsolutePath(), dir.mkdirs() ); } FileWriter writer = null; try { writer = new FileWriter( new File( dir, ""test$1.txt"" ) ); IOUtil.copy( ""Success"", writer ); } finally { IOUtil.close( writer ); } Commandline cmd = new Commandline(); //cmd.getShell().setShellCommand( ""/bin/sh"" ); cmd.getShell().setQuotedArgumentsEnabled( true ); cmd.setExecutable( ""cat"" ); if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { cmd.setExecutable( ""dir"" ); } cmd.setWorkingDirectory( dir ); cmd.createArg().setLine( ""test$1.txt"" ); executeCommandLine( cmd ); } ",FALSE,CommandlineTest.java " public void testTimeOutException() throws Exception { File javaHome = new File( System.getProperty( ""java.home"" ) ); File java; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { java = new File( javaHome, ""/bin/java.exe"" ); } else { java = new File( javaHome, ""/bin/java"" ); } if ( !java.exists() ) { throw new IOException( java.getAbsolutePath() + "" doesn't exist"" ); } Commandline cli = new Commandline(); cli.setExecutable( java.getAbsolutePath() ); cli.createArg().setLine( ""-version"" ); CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); try { // if the os is faster than 1s to execute java -version the unit will fail :-) CommandLineUtils.executeCommandLine( cli, new DefaultConsumer(), err, 1 ); } catch ( CommandLineTimeOutException e ) { // it works } } "," public void testTimeOutException() throws Exception { File javaHome = new File( System.getProperty( ""java.home"" ) ); File java; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { java = new File( javaHome, ""/bin/java.exe"" ); } else { java = new File( javaHome, ""/bin/java"" ); } if ( !java.exists() ) { throw new IOException( java.getAbsolutePath() + "" doesn't exist"" ); } Commandline cli = new Commandline(); cli.setExecutable( java.getAbsolutePath() ); cli.createArg().setLine( ""-version"" ); CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); try { // if the os is faster than 1s to execute java -version the unit will fail :-) CommandLineUtils.executeCommandLine( cli, new DefaultConsumer(), err, 1 ); } catch ( CommandLineTimeOutException e ) { // it works } } ",FALSE,CommandlineTest.java " private static void makeExecutable( File path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException( ""The file is null"" ); } if ( !path.isFile() ) { throw new IllegalArgumentException( ""The file '"" + path.getAbsolutePath() + ""' should be a file"" ); } if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) { Process proc = Runtime.getRuntime().exec( new String[] { ""chmod"", ""a+x"", path.getAbsolutePath() } ); while ( true ) { try { proc.waitFor(); break; } catch ( InterruptedException e ) { // ignore } } } } "," private static void makeExecutable( File path ) throws IOException { if ( path == null ) { throw new IllegalArgumentException( ""The file is null"" ); } if ( !path.isFile() ) { throw new IllegalArgumentException( ""The file '"" + path.getAbsolutePath() + ""' should be a file"" ); } if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) { Process proc = Runtime.getRuntime().exec( new String[] { ""chmod"", ""a+x"", path.getAbsolutePath() } ); while ( true ) { try { proc.waitFor(); break; } catch ( InterruptedException e ) { // ignore } } } } ",FALSE,CommandlineTest.java " private static void createAndCallScript( File dir, String content ) throws Exception { if ( !dir.exists() ) { assertTrue( ""Can't create dir:"" + dir.getAbsolutePath(), dir.mkdirs() ); } // Create a script file File bat; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { bat = new File( dir, ""echo.bat"" ); } else { bat = new File( dir, ""echo"" ); } Writer w = new FileWriter( bat ); try { IOUtil.copy( content, w ); } finally { IOUtil.close( w ); } // Change permission makeExecutable( bat ); Commandline cmd = new Commandline(); cmd.setExecutable( bat.getAbsolutePath() ); cmd.setWorkingDirectory( dir ); // Execute the script file executeCommandLine( cmd ); } "," private static void createAndCallScript( File dir, String content ) throws Exception { if ( !dir.exists() ) { assertTrue( ""Can't create dir:"" + dir.getAbsolutePath(), dir.mkdirs() ); } // Create a script file File bat; if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) { bat = new File( dir, ""echo.bat"" ); } else { bat = new File( dir, ""echo"" ); } Writer w = new FileWriter( bat ); try { IOUtil.copy( content, w ); } finally { IOUtil.close( w ); } // Change permission makeExecutable( bat ); Commandline cmd = new Commandline(); cmd.setExecutable( bat.getAbsolutePath() ); cmd.setWorkingDirectory( dir ); // Execute the script file executeCommandLine( cmd ); } ",FALSE,CommandlineTest.java " private static void executeCommandLine( Commandline cmd ) throws Exception { CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); try { System.out.println( ""Command line is: "" + StringUtils.join( cmd.getShellCommandline(), "" "" ) ); int exitCode = CommandLineUtils.executeCommandLine( cmd, new DefaultConsumer(), err ); if ( exitCode != 0 ) { String msg = ""Exit code: "" + exitCode + "" - "" + err.getOutput(); throw new Exception( msg.toString() ); } } catch ( CommandLineException e ) { throw new Exception( ""Unable to execute command: "" + e.getMessage(), e ); } } "," private static void executeCommandLine( Commandline cmd ) throws Exception { CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); try { System.out.println( ""Command line is: "" + StringUtils.join( cmd.getShellCommandline(), "" "" ) ); int exitCode = CommandLineUtils.executeCommandLine( cmd, new DefaultConsumer(), err ); if ( exitCode != 0 ) { String msg = ""Exit code: "" + exitCode + "" - "" + err.getOutput(); throw new Exception( msg.toString() ); } } catch ( CommandLineException e ) { throw new Exception( ""Unable to execute command: "" + e.getMessage(), e ); } } ",FALSE,CommandlineTest.java " protected Shell newShell() { return new BourneShell(); } "," protected Shell newShell() { return new BourneShell(); } ",FALSE,BourneShellTest.java " public void testQuoteWorkingDirectoryAndExecutable() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/local/bin"" ); sh.setExecutable( ""chmod"" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), "" "" ); assertEquals( ""/bin/sh -c cd /usr/local/bin && chmod"", executable ); } "," public void testQuoteWorkingDirectoryAndExecutable() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/local/bin"" ); sh.setExecutable( ""chmod"" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), "" "" ); assertEquals( ""/bin/sh -c cd '/usr/local/bin' && 'chmod'"", executable ); } ",TRUE,BourneShellTest.java " public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/local/'something else'"" ); sh.setExecutable( ""chmod"" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), "" "" ); assertEquals( ""/bin/sh -c cd \""/usr/local/\'something else\'\"" && chmod"", executable ); } "," public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/local/'something else'"" ); sh.setExecutable( ""chmod"" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), "" "" ); assertEquals( ""/bin/sh -c cd '/usr/local/'\""'\""'something else'\""'\""'' && 'chmod'"", executable ); } ",TRUE,BourneShellTest.java " public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() { Shell sh = newShell(); sh.setWorkingDirectory( ""\\usr\\local\\'something else'"" ); sh.setExecutable( ""chmod"" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), "" "" ); assertEquals( ""/bin/sh -c cd \""\\usr\\local\\\'something else\'\"" && chmod"", executable ); } "," public void testQuoteWorkingDirectoryAndExecutable_WDPathWithSingleQuotes_BackslashFileSep() { Shell sh = newShell(); sh.setWorkingDirectory( ""\\usr\\local\\'something else'"" ); sh.setExecutable( ""chmod"" ); String executable = StringUtils.join( sh.getShellCommandLine( new String[]{} ).iterator(), "" "" ); assertEquals( ""/bin/sh -c cd '\\usr\\local\\\'\""'\""'something else'\""'\""'' && 'chmod'"", executable ); } ",TRUE,BourneShellTest.java " public void testPreserveSingleQuotesOnArgument() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { ""\'some arg with spaces\'"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertTrue( cli.endsWith( args[0] ) ); } "," public void testPreserveSingleQuotesOnArgument() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { ""\'some arg with spaces\'"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertTrue( cli.endsWith(""''\""'\""'some arg with spaces'\""'\""''"")); } ",TRUE,BourneShellTest.java " public void testAddSingleQuotesOnArgumentWithSpaces() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { ""some arg with spaces"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertTrue( cli.endsWith( ""\'"" + args[0] + ""\'"" ) ); } "," public void testAddSingleQuotesOnArgumentWithSpaces() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { ""some arg with spaces"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertTrue( cli.endsWith( ""\'"" + args[0] + ""\'"" ) ); } ",FALSE,BourneShellTest.java " public void testEscapeSingleQuotesOnArgument() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { ""arg'withquote"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertEquals(""cd /usr/bin && chmod 'arg'\\''withquote'"", shellCommandLine.get(shellCommandLine.size() - 1)); } "," public void testEscapeSingleQuotesOnArgument() { Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { ""arg'withquote"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertEquals(""cd '/usr/bin' && 'chmod' 'arg'\""'\""'withquote'"", shellCommandLine.get(shellCommandLine.size() - 1)); } ",TRUE,BourneShellTest.java " public void testArgumentsWithsemicolon() { System.out.println( ""---- semi colon tests ----"" ); Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { "";some&argwithunix$chars"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertTrue( cli.endsWith( ""\'"" + args[0] + ""\'"" ) ); Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( ""chmod"" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( ""--password"" ); commandline.createArg().setValue( "";password"" ); String[] lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""/bin/sh"", lines[0] ); assertEquals( ""-c"", lines[1] ); assertEquals( ""chmod --password ';password'"", lines[2] ); commandline = new Commandline( newShell() ); commandline.setExecutable( ""chmod"" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( ""--password"" ); commandline.createArg().setValue( "";password"" ); lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""/bin/sh"", lines[0] ); assertEquals( ""-c"", lines[1] ); assertEquals( ""chmod --password ';password'"", lines[2] ); commandline = new Commandline( new CmdShell() ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( ""--password"" ); commandline.createArg().setValue( "";password"" ); lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""cmd.exe"", lines[0] ); assertEquals( ""/X"", lines[1] ); assertEquals( ""/C"", lines[2] ); assertEquals( ""\""--password ;password\"""", lines[3] ); } "," public void testArgumentsWithsemicolon() { System.out.println( ""---- semi colon tests ----"" ); Shell sh = newShell(); sh.setWorkingDirectory( ""/usr/bin"" ); sh.setExecutable( ""chmod"" ); String[] args = { "";some&argwithunix$chars"" }; List shellCommandLine = sh.getShellCommandLine( args ); String cli = StringUtils.join( shellCommandLine.iterator(), "" "" ); System.out.println( cli ); assertTrue( cli.endsWith( ""\'"" + args[0] + ""\'"" ) ); Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( ""chmod"" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( ""--password"" ); commandline.createArg().setValue( "";password"" ); String[] lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""/bin/sh"", lines[0] ); assertEquals( ""-c"", lines[1] ); assertEquals( ""'chmod' '--password' ';password'"", lines[2] ); commandline = new Commandline( newShell() ); commandline.setExecutable( ""chmod"" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( ""--password"" ); commandline.createArg().setValue( "";password"" ); lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""/bin/sh"", lines[0] ); assertEquals( ""-c"", lines[1] ); assertEquals( ""'chmod' '--password' ';password'"", lines[2] ); commandline = new Commandline( new CmdShell() ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( ""--password"" ); commandline.createArg().setValue( "";password"" ); lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""cmd.exe"", lines[0] ); assertEquals( ""/X"", lines[1] ); assertEquals( ""/C"", lines[2] ); assertEquals( ""\""--password ;password\"""", lines[3] ); } ",TRUE,BourneShellTest.java " public void testBourneShellQuotingCharacters() throws Exception { // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' }; // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( ""chmod"" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( "" "" ); commandline.createArg().setValue( ""|"" ); commandline.createArg().setValue( ""&&"" ); commandline.createArg().setValue( ""||"" ); commandline.createArg().setValue( "";"" ); commandline.createArg().setValue( "";;"" ); commandline.createArg().setValue( ""&"" ); commandline.createArg().setValue( ""()"" ); commandline.createArg().setValue( ""<"" ); commandline.createArg().setValue( ""<<"" ); commandline.createArg().setValue( "">"" ); commandline.createArg().setValue( "">>"" ); commandline.createArg().setValue( ""*"" ); commandline.createArg().setValue( ""?"" ); commandline.createArg().setValue( ""["" ); commandline.createArg().setValue( ""]"" ); commandline.createArg().setValue( ""{"" ); commandline.createArg().setValue( ""}"" ); commandline.createArg().setValue( ""`"" ); String[] lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""/bin/sh"", lines[0] ); assertEquals( ""-c"", lines[1] ); assertEquals( ""chmod ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'"", lines[2] ); } "," public void testBourneShellQuotingCharacters() throws Exception { // { ' ', '$', ';', '&', '|', '<', '>', '*', '?', '(', ')' }; // test with values http://steve-parker.org/sh/bourne.shtml Appendix B - Meta-characters and Reserved Words Commandline commandline = new Commandline( newShell() ); commandline.setExecutable( ""chmod"" ); commandline.getShell().setQuotedArgumentsEnabled( true ); commandline.createArg().setValue( "" "" ); commandline.createArg().setValue( ""|"" ); commandline.createArg().setValue( ""&&"" ); commandline.createArg().setValue( ""||"" ); commandline.createArg().setValue( "";"" ); commandline.createArg().setValue( "";;"" ); commandline.createArg().setValue( ""&"" ); commandline.createArg().setValue( ""()"" ); commandline.createArg().setValue( ""<"" ); commandline.createArg().setValue( ""<<"" ); commandline.createArg().setValue( "">"" ); commandline.createArg().setValue( "">>"" ); commandline.createArg().setValue( ""*"" ); commandline.createArg().setValue( ""?"" ); commandline.createArg().setValue( ""["" ); commandline.createArg().setValue( ""]"" ); commandline.createArg().setValue( ""{"" ); commandline.createArg().setValue( ""}"" ); commandline.createArg().setValue( ""`"" ); String[] lines = commandline.getShellCommandline(); System.out.println( Arrays.asList( lines ) ); assertEquals( ""/bin/sh"", lines[0] ); assertEquals( ""-c"", lines[1] ); assertEquals( ""'chmod' ' ' '|' '&&' '||' ';' ';;' '&' '()' '<' '<<' '>' '>>' '*' '?' '[' ']' '{' '}' '`'"", lines[2] ); } ",TRUE,BourneShellTest.java " protected List extensions = new ArrayList() {{ add(""action""); add(""""); }}; "," protected List extensions = new ArrayList() {{ add(""action""); add(""""); }}; ",FALSE,DefaultActionMapper.java " public DefaultActionMapper() { prefixTrie = new PrefixTrie() { { put(METHOD_PREFIX, new ParameterAction() { public void execute(String key, ActionMapping mapping) { if (allowDynamicMethodCalls) { mapping.setMethod(cleanupActionName(key.substring(METHOD_PREFIX.length()))); } } }); put(ACTION_PREFIX, new ParameterAction() { public void execute(final String key, ActionMapping mapping) { if (allowActionPrefix) { String name = key.substring(ACTION_PREFIX.length()); if (allowDynamicMethodCalls) { int bang = name.indexOf('!'); if (bang != -1) { String method = cleanupActionName(name.substring(bang + 1)); mapping.setMethod(method); name = name.substring(0, bang); } } String actionName = cleanupActionName(name); if (allowSlashesInActionNames && !allowActionCrossNamespaceAccess) { if (actionName.startsWith(""/"")) { actionName = actionName.substring(1); } } if (!allowSlashesInActionNames && !allowActionCrossNamespaceAccess) { if (actionName.lastIndexOf(""/"") != -1) { actionName = actionName.substring(actionName.lastIndexOf(""/"") + 1); } } mapping.setName(actionName); } } }); } }; } "," public DefaultActionMapper() { prefixTrie = new PrefixTrie() { { put(METHOD_PREFIX, new ParameterAction() { public void execute(String key, ActionMapping mapping) { if (allowDynamicMethodCalls) { mapping.setMethod(cleanupActionName(key.substring(METHOD_PREFIX.length()))); } } }); put(ACTION_PREFIX, new ParameterAction() { public void execute(final String key, ActionMapping mapping) { if (allowActionPrefix) { String name = key.substring(ACTION_PREFIX.length()); if (allowDynamicMethodCalls) { int bang = name.indexOf('!'); if (bang != -1) { String method = cleanupActionName(name.substring(bang + 1)); mapping.setMethod(method); name = name.substring(0, bang); } } String actionName = cleanupActionName(name); if (allowSlashesInActionNames && !allowActionCrossNamespaceAccess) { if (actionName.startsWith(""/"")) { actionName = actionName.substring(1); } } if (!allowSlashesInActionNames && !allowActionCrossNamespaceAccess) { if (actionName.lastIndexOf(""/"") != -1) { actionName = actionName.substring(actionName.lastIndexOf(""/"") + 1); } } mapping.setName(actionName); } } }); } }; } ",FALSE,DefaultActionMapper.java " protected void addParameterAction(String prefix, ParameterAction parameterAction) { prefixTrie.put(prefix, parameterAction); } "," protected void addParameterAction(String prefix, ParameterAction parameterAction) { prefixTrie.put(prefix, parameterAction); } ",FALSE,DefaultActionMapper.java " public void setAllowDynamicMethodCalls(String allow) { allowDynamicMethodCalls = ""true"".equalsIgnoreCase(allow); } "," public void setAllowDynamicMethodCalls(String allow) { allowDynamicMethodCalls = ""true"".equalsIgnoreCase(allow); } ",FALSE,DefaultActionMapper.java " public void setSlashesInActionNames(String allow) { allowSlashesInActionNames = ""true"".equals(allow); } "," public void setSlashesInActionNames(String allow) { allowSlashesInActionNames = ""true"".equals(allow); } ",FALSE,DefaultActionMapper.java " public void setAlwaysSelectFullNamespace(String val) { this.alwaysSelectFullNamespace = ""true"".equals(val); } "," public void setAlwaysSelectFullNamespace(String val) { this.alwaysSelectFullNamespace = ""true"".equals(val); } ",FALSE,DefaultActionMapper.java " public void setAllowedActionNames(String allowedActionNames) { this.allowedActionNames = Pattern.compile(allowedActionNames); } "," public void setAllowedActionNames(String allowedActionNames) { this.allowedActionNames = Pattern.compile(allowedActionNames); } ",FALSE,DefaultActionMapper.java " public void setAllowActionPrefix(String allowActionPrefix) { this.allowActionPrefix = ""true"".equalsIgnoreCase(allowActionPrefix); } "," public void setAllowActionPrefix(String allowActionPrefix) { this.allowActionPrefix = ""true"".equalsIgnoreCase(allowActionPrefix); } ",FALSE,DefaultActionMapper.java " public void setAllowActionCrossNamespaceAccess(String allowActionCrossNamespaceAccess) { this.allowActionCrossNamespaceAccess = ""true"".equalsIgnoreCase(allowActionCrossNamespaceAccess); } "," public void setAllowActionCrossNamespaceAccess(String allowActionCrossNamespaceAccess) { this.allowActionCrossNamespaceAccess = ""true"".equalsIgnoreCase(allowActionCrossNamespaceAccess); } ",FALSE,DefaultActionMapper.java " public void setContainer(Container container) { this.container = container; } "," public void setContainer(Container container) { this.container = container; } ",FALSE,DefaultActionMapper.java " public void setExtensions(String extensions) { if (extensions != null && !"""".equals(extensions)) { List list = new ArrayList(); String[] tokens = extensions.split("",""); Collections.addAll(list, tokens); if (extensions.endsWith("","")) { list.add(""""); } this.extensions = Collections.unmodifiableList(list); } else { this.extensions = null; } } "," public void setExtensions(String extensions) { if (extensions != null && !"""".equals(extensions)) { List list = new ArrayList(); String[] tokens = extensions.split("",""); Collections.addAll(list, tokens); if (extensions.endsWith("","")) { list.add(""""); } this.extensions = Collections.unmodifiableList(list); } else { this.extensions = null; } } ",FALSE,DefaultActionMapper.java " public ActionMapping getMappingFromActionName(String actionName) { ActionMapping mapping = new ActionMapping(); mapping.setName(actionName); return parseActionName(mapping); } "," public ActionMapping getMappingFromActionName(String actionName) { ActionMapping mapping = new ActionMapping(); mapping.setName(actionName); return parseActionName(mapping); } ",FALSE,DefaultActionMapper.java " public boolean isSlashesInActionNames() { return allowSlashesInActionNames; } "," public boolean isSlashesInActionNames() { return allowSlashesInActionNames; } ",FALSE,DefaultActionMapper.java " public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager) { ActionMapping mapping = new ActionMapping(); String uri = RequestUtils.getUri(request); int indexOfSemicolon = uri.indexOf("";""); uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri; uri = dropExtension(uri, mapping); if (uri == null) { return null; } parseNameAndNamespace(uri, mapping, configManager); handleSpecialParameters(request, mapping); return parseActionName(mapping); } "," public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager) { ActionMapping mapping = new ActionMapping(); String uri = RequestUtils.getUri(request); int indexOfSemicolon = uri.indexOf("";""); uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri; uri = dropExtension(uri, mapping); if (uri == null) { return null; } parseNameAndNamespace(uri, mapping, configManager); handleSpecialParameters(request, mapping); return parseActionName(mapping); } ",FALSE,DefaultActionMapper.java " protected ActionMapping parseActionName(ActionMapping mapping) { if (mapping.getName() == null) { return null; } if (allowDynamicMethodCalls) { // handle ""name!method"" convention. String name = mapping.getName(); int exclamation = name.lastIndexOf(""!""); if (exclamation != -1) { mapping.setName(name.substring(0, exclamation)); mapping.setMethod(name.substring(exclamation + 1)); } } return mapping; } "," protected ActionMapping parseActionName(ActionMapping mapping) { if (mapping.getName() == null) { return null; } if (allowDynamicMethodCalls) { // handle ""name!method"" convention. String name = mapping.getName(); int exclamation = name.lastIndexOf(""!""); if (exclamation != -1) { mapping.setName(name.substring(0, exclamation)); mapping.setMethod(name.substring(exclamation + 1)); } } return mapping; } ",FALSE,DefaultActionMapper.java " public void handleSpecialParameters(HttpServletRequest request, ActionMapping mapping) { // handle special parameter prefixes. Set uniqueParameters = new HashSet(); Map parameterMap = request.getParameterMap(); for (Object o : parameterMap.keySet()) { String key = (String) o; // Strip off the image button location info, if found if (key.endsWith("".x"") || key.endsWith("".y"")) { key = key.substring(0, key.length() - 2); } // Ensure a parameter doesn't get processed twice if (!uniqueParameters.contains(key)) { ParameterAction parameterAction = (ParameterAction) prefixTrie.get(key); if (parameterAction != null) { parameterAction.execute(key, mapping); uniqueParameters.add(key); break; } } } } "," public void handleSpecialParameters(HttpServletRequest request, ActionMapping mapping) { // handle special parameter prefixes. Set uniqueParameters = new HashSet(); Map parameterMap = request.getParameterMap(); for (Object o : parameterMap.keySet()) { String key = (String) o; // Strip off the image button location info, if found if (key.endsWith("".x"") || key.endsWith("".y"")) { key = key.substring(0, key.length() - 2); } // Ensure a parameter doesn't get processed twice if (!uniqueParameters.contains(key)) { ParameterAction parameterAction = (ParameterAction) prefixTrie.get(key); if (parameterAction != null) { parameterAction.execute(key, mapping); uniqueParameters.add(key); break; } } } } ",FALSE,DefaultActionMapper.java " protected void parseNameAndNamespace(String uri, ActionMapping mapping, ConfigurationManager configManager) { String namespace, name; int lastSlash = uri.lastIndexOf(""/""); if (lastSlash == -1) { namespace = """"; name = uri; } else if (lastSlash == 0) { // ww-1046, assume it is the root namespace, it will fallback to // default // namespace anyway if not found in root namespace. namespace = ""/""; name = uri.substring(lastSlash + 1); } else if (alwaysSelectFullNamespace) { // Simply select the namespace as everything before the last slash namespace = uri.substring(0, lastSlash); name = uri.substring(lastSlash + 1); } else { // Try to find the namespace in those defined, defaulting to """" Configuration config = configManager.getConfiguration(); String prefix = uri.substring(0, lastSlash); namespace = """"; boolean rootAvailable = false; // Find the longest matching namespace, defaulting to the default for (PackageConfig cfg : config.getPackageConfigs().values()) { String ns = cfg.getNamespace(); if (ns != null && prefix.startsWith(ns) && (prefix.length() == ns.length() || prefix.charAt(ns.length()) == '/')) { if (ns.length() > namespace.length()) { namespace = ns; } } if (""/"".equals(ns)) { rootAvailable = true; } } name = uri.substring(namespace.length() + 1); // Still none found, use root namespace if found if (rootAvailable && """".equals(namespace)) { namespace = ""/""; } } if (!allowSlashesInActionNames) { int pos = name.lastIndexOf('/'); if (pos > -1 && pos < name.length() - 1) { name = name.substring(pos + 1); } } mapping.setNamespace(namespace); mapping.setName(cleanupActionName(name)); } "," protected void parseNameAndNamespace(String uri, ActionMapping mapping, ConfigurationManager configManager) { String namespace, name; int lastSlash = uri.lastIndexOf(""/""); if (lastSlash == -1) { namespace = """"; name = uri; } else if (lastSlash == 0) { // ww-1046, assume it is the root namespace, it will fallback to // default // namespace anyway if not found in root namespace. namespace = ""/""; name = uri.substring(lastSlash + 1); } else if (alwaysSelectFullNamespace) { // Simply select the namespace as everything before the last slash namespace = uri.substring(0, lastSlash); name = uri.substring(lastSlash + 1); } else { // Try to find the namespace in those defined, defaulting to """" Configuration config = configManager.getConfiguration(); String prefix = uri.substring(0, lastSlash); namespace = """"; boolean rootAvailable = false; // Find the longest matching namespace, defaulting to the default for (PackageConfig cfg : config.getPackageConfigs().values()) { String ns = cfg.getNamespace(); if (ns != null && prefix.startsWith(ns) && (prefix.length() == ns.length() || prefix.charAt(ns.length()) == '/')) { if (ns.length() > namespace.length()) { namespace = ns; } } if (""/"".equals(ns)) { rootAvailable = true; } } name = uri.substring(namespace.length() + 1); // Still none found, use root namespace if found if (rootAvailable && """".equals(namespace)) { namespace = ""/""; } } if (!allowSlashesInActionNames) { int pos = name.lastIndexOf('/'); if (pos > -1 && pos < name.length() - 1) { name = name.substring(pos + 1); } } mapping.setNamespace(namespace); mapping.setName(cleanupActionName(name)); } ",FALSE,DefaultActionMapper.java " protected String cleanupActionName(final String rawActionName) { if (allowedActionNames.matcher(rawActionName).matches()) { return rawActionName; } else { if (LOG.isWarnEnabled()) { LOG.warn(""Action/method [#0] does not match allowed action names pattern [#1], cleaning it up!"", rawActionName, allowedActionNames); } String cleanActionName = rawActionName; for (String chunk : allowedActionNames.split(rawActionName)) { cleanActionName = cleanActionName.replace(chunk, """"); } if (LOG.isDebugEnabled()) { LOG.debug(""Cleaned action/method name [#0]"", cleanActionName); } return cleanActionName; } } "," protected String cleanupActionName(final String rawActionName) { if (allowedActionNames.matcher(rawActionName).matches()) { return rawActionName; } else { throw new StrutsException(""Action ["" + rawActionName + ""] does not match allowed action names pattern ["" + allowedActionNames + ""]!""); } } ",TRUE,DefaultActionMapper.java " protected String dropExtension(String name) { return dropExtension(name, new ActionMapping()); } "," protected String dropExtension(String name) { return dropExtension(name, new ActionMapping()); } ",FALSE,DefaultActionMapper.java " protected String dropExtension(String name, ActionMapping mapping) { if (extensions == null) { return name; } for (String ext : extensions) { if ("""".equals(ext)) { // This should also handle cases such as /foo/bar-1.0/description. It is tricky to // distinquish /foo/bar-1.0 but perhaps adding a numeric check in the future could // work int index = name.lastIndexOf('.'); if (index == -1 || name.indexOf('/', index) >= 0) { return name; } } else { String extension = ""."" + ext; if (name.endsWith(extension)) { name = name.substring(0, name.length() - extension.length()); mapping.setExtension(ext); return name; } } } return null; } "," protected String dropExtension(String name, ActionMapping mapping) { if (extensions == null) { return name; } for (String ext : extensions) { if ("""".equals(ext)) { // This should also handle cases such as /foo/bar-1.0/description. It is tricky to // distinquish /foo/bar-1.0 but perhaps adding a numeric check in the future could // work int index = name.lastIndexOf('.'); if (index == -1 || name.indexOf('/', index) >= 0) { return name; } } else { String extension = ""."" + ext; if (name.endsWith(extension)) { name = name.substring(0, name.length() - extension.length()); mapping.setExtension(ext); return name; } } } return null; } ",FALSE,DefaultActionMapper.java " protected String getDefaultExtension() { if (extensions == null) { return null; } else { return extensions.get(0); } } "," protected String getDefaultExtension() { if (extensions == null) { return null; } else { return extensions.get(0); } } ",FALSE,DefaultActionMapper.java " public String getUriFromActionMapping(ActionMapping mapping) { StringBuilder uri = new StringBuilder(); handleNamespace(mapping, uri); handleName(mapping, uri); handleDynamicMethod(mapping, uri); handleExtension(mapping, uri); handleParams(mapping, uri); return uri.toString(); } "," public String getUriFromActionMapping(ActionMapping mapping) { StringBuilder uri = new StringBuilder(); handleNamespace(mapping, uri); handleName(mapping, uri); handleDynamicMethod(mapping, uri); handleExtension(mapping, uri); handleParams(mapping, uri); return uri.toString(); } ",FALSE,DefaultActionMapper.java " protected void handleNamespace(ActionMapping mapping, StringBuilder uri) { if (mapping.getNamespace() != null) { uri.append(mapping.getNamespace()); if (!""/"".equals(mapping.getNamespace())) { uri.append(""/""); } } } "," protected void handleNamespace(ActionMapping mapping, StringBuilder uri) { if (mapping.getNamespace() != null) { uri.append(mapping.getNamespace()); if (!""/"".equals(mapping.getNamespace())) { uri.append(""/""); } } } ",FALSE,DefaultActionMapper.java " protected void handleName(ActionMapping mapping, StringBuilder uri) { String name = mapping.getName(); if (name.indexOf('?') != -1) { name = name.substring(0, name.indexOf('?')); } uri.append(name); } "," protected void handleName(ActionMapping mapping, StringBuilder uri) { String name = mapping.getName(); if (name.indexOf('?') != -1) { name = name.substring(0, name.indexOf('?')); } uri.append(name); } ",FALSE,DefaultActionMapper.java " protected void handleDynamicMethod(ActionMapping mapping, StringBuilder uri) { // See WW-3965 if (StringUtils.isNotEmpty(mapping.getMethod())) { if (allowDynamicMethodCalls) { // handle ""name!method"" convention. String name = mapping.getName(); if (!name.contains(""!"")) { // Append the method as no bang found uri.append(""!"").append(mapping.getMethod()); } } else { uri.append(""!"").append(mapping.getMethod()); } } } "," protected void handleDynamicMethod(ActionMapping mapping, StringBuilder uri) { // See WW-3965 if (StringUtils.isNotEmpty(mapping.getMethod())) { if (allowDynamicMethodCalls) { // handle ""name!method"" convention. String name = mapping.getName(); if (!name.contains(""!"")) { // Append the method as no bang found uri.append(""!"").append(mapping.getMethod()); } } else { uri.append(""!"").append(mapping.getMethod()); } } } ",FALSE,DefaultActionMapper.java " protected void handleExtension(ActionMapping mapping, StringBuilder uri) { String extension = lookupExtension(mapping.getExtension()); if (extension != null) { if (extension.length() == 0 || (extension.length() > 0 && uri.indexOf('.' + extension) == -1)) { if (extension.length() > 0) { uri.append(""."").append(extension); } } } } "," protected void handleExtension(ActionMapping mapping, StringBuilder uri) { String extension = lookupExtension(mapping.getExtension()); if (extension != null) { if (extension.length() == 0 || (extension.length() > 0 && uri.indexOf('.' + extension) == -1)) { if (extension.length() > 0) { uri.append(""."").append(extension); } } } } ",FALSE,DefaultActionMapper.java " protected String lookupExtension(String extension) { if (extension == null) { // Look for the current extension, if available ActionContext context = ActionContext.getContext(); if (context != null) { ActionMapping orig = (ActionMapping) context.get(ServletActionContext.ACTION_MAPPING); if (orig != null) { extension = orig.getExtension(); } } if (extension == null) { extension = getDefaultExtension(); } } return extension; } "," protected String lookupExtension(String extension) { if (extension == null) { // Look for the current extension, if available ActionContext context = ActionContext.getContext(); if (context != null) { ActionMapping orig = (ActionMapping) context.get(ServletActionContext.ACTION_MAPPING); if (orig != null) { extension = orig.getExtension(); } } if (extension == null) { extension = getDefaultExtension(); } } return extension; } ",FALSE,DefaultActionMapper.java " protected void handleParams(ActionMapping mapping, StringBuilder uri) { String name = mapping.getName(); String params = """"; if (name.indexOf('?') != -1) { params = name.substring(name.indexOf('?')); } if (params.length() > 0) { uri.append(params); } } "," protected void handleParams(ActionMapping mapping, StringBuilder uri) { String name = mapping.getName(); String params = """"; if (name.indexOf('?') != -1) { params = name.substring(name.indexOf('?')); } if (params.length() > 0) { uri.append(params); } } ",FALSE,DefaultActionMapper.java " protected void setUp() throws Exception { super.setUp(); req = new MockHttpServletRequest(); req.setupGetParameterMap(new HashMap()); req.setupGetContextPath(""/my/namespace""); config = new DefaultConfiguration(); PackageConfig pkg = new PackageConfig.Builder(""myns"") .namespace(""/my/namespace"").build(); PackageConfig pkg2 = new PackageConfig.Builder(""my"").namespace(""/my"").build(); config.addPackageConfig(""mvns"", pkg); config.addPackageConfig(""my"", pkg2); configManager = new ConfigurationManager() { public Configuration getConfiguration() { return config; } }; } "," protected void setUp() throws Exception { super.setUp(); req = new MockHttpServletRequest(); req.setupGetParameterMap(new HashMap()); req.setupGetContextPath(""/my/namespace""); config = new DefaultConfiguration(); PackageConfig pkg = new PackageConfig.Builder(""myns"") .namespace(""/my/namespace"").build(); PackageConfig pkg2 = new PackageConfig.Builder(""my"").namespace(""/my"").build(); config.addPackageConfig(""mvns"", pkg); config.addPackageConfig(""my"", pkg2); configManager = new ConfigurationManager() { public Configuration getConfiguration() { return config; } }; } ",FALSE,DefaultActionMapperTest.java " public void testGetMapping() throws Exception { req.setupGetRequestURI(""/my/namespace/actionName.action""); req.setupGetServletPath(""/my/namespace/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMapping() throws Exception { req.setupGetRequestURI(""/my/namespace/actionName.action""); req.setupGetServletPath(""/my/namespace/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithMethod() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName!add.action""); req.setupGetServletPath(""/my/namespace/actionName!add.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAllowDynamicMethodCalls(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertEquals(""add"", mapping.getMethod()); } "," public void testGetMappingWithMethod() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName!add.action""); req.setupGetServletPath(""/my/namespace/actionName!add.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAllowDynamicMethodCalls(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertEquals(""add"", mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithSlashedName() throws Exception { req.setupGetRequestURI(""/my/foo/actionName.action""); req.setupGetServletPath(""/my/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my"", mapping.getNamespace()); assertEquals(""foo/actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithSlashedName() throws Exception { req.setupGetRequestURI(""/my/foo/actionName.action""); req.setupGetServletPath(""/my/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my"", mapping.getNamespace()); assertEquals(""foo/actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithSlashedNameAtRootButNoSlashPackage() throws Exception { req.setupGetRequestURI(""/foo/actionName.action""); req.setupGetServletPath(""/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""foo/actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithSlashedNameAtRootButNoSlashPackage() throws Exception { req.setupGetRequestURI(""/foo/actionName.action""); req.setupGetServletPath(""/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""foo/actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithSlashedNameAtRoot() throws Exception { config = new DefaultConfiguration(); PackageConfig pkg = new PackageConfig.Builder(""myns"") .namespace(""/my/namespace"").build(); PackageConfig pkg2 = new PackageConfig.Builder(""my"").namespace(""/my"").build(); PackageConfig pkg3 = new PackageConfig.Builder(""root"").namespace(""/"").build(); config.addPackageConfig(""mvns"", pkg); config.addPackageConfig(""my"", pkg2); config.addPackageConfig(""root"", pkg3); configManager = new ConfigurationManager() { public Configuration getConfiguration() { return config; } }; req.setupGetRequestURI(""/foo/actionName.action""); req.setupGetServletPath(""/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/"", mapping.getNamespace()); assertEquals(""foo/actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithSlashedNameAtRoot() throws Exception { config = new DefaultConfiguration(); PackageConfig pkg = new PackageConfig.Builder(""myns"") .namespace(""/my/namespace"").build(); PackageConfig pkg2 = new PackageConfig.Builder(""my"").namespace(""/my"").build(); PackageConfig pkg3 = new PackageConfig.Builder(""root"").namespace(""/"").build(); config.addPackageConfig(""mvns"", pkg); config.addPackageConfig(""my"", pkg2); config.addPackageConfig(""root"", pkg3); configManager = new ConfigurationManager() { public Configuration getConfiguration() { return config; } }; req.setupGetRequestURI(""/foo/actionName.action""); req.setupGetServletPath(""/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/"", mapping.getNamespace()); assertEquals(""foo/actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithNamespaceSlash() throws Exception { req.setupGetRequestURI(""/my.hh/abc.action""); req.setupGetServletPath(""/my.hh/abc.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""abc"", mapping.getName()); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""my.hh/abc"", mapping.getName()); } "," public void testGetMappingWithNamespaceSlash() throws Exception { req.setupGetRequestURI(""/my.hh/abc.action""); req.setupGetServletPath(""/my.hh/abc.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""abc"", mapping.getName()); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); mapper = new DefaultActionMapper(); mapper.setSlashesInActionNames(""true""); mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""my.hh/abc"", mapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithUnknownNamespace() throws Exception { req.setupGetRequestURI(""/bo/foo/actionName.action""); req.setupGetServletPath(""/bo/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithUnknownNamespace() throws Exception { req.setupGetRequestURI(""/bo/foo/actionName.action""); req.setupGetServletPath(""/bo/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals("""", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithUnknownNamespaceButFullNamespaceSelect() throws Exception { req.setupGetRequestURI(""/bo/foo/actionName.action""); req.setupGetServletPath(""/bo/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAlwaysSelectFullNamespace(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/bo/foo"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithUnknownNamespaceButFullNamespaceSelect() throws Exception { req.setupGetRequestURI(""/bo/foo/actionName.action""); req.setupGetServletPath(""/bo/foo/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAlwaysSelectFullNamespace(""true""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/bo/foo"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithActionName_methodAndName() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAllowDynamicMethodCalls(""true""); ActionMapping mapping = mapper.getMappingFromActionName(""actionName!add""); assertEquals(""actionName"", mapping.getName()); assertEquals(""add"", mapping.getMethod()); } "," public void testGetMappingWithActionName_methodAndName() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAllowDynamicMethodCalls(""true""); ActionMapping mapping = mapper.getMappingFromActionName(""actionName!add""); assertEquals(""actionName"", mapping.getName()); assertEquals(""add"", mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithActionName_name() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMappingFromActionName(""actionName""); assertEquals(""actionName"", mapping.getName()); assertEquals(null, mapping.getMethod()); } "," public void testGetMappingWithActionName_name() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMappingFromActionName(""actionName""); assertEquals(""actionName"", mapping.getName()); assertEquals(null, mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithActionName_noDynamicMethod() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAllowDynamicMethodCalls(""false""); ActionMapping mapping = mapper.getMappingFromActionName(""actionName!add""); assertEquals(""actionName!add"", mapping.getName()); assertEquals(null, mapping.getMethod()); } "," public void testGetMappingWithActionName_noDynamicMethod() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setAllowDynamicMethodCalls(""false""); ActionMapping mapping = mapper.getMappingFromActionName(""actionName!add""); assertEquals(""actionName!add"", mapping.getName()); assertEquals(null, mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithActionName_noDynamicMethodColonPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.METHOD_PREFIX + ""someMethod"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowDynamicMethodCalls(""false""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""someServletPath"", actionMapping.getName()); assertEquals(null, actionMapping.getMethod()); } "," public void testGetMappingWithActionName_noDynamicMethodColonPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.METHOD_PREFIX + ""someMethod"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowDynamicMethodCalls(""false""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""someServletPath"", actionMapping.getName()); assertEquals(null, actionMapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithActionName_null() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMappingFromActionName(null); assertNull(mapping); } "," public void testGetMappingWithActionName_null() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMappingFromActionName(null); assertNull(mapping); } ",FALSE,DefaultActionMapperTest.java " public void testGetUri() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName.action""); req.setupGetServletPath(""/my/namespace/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace/actionName.action"", mapper.getUriFromActionMapping(mapping)); } "," public void testGetUri() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName.action""); req.setupGetServletPath(""/my/namespace/actionName.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace/actionName.action"", mapper.getUriFromActionMapping(mapping)); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriWithSemicolonPresent() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName.action;abc=123rty56""); req.setupGetServletPath(""/my/namespace/actionName.action;abc=123rty56""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace/actionName.action"", mapper.getUriFromActionMapping(mapping)); } "," public void testGetUriWithSemicolonPresent() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName.action;abc=123rty56""); req.setupGetServletPath(""/my/namespace/actionName.action;abc=123rty56""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace/actionName.action"", mapper.getUriFromActionMapping(mapping)); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriWithMethod() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName!add.action""); req.setupGetServletPath(""/my/namespace/actionName!add.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace/actionName!add.action"", mapper.getUriFromActionMapping(mapping)); } "," public void testGetUriWithMethod() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName!add.action""); req.setupGetServletPath(""/my/namespace/actionName!add.action""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace/actionName!add.action"", mapper.getUriFromActionMapping(mapping)); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriWithOriginalExtension() throws Exception { ActionMapping mapping = new ActionMapping(""actionName"", ""/ns"", null, new HashMap()); ActionMapping orig = new ActionMapping(); orig.setExtension(""foo""); ActionContext.getContext().put(ServletActionContext.ACTION_MAPPING, orig); DefaultActionMapper mapper = new DefaultActionMapper(); assertEquals(""/ns/actionName.foo"", mapper.getUriFromActionMapping(mapping)); } "," public void testGetUriWithOriginalExtension() throws Exception { ActionMapping mapping = new ActionMapping(""actionName"", ""/ns"", null, new HashMap()); ActionMapping orig = new ActionMapping(); orig.setExtension(""foo""); ActionContext.getContext().put(ServletActionContext.ACTION_MAPPING, orig); DefaultActionMapper mapper = new DefaultActionMapper(); assertEquals(""/ns/actionName.foo"", mapper.getUriFromActionMapping(mapping)); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithNoExtension() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName""); req.setupGetServletPath(""/my/namespace/actionName""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithNoExtension() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName""); req.setupGetServletPath(""/my/namespace/actionName""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testGetMappingWithNoExtensionButUriHasExtension() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName.html""); req.setupGetServletPath(""/my/namespace/actionName.html""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName.html"", mapping.getName()); assertNull(mapping.getMethod()); } "," public void testGetMappingWithNoExtensionButUriHasExtension() throws Exception { req.setupGetParameterMap(new HashMap()); req.setupGetRequestURI(""/my/namespace/actionName.html""); req.setupGetServletPath(""/my/namespace/actionName.html""); req.setupGetAttribute(null); req.addExpectedGetAttributeName(""javax.servlet.include.servlet_path""); DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""""); ActionMapping mapping = mapper.getMapping(req, configManager); assertEquals(""/my/namespace"", mapping.getNamespace()); assertEquals(""actionName.html"", mapping.getName()); assertNull(mapping.getMethod()); } ",FALSE,DefaultActionMapperTest.java " public void testParseNameAndNamespace1() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.parseNameAndNamespace(""someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), """"); } "," public void testParseNameAndNamespace1() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.parseNameAndNamespace(""someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), """"); } ",FALSE,DefaultActionMapperTest.java " public void testParseNameAndNamespace2() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.parseNameAndNamespace(""/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), ""/""); } "," public void testParseNameAndNamespace2() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.parseNameAndNamespace(""/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), ""/""); } ",FALSE,DefaultActionMapperTest.java " public void testParseNameAndNamespace3() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.parseNameAndNamespace(""/my/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), ""/my""); } "," public void testParseNameAndNamespace3() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.parseNameAndNamespace(""/my/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), ""/my""); } ",FALSE,DefaultActionMapperTest.java " public void testParseNameAndNamespace_NoSlashes() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setSlashesInActionNames(""false""); defaultActionMapper.parseNameAndNamespace(""/foo/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), """"); } "," public void testParseNameAndNamespace_NoSlashes() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setSlashesInActionNames(""false""); defaultActionMapper.parseNameAndNamespace(""/foo/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""someAction""); assertEquals(actionMapping.getNamespace(), """"); } ",FALSE,DefaultActionMapperTest.java " public void testParseNameAndNamespace_AllowSlashes() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setSlashesInActionNames(""true""); defaultActionMapper.parseNameAndNamespace(""/foo/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""foo/someAction""); assertEquals(actionMapping.getNamespace(), """"); } "," public void testParseNameAndNamespace_AllowSlashes() throws Exception { ActionMapping actionMapping = new ActionMapping(); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setSlashesInActionNames(""true""); defaultActionMapper.parseNameAndNamespace(""/foo/someAction"", actionMapping, configManager); assertEquals(actionMapping.getName(), ""foo/someAction""); assertEquals(actionMapping.getNamespace(), """"); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefixWhenDisabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""someServletPath"", actionMapping.getName()); } "," public void testActionPrefixWhenDisabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""someServletPath"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefixWhenEnabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""myAction"", actionMapping.getName()); } "," public void testActionPrefixWhenEnabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""myAction"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefixWhenSlashesAndCrossNamespaceDisabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setSlashesInActionNames(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""my/Action"", actionMapping.getName()); } "," public void testActionPrefixWhenSlashesAndCrossNamespaceDisabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setSlashesInActionNames(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""my/Action"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespaceDisabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setSlashesInActionNames(""false""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""Action"", actionMapping.getName()); } "," public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespaceDisabled() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setSlashesInActionNames(""false""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""Action"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespace() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setAllowActionCrossNamespaceAccess(""true""); defaultActionMapper.setSlashesInActionNames(""false""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""my/Action"", actionMapping.getName()); } "," public void testActionPrefixWhenSlashesButSlashesDisabledAndCrossNamespace() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setAllowActionCrossNamespaceAccess(""true""); defaultActionMapper.setSlashesInActionNames(""false""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""my/Action"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefixWhenCrossNamespace() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""/my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setAllowActionCrossNamespaceAccess(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""/my/Action"", actionMapping.getName()); } "," public void testActionPrefixWhenCrossNamespace() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""/my/Action"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); defaultActionMapper.setAllowActionCrossNamespaceAccess(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""/my/Action"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefix_fromImageButton() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction"", """"); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.x"", """"); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.y"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""myAction"", actionMapping.getName()); } "," public void testActionPrefix_fromImageButton() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction"", """"); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.x"", """"); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.y"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""myAction"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testActionPrefix_fromIEImageButton() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.x"", """"); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.y"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""myAction"", actionMapping.getName()); } "," public void testActionPrefix_fromIEImageButton() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.x"", """"); parameterMap.put(DefaultActionMapper.ACTION_PREFIX + ""myAction.y"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setAllowActionPrefix(""true""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(""myAction"", actionMapping.getName()); } ",FALSE,DefaultActionMapperTest.java " public void testRedirectPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirect:"" + ""http://www.google.com"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); Result result = actionMapping.getResult(); assertNull(result); } "," public void testRedirectPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirect:"" + ""http://www.google.com"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); Result result = actionMapping.getResult(); assertNull(result); } ",FALSE,DefaultActionMapperTest.java " public void testUnsafeRedirectPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirect:"" + ""http://%{3*4}"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); Result result = actionMapping.getResult(); assertNull(result); } "," public void testUnsafeRedirectPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirect:"" + ""http://%{3*4}"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); Result result = actionMapping.getResult(); assertNull(result); } ",FALSE,DefaultActionMapperTest.java " public void testRedirectActionPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirectAction:"" + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNull(result); } "," public void testRedirectActionPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirectAction:"" + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNull(result); } ",FALSE,DefaultActionMapperTest.java " public void testUnsafeRedirectActionPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirectAction:"" + ""%{3*4}"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNull(result); } "," public void testUnsafeRedirectActionPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirectAction:"" + ""%{3*4}"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath.action""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNull(result); } ",FALSE,DefaultActionMapperTest.java " public void testRedirectActionPrefixWithEmptyExtension() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirectAction:"" + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); defaultActionMapper.setExtensions("",,""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNull(result); } "," public void testRedirectActionPrefixWithEmptyExtension() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""redirectAction:"" + ""myAction"", """"); StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setupGetServletPath(""/someServletPath""); request.setParameterMap(parameterMap); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.setContainer(container); defaultActionMapper.setExtensions("",,""); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); StrutsResultSupport result = (StrutsResultSupport) actionMapping.getResult(); assertNull(result); } ",FALSE,DefaultActionMapperTest.java " public void testCustomActionPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""foo:myAction"", """"); final StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.addParameterAction(""foo"", new ParameterAction() { public void execute(String key, ActionMapping mapping) { mapping.setName(""myAction""); } }); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(actionMapping.getName(), ""myAction""); } "," public void testCustomActionPrefix() throws Exception { Map parameterMap = new HashMap(); parameterMap.put(""foo:myAction"", """"); final StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest(); request.setParameterMap(parameterMap); request.setupGetServletPath(""/someServletPath.action""); DefaultActionMapper defaultActionMapper = new DefaultActionMapper(); defaultActionMapper.addParameterAction(""foo"", new ParameterAction() { public void execute(String key, ActionMapping mapping) { mapping.setName(""myAction""); } }); ActionMapping actionMapping = defaultActionMapper.getMapping(request, configManager); assertEquals(actionMapping.getName(), ""myAction""); } ",FALSE,DefaultActionMapperTest.java " public void testDropExtension() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); String name = mapper.dropExtension(""foo.action""); assertTrue(""Name not right: ""+name, ""foo"".equals(name)); name = mapper.dropExtension(""foo.action.action""); assertTrue(""Name not right: ""+name, ""foo.action"".equals(name)); } "," public void testDropExtension() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); String name = mapper.dropExtension(""foo.action""); assertTrue(""Name not right: ""+name, ""foo"".equals(name)); name = mapper.dropExtension(""foo.action.action""); assertTrue(""Name not right: ""+name, ""foo.action"".equals(name)); } ",FALSE,DefaultActionMapperTest.java " public void testDropExtensionWhenBlank() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""action,,""); String name = mapper.dropExtension(""foo.action""); assertTrue(""Name not right: ""+name, ""foo"".equals(name)); name = mapper.dropExtension(""foo""); assertTrue(""Name not right: ""+name, ""foo"".equals(name)); assertNull(mapper.dropExtension(""foo.bar"")); assertNull(mapper.dropExtension(""foo."")); } "," public void testDropExtensionWhenBlank() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""action,,""); String name = mapper.dropExtension(""foo.action""); assertTrue(""Name not right: ""+name, ""foo"".equals(name)); name = mapper.dropExtension(""foo""); assertTrue(""Name not right: ""+name, ""foo"".equals(name)); assertNull(mapper.dropExtension(""foo.bar"")); assertNull(mapper.dropExtension(""foo."")); } ",FALSE,DefaultActionMapperTest.java " public void testDropExtensionEmbeddedDot() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""action,,""); String name = mapper.dropExtension(""/foo/bar-1.0/baz.action""); assertTrue(""Name not right: ""+name, ""/foo/bar-1.0/baz"".equals(name)); name = mapper.dropExtension(""/foo/bar-1.0/baz""); assertTrue(""Name not right: ""+name, ""/foo/bar-1.0/baz"".equals(name)); } "," public void testDropExtensionEmbeddedDot() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""action,,""); String name = mapper.dropExtension(""/foo/bar-1.0/baz.action""); assertTrue(""Name not right: ""+name, ""/foo/bar-1.0/baz"".equals(name)); name = mapper.dropExtension(""/foo/bar-1.0/baz""); assertTrue(""Name not right: ""+name, ""/foo/bar-1.0/baz"".equals(name)); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper1() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/myNamespace""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myNamespace/myActionName!myMethod.action"", uri); } "," public void testGetUriFromActionMapper1() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/myNamespace""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myNamespace/myActionName!myMethod.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper2() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action"", uri); } "," public void testGetUriFromActionMapper2() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper3() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action"", uri); } "," public void testGetUriFromActionMapper3() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper4() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } "," public void testGetUriFromActionMapper4() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper5() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } "," public void testGetUriFromActionMapper5() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper6() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""/myNamespace""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myNamespace/myActionName!myMethod.action?test=bla"", uri); } "," public void testGetUriFromActionMapper6() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""/myNamespace""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myNamespace/myActionName!myMethod.action?test=bla"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper7() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action?test=bla"", uri); } "," public void testGetUriFromActionMapper7() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action?test=bla"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper8() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action?test=bla"", uri); } "," public void testGetUriFromActionMapper8() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName!myMethod.action?test=bla"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper9() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action?test=bla"", uri); } "," public void testGetUriFromActionMapper9() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action?test=bla"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper10() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action?test=bla"", uri); } "," public void testGetUriFromActionMapper10() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName?test=bla""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action?test=bla"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper11() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName.action""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } "," public void testGetUriFromActionMapper11() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName.action""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper12() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName.action""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } "," public void testGetUriFromActionMapper12() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setName(""myActionName.action""); actionMapping.setNamespace(""/""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myActionName.action"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapper_justActionAndMethod() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setExtension(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""myActionName!myMethod"", uri); } "," public void testGetUriFromActionMapper_justActionAndMethod() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setExtension(""""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""myActionName!myMethod"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testGetUriFromActionMapperWhenBlankExtension() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions("",,""); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/myNamespace""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myNamespace/myActionName!myMethod"", uri); } "," public void testGetUriFromActionMapperWhenBlankExtension() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions("",,""); ActionMapping actionMapping = new ActionMapping(); actionMapping.setMethod(""myMethod""); actionMapping.setName(""myActionName""); actionMapping.setNamespace(""/myNamespace""); String uri = mapper.getUriFromActionMapping(actionMapping); assertEquals(""/myNamespace/myActionName!myMethod"", uri); } ",FALSE,DefaultActionMapperTest.java " public void testSetExtension() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""""); assertNull(mapper.extensions); mapper.setExtensions(null); assertNull(mapper.extensions); mapper.setExtensions("",xml""); assertEquals(Arrays.asList("""", ""xml""), mapper.extensions); mapper.setExtensions(""html,xml,""); assertEquals(Arrays.asList(""html"", ""xml"", """"), mapper.extensions); mapper.setExtensions(""html,,xml""); assertEquals(Arrays.asList(""html"", """", ""xml""), mapper.extensions); mapper.setExtensions(""xml""); assertEquals(Arrays.asList(""xml""), mapper.extensions); mapper.setExtensions("",""); assertEquals(Arrays.asList(""""), mapper.extensions); } "," public void testSetExtension() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); mapper.setExtensions(""""); assertNull(mapper.extensions); mapper.setExtensions(null); assertNull(mapper.extensions); mapper.setExtensions("",xml""); assertEquals(Arrays.asList("""", ""xml""), mapper.extensions); mapper.setExtensions(""html,xml,""); assertEquals(Arrays.asList(""html"", ""xml"", """"), mapper.extensions); mapper.setExtensions(""html,,xml""); assertEquals(Arrays.asList(""html"", """", ""xml""), mapper.extensions); mapper.setExtensions(""xml""); assertEquals(Arrays.asList(""xml""), mapper.extensions); mapper.setExtensions("",""); assertEquals(Arrays.asList(""""), mapper.extensions); } ",FALSE,DefaultActionMapperTest.java " public void testAllowedActionNames() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); String actionName = ""action""; assertEquals(actionName, mapper.cleanupActionName(actionName)); actionName = ""${action}""; assertEquals(""action"", mapper.cleanupActionName(actionName)); actionName = ""${${%{action}}}""; assertEquals(""action"", mapper.cleanupActionName(actionName)); actionName = ""${#foo='action',#foo}""; assertEquals(""fooactionfoo"", mapper.cleanupActionName(actionName)); actionName = ""test-action""; assertEquals(""test-action"", mapper.cleanupActionName(actionName)); actionName = ""test_action""; assertEquals(""test_action"", mapper.cleanupActionName(actionName)); actionName = ""test!bar.action""; assertEquals(""test!bar.action"", mapper.cleanupActionName(actionName)); } "," public void testAllowedActionNames() throws Exception { DefaultActionMapper mapper = new DefaultActionMapper(); String actionName = ""action""; assertEquals(actionName, mapper.cleanupActionName(actionName)); Throwable expected = null; actionName = ""${action}""; try { mapper.cleanupActionName(actionName); fail(); } catch (Throwable t) { expected = t; } assertTrue(expected instanceof StrutsException); assertEquals(""Action [${action}] does not match allowed action names pattern [[a-zA-Z0-9._!/\\-]*]!"", expected.getMessage()); actionName = ""${${%{action}}}""; try { mapper.cleanupActionName(actionName); fail(); } catch (Throwable t) { expected = t; } assertTrue(expected instanceof StrutsException); assertEquals(""Action [${${%{action}}}] does not match allowed action names pattern [[a-zA-Z0-9._!/\\-]*]!"", expected.getMessage()); actionName = ""${#foo='action',#foo}""; try { mapper.cleanupActionName(actionName); fail(); } catch (Throwable t) { expected = t; } assertTrue(expected instanceof StrutsException); assertEquals(""Action [${#foo='action',#foo}] does not match allowed action names pattern [[a-zA-Z0-9._!/\\-]*]!"", expected.getMessage()); actionName = ""test-action""; assertEquals(""test-action"", mapper.cleanupActionName(actionName)); actionName = ""test_action""; assertEquals(""test_action"", mapper.cleanupActionName(actionName)); actionName = ""test!bar.action""; assertEquals(""test!bar.action"", mapper.cleanupActionName(actionName)); } ",TRUE,DefaultActionMapperTest.java " } "," public CookieInterceptor() { for (String pattern : ExcludedPatterns.EXCLUDED_PATTERNS) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } ",TRUE,CookieInterceptor.java " public void setCookiesName(String cookiesName) { if (cookiesName != null) this.cookiesNameSet = TextParseUtil.commaDelimitedStringToSet(cookiesName); } "," public void setCookiesName(String cookiesName) { if (cookiesName != null) this.cookiesNameSet = TextParseUtil.commaDelimitedStringToSet(cookiesName); } ",FALSE,CookieInterceptor.java " public void setCookiesValue(String cookiesValue) { if (cookiesValue != null) this.cookiesValueSet = TextParseUtil.commaDelimitedStringToSet(cookiesValue); } "," public void setCookiesValue(String cookiesValue) { if (cookiesValue != null) this.cookiesValueSet = TextParseUtil.commaDelimitedStringToSet(cookiesValue); } ",FALSE,CookieInterceptor.java " public void setAcceptCookieNames(String pattern) { acceptedPattern = Pattern.compile(pattern); } "," public void setAcceptCookieNames(String pattern) { acceptedPattern = Pattern.compile(pattern); } ",FALSE,CookieInterceptor.java " public String intercept(ActionInvocation invocation) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(""start interception""); } // contains selected cookies final Map cookiesMap = new LinkedHashMap(); Cookie[] cookies = ServletActionContext.getRequest().getCookies(); if (cookies != null) { final ValueStack stack = ActionContext.getContext().getValueStack(); for (Cookie cookie : cookies) { String name = cookie.getName(); String value = cookie.getValue(); if (isAcceptableName(name) && isAcceptableValue(value)) { if (cookiesNameSet.contains(""*"")) { if (LOG.isDebugEnabled()) { LOG.debug(""contains cookie name [*] in configured cookies name set, cookie with name ["" + name + ""] with value ["" + value + ""] will be injected""); } populateCookieValueIntoStack(name, value, cookiesMap, stack); } else if (cookiesNameSet.contains(cookie.getName())) { populateCookieValueIntoStack(name, value, cookiesMap, stack); } } else { LOG.warn(""Cookie name [#0] with value [#1] was rejected!"", name, value); } } } // inject the cookiesMap, even if we don't have any cookies injectIntoCookiesAwareAction(invocation.getAction(), cookiesMap); return invocation.invoke(); } "," public String intercept(ActionInvocation invocation) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug(""start interception""); } // contains selected cookies final Map cookiesMap = new LinkedHashMap(); Cookie[] cookies = ServletActionContext.getRequest().getCookies(); if (cookies != null) { final ValueStack stack = ActionContext.getContext().getValueStack(); for (Cookie cookie : cookies) { String name = cookie.getName(); String value = cookie.getValue(); if (isAcceptableName(name) && isAcceptableValue(value)) { if (cookiesNameSet.contains(""*"")) { if (LOG.isDebugEnabled()) { LOG.debug(""contains cookie name [*] in configured cookies name set, cookie with name ["" + name + ""] with value ["" + value + ""] will be injected""); } populateCookieValueIntoStack(name, value, cookiesMap, stack); } else if (cookiesNameSet.contains(cookie.getName())) { populateCookieValueIntoStack(name, value, cookiesMap, stack); } } else { LOG.warn(""Cookie name [#0] with value [#1] was rejected!"", name, value); } } } // inject the cookiesMap, even if we don't have any cookies injectIntoCookiesAwareAction(invocation.getAction(), cookiesMap); return invocation.invoke(); } ",FALSE,CookieInterceptor.java " protected boolean isAcceptableValue(String value) { boolean matches = !excludedPattern.matcher(value).matches(); if (!matches) { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie value [#0] matches excludedPattern [#1]"", value, ExcludedPatterns.CLASS_ACCESS_PATTERN); } } return matches; } "," protected boolean isAcceptableValue(String value) { for (Pattern excludedPattern : excludedPatterns) { boolean matches = !excludedPattern.matcher(value).matches(); if (!matches) { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie value [#0] matches excludedPattern [#1]"", value, excludedPattern.toString()); } return false; } } return true; } ",TRUE,CookieInterceptor.java " protected boolean isAcceptableName(String name) { return !isExcluded(name) && isAccepted(name); } "," protected boolean isAcceptableName(String name) { return !isExcluded(name) && isAccepted(name); } ",FALSE,CookieInterceptor.java " protected boolean isAccepted(String name) { boolean matches = acceptedPattern.matcher(name).matches(); if (matches) { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] matches acceptedPattern [#1]"", name, ACCEPTED_PATTERN); } } else { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] doesn't match acceptedPattern [#1]"", name, ACCEPTED_PATTERN); } } return matches; } "," protected boolean isAccepted(String name) { boolean matches = acceptedPattern.matcher(name).matches(); if (matches) { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] matches acceptedPattern [#1]"", name, ACCEPTED_PATTERN); } } else { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] doesn't match acceptedPattern [#1]"", name, ACCEPTED_PATTERN); } } return matches; } ",FALSE,CookieInterceptor.java " protected boolean isExcluded(String name) { boolean matches = excludedPattern.matcher(name).matches(); if (matches) { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] matches excludedPattern [#1]"", name, ExcludedPatterns.CLASS_ACCESS_PATTERN); } } else { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] doesn't match excludedPattern [#1]"", name, ExcludedPatterns.CLASS_ACCESS_PATTERN); } } return matches; } "," protected boolean isExcluded(String name) { for (Pattern excludedPattern : excludedPatterns) { boolean matches = excludedPattern.matcher(name).matches(); if (matches) { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] matches excludedPattern [#1]"", name, excludedPattern.toString()); } return true; } else { if (LOG.isTraceEnabled()) { LOG.trace(""Cookie [#0] doesn't match excludedPattern [#1]"", name, excludedPattern.toString()); } } } return false; } ",TRUE,CookieInterceptor.java " protected void populateCookieValueIntoStack(String cookieName, String cookieValue, Map cookiesMap, ValueStack stack) { if (cookiesValueSet.isEmpty() || cookiesValueSet.contains(""*"")) { // If the interceptor is configured to accept any cookie value // OR // no cookiesValue is defined, so as long as the cookie name match // we'll inject it into Struts' action if (LOG.isDebugEnabled()) { if (cookiesValueSet.isEmpty()) LOG.debug(""no cookie value is configured, cookie with name [""+cookieName+""] with value [""+cookieValue+""] will be injected""); else if (cookiesValueSet.contains(""*"")) LOG.debug(""interceptor is configured to accept any value, cookie with name [""+cookieName+""] with value [""+cookieValue+""] will be injected""); } cookiesMap.put(cookieName, cookieValue); stack.setValue(cookieName, cookieValue); } else { // if cookiesValues is specified, the cookie's value must match before we // inject them into Struts' action if (cookiesValueSet.contains(cookieValue)) { if (LOG.isDebugEnabled()) { LOG.debug(""both configured cookie name and value matched, cookie [""+cookieName+""] with value [""+cookieValue+""] will be injected""); } cookiesMap.put(cookieName, cookieValue); stack.setValue(cookieName, cookieValue); } } } "," protected void populateCookieValueIntoStack(String cookieName, String cookieValue, Map cookiesMap, ValueStack stack) { if (cookiesValueSet.isEmpty() || cookiesValueSet.contains(""*"")) { // If the interceptor is configured to accept any cookie value // OR // no cookiesValue is defined, so as long as the cookie name match // we'll inject it into Struts' action if (LOG.isDebugEnabled()) { if (cookiesValueSet.isEmpty()) LOG.debug(""no cookie value is configured, cookie with name [""+cookieName+""] with value [""+cookieValue+""] will be injected""); else if (cookiesValueSet.contains(""*"")) LOG.debug(""interceptor is configured to accept any value, cookie with name [""+cookieName+""] with value [""+cookieValue+""] will be injected""); } cookiesMap.put(cookieName, cookieValue); stack.setValue(cookieName, cookieValue); } else { // if cookiesValues is specified, the cookie's value must match before we // inject them into Struts' action if (cookiesValueSet.contains(cookieValue)) { if (LOG.isDebugEnabled()) { LOG.debug(""both configured cookie name and value matched, cookie [""+cookieName+""] with value [""+cookieValue+""] will be injected""); } cookiesMap.put(cookieName, cookieValue); stack.setValue(cookieName, cookieValue); } } } ",FALSE,CookieInterceptor.java " protected void injectIntoCookiesAwareAction(Object action, Map cookiesMap) { if (action instanceof CookiesAware) { if (LOG.isDebugEnabled()) { LOG.debug(""action [""+action+""] implements CookiesAware, injecting cookies map [""+cookiesMap+""]""); } ((CookiesAware)action).setCookiesMap(cookiesMap); } } "," protected void injectIntoCookiesAwareAction(Object action, Map cookiesMap) { if (action instanceof CookiesAware) { if (LOG.isDebugEnabled()) { LOG.debug(""action [""+action+""] implements CookiesAware, injecting cookies map [""+cookiesMap+""]""); } ((CookiesAware)action).setCookiesMap(cookiesMap); } } ",FALSE,CookieInterceptor.java " public void testIntercepDefault() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); // by default the interceptor doesn't accept any cookies CookieInterceptor interceptor = new CookieInterceptor(); interceptor.intercept(invocation); assertTrue(action.getCookiesMap().isEmpty()); assertNull(action.getCookie1(), null); assertNull(action.getCookie2(), null); assertNull(action.getCookie3(), null); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie1"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie2"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie3"")); } "," public void testIntercepDefault() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); // by default the interceptor doesn't accept any cookies CookieInterceptor interceptor = new CookieInterceptor(); interceptor.intercept(invocation); assertTrue(action.getCookiesMap().isEmpty()); assertNull(action.getCookie1(), null); assertNull(action.getCookie2(), null); assertNull(action.getCookie3(), null); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie1"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie2"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie3"")); } ",FALSE,CookieInterceptorTest.java " public void testInterceptAll1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""*""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptAll1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""*""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptAll2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie2, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptAll2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie2, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameOnly1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptSelectedCookiesNameOnly1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameOnly2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptSelectedCookiesNameOnly2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameOnly3() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptSelectedCookiesNameOnly3() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameAndValue() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 1); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), null); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), null); } "," public void testInterceptSelectedCookiesNameAndValue() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 1); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), null); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), null); } ",FALSE,CookieInterceptorTest.java " public void testCookiesWithClassPollution() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String pollution1 = ""model['class']['classLoader']['jarPath']""; String pollution2 = ""model.class.classLoader.jarPath""; String pollution3 = ""class.classLoader.jarPath""; String pollution4 = ""class['classLoader']['jarPath']""; String pollution5 = ""model[\""class\""]['classLoader']['jarPath']""; String pollution6 = ""class[\""classLoader\""]['jarPath']""; request.setCookies( new Cookie(pollution1, ""pollution1""), new Cookie(""pollution1"", pollution1), new Cookie(pollution2, ""pollution2""), new Cookie(""pollution2"", pollution2), new Cookie(pollution3, ""pollution3""), new Cookie(""pollution3"", pollution3), new Cookie(pollution4, ""pollution4""), new Cookie(""pollution4"", pollution4), new Cookie(pollution5, ""pollution5""), new Cookie(""pollution5"", pollution5), new Cookie(pollution6, ""pollution6""), new Cookie(""pollution6"", pollution6) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(pollution1)); assertFalse(excludedName.get(pollution2)); assertFalse(excludedName.get(pollution3)); assertFalse(excludedName.get(pollution4)); assertFalse(excludedName.get(pollution5)); assertFalse(excludedName.get(pollution6)); assertFalse(excludedValue.get(pollution1)); assertFalse(excludedValue.get(pollution2)); assertFalse(excludedValue.get(pollution3)); assertFalse(excludedValue.get(pollution4)); assertFalse(excludedValue.get(pollution5)); assertFalse(excludedValue.get(pollution6)); } "," public void testCookiesWithClassPollution() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String pollution1 = ""model['class']['classLoader']['jarPath']""; String pollution2 = ""model.class.classLoader.jarPath""; String pollution3 = ""class.classLoader.jarPath""; String pollution4 = ""class['classLoader']['jarPath']""; String pollution5 = ""model[\""class\""]['classLoader']['jarPath']""; String pollution6 = ""class[\""classLoader\""]['jarPath']""; request.setCookies( new Cookie(pollution1, ""pollution1""), new Cookie(""pollution1"", pollution1), new Cookie(pollution2, ""pollution2""), new Cookie(""pollution2"", pollution2), new Cookie(pollution3, ""pollution3""), new Cookie(""pollution3"", pollution3), new Cookie(pollution4, ""pollution4""), new Cookie(""pollution4"", pollution4), new Cookie(pollution5, ""pollution5""), new Cookie(""pollution5"", pollution5), new Cookie(pollution6, ""pollution6""), new Cookie(""pollution6"", pollution6) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(pollution1)); assertFalse(excludedName.get(pollution2)); assertFalse(excludedName.get(pollution3)); assertFalse(excludedName.get(pollution4)); assertFalse(excludedName.get(pollution5)); assertFalse(excludedName.get(pollution6)); assertFalse(excludedValue.get(pollution1)); assertFalse(excludedValue.get(pollution2)); assertFalse(excludedValue.get(pollution3)); assertFalse(excludedValue.get(pollution4)); assertFalse(excludedValue.get(pollution5)); assertFalse(excludedValue.get(pollution6)); } ",FALSE,CookieInterceptorTest.java " "," public void testCookiesWithStrutsInternalsAccess() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String sessionCookieName = ""session.userId""; String sessionCookieValue = ""session.userId=1""; String appCookieName = ""application.userId""; String appCookieValue = ""application.userId=1""; String reqCookieName = ""request.userId""; String reqCookieValue = ""request.userId=1""; request.setCookies( new Cookie(sessionCookieName, ""1""), new Cookie(""1"", sessionCookieValue), new Cookie(appCookieName, ""1""), new Cookie(""1"", appCookieValue), new Cookie(reqCookieName, ""1""), new Cookie(""1"", reqCookieValue) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(sessionCookieName)); assertFalse(excludedName.get(appCookieName)); assertFalse(excludedName.get(reqCookieName)); assertFalse(excludedValue.get(sessionCookieValue)); assertFalse(excludedValue.get(appCookieValue)); assertFalse(excludedValue.get(reqCookieValue)); } ",TRUE,CookieInterceptorTest.java " public void setCookiesMap(Map cookies) { this.cookies = cookies; } "," public void setCookiesMap(Map cookies) { this.cookies = cookies; } ",FALSE,CookieInterceptorTest.java " public Map getCookiesMap() { return this.cookies; } "," public Map getCookiesMap() { return this.cookies; } ",FALSE,CookieInterceptorTest.java " public String getCookie1() { return cookie1; } "," public String getCookie1() { return cookie1; } ",FALSE,CookieInterceptorTest.java " public void setCookie1(String cookie1) { this.cookie1 = cookie1; } "," public void setCookie1(String cookie1) { this.cookie1 = cookie1; } ",FALSE,CookieInterceptorTest.java " public String getCookie2() { return cookie2; } "," public String getCookie2() { return cookie2; } ",FALSE,CookieInterceptorTest.java " public void setCookie2(String cookie2) { this.cookie2 = cookie2; } "," public void setCookie2(String cookie2) { this.cookie2 = cookie2; } ",FALSE,CookieInterceptorTest.java " public String getCookie3() { return cookie3; } "," public String getCookie3() { return cookie3; } ",FALSE,CookieInterceptorTest.java " public void setCookie3(String cookie3) { this.cookie3 = cookie3; } "," public void setCookie3(String cookie3) { this.cookie3 = cookie3; } ",FALSE,CookieInterceptorTest.java " RgbeInfo(final ByteSource byteSource) throws IOException { this.in = byteSource.getInputStream(); } "," RgbeInfo(final ByteSource byteSource) throws IOException { this.in = byteSource.getInputStream(); } ",FALSE,RgbeInfo.java " ImageMetadata getMetadata() throws IOException, ImageReadException { if (null == metadata) { readMetadata(); } return metadata; } "," ImageMetadata getMetadata() throws IOException, ImageReadException { if (null == metadata) { readMetadata(); } return metadata; } ",FALSE,RgbeInfo.java " int getWidth() throws IOException, ImageReadException { if (-1 == width) { readDimensions(); } return width; } "," int getWidth() throws IOException, ImageReadException { if (-1 == width) { readDimensions(); } return width; } ",FALSE,RgbeInfo.java " int getHeight() throws IOException, ImageReadException { if (-1 == height) { readDimensions(); } return height; } "," int getHeight() throws IOException, ImageReadException { if (-1 == height) { readDimensions(); } return height; } ",FALSE,RgbeInfo.java " public void close() throws IOException { in.close(); } "," public void close() throws IOException { in.close(); } ",FALSE,RgbeInfo.java " private void readDimensions() throws IOException, ImageReadException { getMetadata(); // Ensure we've read past this final InfoHeaderReader reader = new InfoHeaderReader(in); final String resolution = reader.readNextLine(); final Matcher matcher = RESOLUTION_STRING.matcher(resolution); if (!matcher.matches()) { throw new ImageReadException( ""Invalid HDR resolution string. Only \""-Y N +X M\"" is supported. Found \"""" + resolution + ""\""""); } height = Integer.parseInt(matcher.group(1)); width = Integer.parseInt(matcher.group(2)); } "," private void readDimensions() throws IOException, ImageReadException { getMetadata(); // Ensure we've read past this final InfoHeaderReader reader = new InfoHeaderReader(in); final String resolution = reader.readNextLine(); final Matcher matcher = RESOLUTION_STRING.matcher(resolution); if (!matcher.matches()) { throw new ImageReadException( ""Invalid HDR resolution string. Only \""-Y N +X M\"" is supported. Found \"""" + resolution + ""\""""); } height = Integer.parseInt(matcher.group(1)); width = Integer.parseInt(matcher.group(2)); } ",FALSE,RgbeInfo.java " private void readMetadata() throws IOException, ImageReadException { BinaryFunctions.readAndVerifyBytes(in, HEADER, ""Not a valid HDR: Incorrect Header""); final InfoHeaderReader reader = new InfoHeaderReader(in); if (reader.readNextLine().length() != 0) { throw new ImageReadException(""Not a valid HDR: Incorrect Header""); } metadata = new GenericImageMetadata(); String info = reader.readNextLine(); while (info.length() != 0) { final int equals = info.indexOf('='); if (equals > 0) { final String variable = info.substring(0, equals); final String value = info.substring(equals + 1); if (""FORMAT"".equals(value) && !""32-bit_rle_rgbe"".equals(value)) { throw new ImageReadException(""Only 32-bit_rle_rgbe images are supported, trying to read "" + value); } metadata.add(variable, value); } else { metadata.add("""", info); } info = reader.readNextLine(); } } "," private void readMetadata() throws IOException, ImageReadException { BinaryFunctions.readAndVerifyBytes(in, HEADER, ""Not a valid HDR: Incorrect Header""); final InfoHeaderReader reader = new InfoHeaderReader(in); if (reader.readNextLine().length() != 0) { throw new ImageReadException(""Not a valid HDR: Incorrect Header""); } metadata = new GenericImageMetadata(); String info = reader.readNextLine(); while (info.length() != 0) { final int equals = info.indexOf('='); if (equals > 0) { final String variable = info.substring(0, equals); final String value = info.substring(equals + 1); if (""FORMAT"".equals(value) && !""32-bit_rle_rgbe"".equals(value)) { throw new ImageReadException(""Only 32-bit_rle_rgbe images are supported, trying to read "" + value); } metadata.add(variable, value); } else { metadata.add("""", info); } info = reader.readNextLine(); } } ",FALSE,RgbeInfo.java " public float[][] getPixelData() throws IOException, ImageReadException { // Read into local variables to ensure that we have seeked into the file // far enough final int ht = getHeight(); final int wd = getWidth(); if (wd >= 32768) { throw new ImageReadException(""Scan lines must be less than 32768 bytes long""); } final byte[] scanLineBytes = ByteConversions.toBytes((short) wd, ByteOrder.BIG_ENDIAN); final byte[] rgbe = new byte[wd * 4]; final float[][] out = new float[3][wd * ht]; for (int i = 0; i < ht; i++) { BinaryFunctions.readAndVerifyBytes(in, TWO_TWO, ""Scan line "" + i + "" expected to start with 0x2 0x2""); BinaryFunctions.readAndVerifyBytes(in, scanLineBytes, ""Scan line "" + i + "" length expected""); decompress(in, rgbe); for (int channel = 0; channel < 3; channel++) { final int channelOffset = channel * wd; final int eOffset = 3 * wd; for (int p = 0; p < wd; p++) { final int mantissa = rgbe[p + eOffset] & 0xff; final int pos = p + i * wd; if (0 == mantissa) { out[channel][pos] = 0; } else { final float mult = (float) Math.pow(2, mantissa - (128 + 8)); out[channel][pos] = ((rgbe[p + channelOffset] & 0xff) + 0.5f) * mult; } } } } return out; } "," public float[][] getPixelData() throws IOException, ImageReadException { // Read into local variables to ensure that we have seeked into the file // far enough final int ht = getHeight(); final int wd = getWidth(); if (wd >= 32768) { throw new ImageReadException(""Scan lines must be less than 32768 bytes long""); } final byte[] scanLineBytes = ByteConversions.toBytes((short) wd, ByteOrder.BIG_ENDIAN); final byte[] rgbe = new byte[wd * 4]; final float[][] out = new float[3][wd * ht]; for (int i = 0; i < ht; i++) { BinaryFunctions.readAndVerifyBytes(in, TWO_TWO, ""Scan line "" + i + "" expected to start with 0x2 0x2""); BinaryFunctions.readAndVerifyBytes(in, scanLineBytes, ""Scan line "" + i + "" length expected""); decompress(in, rgbe); for (int channel = 0; channel < 3; channel++) { final int channelOffset = channel * wd; final int eOffset = 3 * wd; for (int p = 0; p < wd; p++) { final int mantissa = rgbe[p + eOffset] & 0xff; final int pos = p + i * wd; if (0 == mantissa) { out[channel][pos] = 0; } else { final float mult = (float) Math.pow(2, mantissa - (128 + 8)); out[channel][pos] = ((rgbe[p + channelOffset] & 0xff) + 0.5f) * mult; } } } } return out; } ",FALSE,RgbeInfo.java " private static void decompress(final InputStream in, final byte[] out) throws IOException { int position = 0; final int total = out.length; while (position < total) { final int n = in.read(); if (n > 128) { final int value = in.read(); for (int i = 0; i < (n & 0x7f); i++) { out[position++] = (byte) value; } } else { for (int i = 0; i < n; i++) { out[position++] = (byte) in.read(); } } } } "," private static void decompress(final InputStream in, final byte[] out) throws IOException,ImageReadException { int position = 0; final int total = out.length; while (position < total) { final int n = in.read(); if (n < 0) { throw new ImageReadException(""Error decompressing RGBE file""); } if (n > 128) { final int value = in.read(); for (int i = 0; i < (n & 0x7f); i++) { out[position++] = (byte) value; } } else { for (int i = 0; i < n; i++) { out[position++] = (byte) in.read(); } } } } ",TRUE,RgbeInfo.java " public void test() throws IOException, ImageReadException { Debug.debug(""start""); final List images = getRgbeImages(); for (final File imageFile : images) { Debug.debug(""imageFile"", imageFile); final ImageMetadata metadata = Imaging.getMetadata(imageFile); assertNotNull(metadata); final ImageInfo imageInfo = Imaging.getImageInfo(imageFile); assertNotNull(imageInfo); final BufferedImage image = Imaging.getBufferedImage(imageFile); assertNotNull(image); } } "," public void test() throws IOException, ImageReadException { Debug.debug(""start""); final List images = getRgbeImages(); for (final File imageFile : images) { Debug.debug(""imageFile"", imageFile); final ImageMetadata metadata = Imaging.getMetadata(imageFile); assertNotNull(metadata); final ImageInfo imageInfo = Imaging.getImageInfo(imageFile); assertNotNull(imageInfo); final BufferedImage image = Imaging.getBufferedImage(imageFile); assertNotNull(image); } } ",FALSE,RgbeReadTest.java " } "," public void testErrorDecompressingInvalidFile() throws ImageReadException, IOException { // From IMAGING-219 File inputFile = new File( RgbeReadTest.class.getResource(""/IMAGING-219/timeout-9713502c9c371f1654b493650c16ab17c0444369"") .getFile()); ByteSourceFile byteSourceFile = new ByteSourceFile(inputFile); Map params = Collections.emptyMap(); new RgbeImageParser().getBufferedImage(byteSourceFile, params); } ",TRUE,RgbeReadTest.java " public static boolean isZipStream(InputStream in) throws IOException { in.mark(MAGIC_NUMBER.length); byte[] fileHeader = IOUtil.readBytes(in, MAGIC_NUMBER.length); in.reset(); return Arrays.equals(MAGIC_NUMBER, fileHeader); } "," public static boolean isZipStream(InputStream in) throws IOException { in.mark(MAGIC_NUMBER.length); byte[] fileHeader = IOUtil.readBytes(in, MAGIC_NUMBER.length); in.reset(); return Arrays.equals(MAGIC_NUMBER, fileHeader); } ",TRUE,ZipUtil.java " public static void extract(File zipFile, File destDir) throws IOException { try (ZipFile zf = new ZipFile(zipFile)) { extract(zf, destDir); } } "," public static void extract(File zipFile, File destDir) throws IOException { try (ZipFile zf = new ZipFile(zipFile)) { extract(zf, destDir); } } ",TRUE,ZipUtil.java " public static void extract(ZipFile zipFile, File destDir) throws IOException { assert destDir.isDirectory(); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); writeEntry(zipFile, entry, destDir); } } "," public static void extract(ZipFile zipFile, File destDir) throws IOException { assert destDir.isDirectory(); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); writeEntry(zipFile, entry, destDir); } } ",TRUE,ZipUtil.java " public static void writeEntry(ZipFile zipFile, ZipEntry entry, File destDir) throws IOException { File outFile = new File(destDir, entry.getName()); if (entry.isDirectory()) { outFile.mkdirs(); } else { outFile.getParentFile().mkdirs(); try (InputStream in = zipFile.getInputStream(entry)) { IOUtil.writeStream(in, outFile); } } } "," public static void writeEntry(ZipFile zipFile, ZipEntry entry, File destDir) throws IOException { File outFile = new File(destDir, entry.getName()); if (! outFile.getCanonicalFile().toPath().startsWith(destDir.toPath())) { throw new IOException(""Zip entry outside destination directory: "" + entry.getName()); } if (entry.isDirectory()) { outFile.mkdirs(); } else { outFile.getParentFile().mkdirs(); try (InputStream in = zipFile.getInputStream(entry)) { IOUtil.writeStream(in, outFile); } } } ",TRUE,ZipUtil.java " public XStream() { this(null, (Mapper)null, new XppDriver()); } "," public XStream() { this(null, (Mapper)null, new XppDriver()); } ",FALSE,XStream.java " public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } "," public XStream(ReflectionProvider reflectionProvider) { this(reflectionProvider, (Mapper)null, new XppDriver()); } ",FALSE,XStream.java " public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } "," public XStream(HierarchicalStreamDriver hierarchicalStreamDriver) { this(null, (Mapper)null, hierarchicalStreamDriver); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver hierarchicalStreamDriver) { this(reflectionProvider, (Mapper)null, hierarchicalStreamDriver); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { this(reflectionProvider, driver, new CompositeClassLoader(), mapper); } "," public XStream( ReflectionProvider reflectionProvider, Mapper mapper, HierarchicalStreamDriver driver) { this(reflectionProvider, driver, new CompositeClassLoader(), mapper); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference) { this(reflectionProvider, driver, classLoaderReference, null); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference) { this(reflectionProvider, driver, classLoaderReference, null); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) { this(reflectionProvider, driver, classLoader, null); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader) { this(reflectionProvider, driver, classLoader, null); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper) { this( reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, new DefaultConverterLookup()); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper) { this( reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, new DefaultConverterLookup()); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper) { this( reflectionProvider, driver, classLoaderReference, mapper, new DefaultConverterLookup()); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper) { this( reflectionProvider, driver, classLoaderReference, mapper, new DefaultConverterLookup()); } ",FALSE,XStream.java " private XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoader, Mapper mapper, final DefaultConverterLookup defaultConverterLookup) { this(reflectionProvider, driver, classLoader, mapper, new ConverterLookup() { public Converter lookupConverterForType(Class type) { return defaultConverterLookup.lookupConverterForType(type); } }, new ConverterRegistry() { public void registerConverter(Converter converter, int priority) { defaultConverterLookup.registerConverter(converter, priority); } }); } "," private XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoader, Mapper mapper, final DefaultConverterLookup defaultConverterLookup) { this(reflectionProvider, driver, classLoader, mapper, new ConverterLookup() { public Converter lookupConverterForType(Class type) { return defaultConverterLookup.lookupConverterForType(type); } }, new ConverterRegistry() { public void registerConverter(Converter converter, int priority) { defaultConverterLookup.registerConverter(converter, priority); } }); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { this(reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, converterLookup, converterRegistry); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoader classLoader, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { this(reflectionProvider, driver, new ClassLoaderReference(classLoader), mapper, converterLookup, converterRegistry); } ",FALSE,XStream.java " public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { if (reflectionProvider == null) { reflectionProvider = JVM.newReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = classLoaderReference; this.converterLookup = converterLookup; this.converterRegistry = converterRegistry; this.mapper = mapper == null ? buildMapper() : mapper; setupMappers(); setupSecurity(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } "," public XStream( ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup, ConverterRegistry converterRegistry) { if (reflectionProvider == null) { reflectionProvider = JVM.newReflectionProvider(); } this.reflectionProvider = reflectionProvider; this.hierarchicalStreamDriver = driver; this.classLoaderReference = classLoaderReference; this.converterLookup = converterLookup; this.converterRegistry = converterRegistry; this.mapper = mapper == null ? buildMapper() : mapper; setupMappers(); setupSecurity(); setupAliases(); setupDefaultImplementations(); setupConverters(); setupImmutableTypes(); setMode(XPATH_RELATIVE_REFERENCES); } ",FALSE,XStream.java " private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if (useXStream11XmlFriendlyMapper()) { mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new DynamicProxyMapper(mapper); mapper = new PackageAliasingMapper(mapper); mapper = new ClassAliasingMapper(mapper); mapper = new ElementIgnoringMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new SystemAttributeAliasingMapper(mapper); mapper = new ImplicitCollectionMapper(mapper, reflectionProvider); mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new AttributeMapper(mapper, converterLookup, reflectionProvider); if (JVM.isVersion(5)) { mapper = buildMapperDynamically( ""com.thoughtworks.xstream.mapper.EnumMapper"", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new LocalConversionMapper(mapper); mapper = new ImmutableTypesMapper(mapper); if (JVM.isVersion(8)) { mapper = buildMapperDynamically(""com.thoughtworks.xstream.mapper.LambdaMapper"", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new SecurityMapper(mapper); if (JVM.isVersion(5)) { mapper = buildMapperDynamically(ANNOTATION_MAPPER_TYPE, new Class[]{ Mapper.class, ConverterRegistry.class, ConverterLookup.class, ClassLoaderReference.class, ReflectionProvider.class}, new Object[]{ mapper, converterRegistry, converterLookup, classLoaderReference, reflectionProvider}); } mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } "," private Mapper buildMapper() { Mapper mapper = new DefaultMapper(classLoaderReference); if (useXStream11XmlFriendlyMapper()) { mapper = new XStream11XmlFriendlyMapper(mapper); } mapper = new DynamicProxyMapper(mapper); mapper = new PackageAliasingMapper(mapper); mapper = new ClassAliasingMapper(mapper); mapper = new ElementIgnoringMapper(mapper); mapper = new FieldAliasingMapper(mapper); mapper = new AttributeAliasingMapper(mapper); mapper = new SystemAttributeAliasingMapper(mapper); mapper = new ImplicitCollectionMapper(mapper, reflectionProvider); mapper = new OuterClassMapper(mapper); mapper = new ArrayMapper(mapper); mapper = new DefaultImplementationsMapper(mapper); mapper = new AttributeMapper(mapper, converterLookup, reflectionProvider); if (JVM.isVersion(5)) { mapper = buildMapperDynamically( ""com.thoughtworks.xstream.mapper.EnumMapper"", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new LocalConversionMapper(mapper); mapper = new ImmutableTypesMapper(mapper); if (JVM.isVersion(8)) { mapper = buildMapperDynamically(""com.thoughtworks.xstream.mapper.LambdaMapper"", new Class[]{Mapper.class}, new Object[]{mapper}); } mapper = new SecurityMapper(mapper); if (JVM.isVersion(5)) { mapper = buildMapperDynamically(ANNOTATION_MAPPER_TYPE, new Class[]{ Mapper.class, ConverterRegistry.class, ConverterLookup.class, ClassLoaderReference.class, ReflectionProvider.class}, new Object[]{ mapper, converterRegistry, converterLookup, classLoaderReference, reflectionProvider}); } mapper = wrapMapper((MapperWrapper)mapper); mapper = new CachingMapper(mapper); return mapper; } ",FALSE,XStream.java " private Mapper buildMapperDynamically(String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate mapper : "" + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate mapper : "" + className, e); } } "," private Mapper buildMapperDynamically(String className, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); return (Mapper)constructor.newInstance(constructorParamValues); } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate mapper : "" + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate mapper : "" + className, e); } } ",FALSE,XStream.java " protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } "," protected MapperWrapper wrapMapper(MapperWrapper next) { return next; } ",FALSE,XStream.java " protected boolean useXStream11XmlFriendlyMapper() { return false; } "," protected boolean useXStream11XmlFriendlyMapper() { return false; } ",FALSE,XStream.java " private void setupMappers() { packageAliasingMapper = (PackageAliasingMapper)this.mapper .lookupMapperOfType(PackageAliasingMapper.class); classAliasingMapper = (ClassAliasingMapper)this.mapper .lookupMapperOfType(ClassAliasingMapper.class); elementIgnoringMapper = (ElementIgnoringMapper)this.mapper .lookupMapperOfType(ElementIgnoringMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper .lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper .lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); systemAttributeAliasingMapper = (SystemAttributeAliasingMapper)this.mapper .lookupMapperOfType(SystemAttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper .lookupMapperOfType(ImmutableTypesMapper.class); localConversionMapper = (LocalConversionMapper)this.mapper .lookupMapperOfType(LocalConversionMapper.class); securityMapper = (SecurityMapper)this.mapper .lookupMapperOfType(SecurityMapper.class); annotationConfiguration = (AnnotationConfiguration)this.mapper .lookupMapperOfType(AnnotationConfiguration.class); } "," private void setupMappers() { packageAliasingMapper = (PackageAliasingMapper)this.mapper .lookupMapperOfType(PackageAliasingMapper.class); classAliasingMapper = (ClassAliasingMapper)this.mapper .lookupMapperOfType(ClassAliasingMapper.class); elementIgnoringMapper = (ElementIgnoringMapper)this.mapper .lookupMapperOfType(ElementIgnoringMapper.class); fieldAliasingMapper = (FieldAliasingMapper)this.mapper .lookupMapperOfType(FieldAliasingMapper.class); attributeMapper = (AttributeMapper)this.mapper .lookupMapperOfType(AttributeMapper.class); attributeAliasingMapper = (AttributeAliasingMapper)this.mapper .lookupMapperOfType(AttributeAliasingMapper.class); systemAttributeAliasingMapper = (SystemAttributeAliasingMapper)this.mapper .lookupMapperOfType(SystemAttributeAliasingMapper.class); implicitCollectionMapper = (ImplicitCollectionMapper)this.mapper .lookupMapperOfType(ImplicitCollectionMapper.class); defaultImplementationsMapper = (DefaultImplementationsMapper)this.mapper .lookupMapperOfType(DefaultImplementationsMapper.class); immutableTypesMapper = (ImmutableTypesMapper)this.mapper .lookupMapperOfType(ImmutableTypesMapper.class); localConversionMapper = (LocalConversionMapper)this.mapper .lookupMapperOfType(LocalConversionMapper.class); securityMapper = (SecurityMapper)this.mapper .lookupMapperOfType(SecurityMapper.class); annotationConfiguration = (AnnotationConfiguration)this.mapper .lookupMapperOfType(AnnotationConfiguration.class); } ",FALSE,XStream.java " protected void setupSecurity() { if (securityMapper == null) { return; } addPermission(AnyTypePermission.ANY); insecureWarning = true; } "," protected void setupSecurity() { if (securityMapper == null) { return; } addPermission(AnyTypePermission.ANY); securityInitialized = false; } ",TRUE,XStream.java " public static void setupDefaultSecurity(final XStream xstream) { if (xstream.insecureWarning) { xstream.addPermission(NoTypePermission.NONE); xstream.addPermission(NullPermission.NULL); xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); xstream.addPermission(ArrayTypePermission.ARRAYS); xstream.addPermission(InterfaceTypePermission.INTERFACES); xstream.allowTypeHierarchy(Calendar.class); xstream.allowTypeHierarchy(Collection.class); xstream.allowTypeHierarchy(Map.class); xstream.allowTypeHierarchy(Map.Entry.class); xstream.allowTypeHierarchy(Member.class); xstream.allowTypeHierarchy(Number.class); xstream.allowTypeHierarchy(Throwable.class); xstream.allowTypeHierarchy(TimeZone.class); Class type = JVM.loadClassForName(""java.lang.Enum""); if (type != null) { xstream.allowTypeHierarchy(type); } type = JVM.loadClassForName(""java.nio.file.Path""); if (type != null) { xstream.allowTypeHierarchy(type); } final Set types = new HashSet(); types.add(BitSet.class); types.add(Charset.class); types.add(Class.class); types.add(Currency.class); types.add(Date.class); types.add(DecimalFormatSymbols.class); types.add(File.class); types.add(Locale.class); types.add(Object.class); types.add(Pattern.class); types.add(StackTraceElement.class); types.add(String.class); types.add(StringBuffer.class); types.add(JVM.loadClassForName(""java.lang.StringBuilder"")); types.add(URL.class); types.add(URI.class); types.add(JVM.loadClassForName(""java.util.UUID"")); if (JVM.isSQLAvailable()) { types.add(JVM.loadClassForName(""java.sql.Timestamp"")); types.add(JVM.loadClassForName(""java.sql.Time"")); types.add(JVM.loadClassForName(""java.sql.Date"")); } if (JVM.isVersion(8)) { xstream.allowTypeHierarchy(JVM.loadClassForName(""java.time.Clock"")); types.add(JVM.loadClassForName(""java.time.Duration"")); types.add(JVM.loadClassForName(""java.time.Instant"")); types.add(JVM.loadClassForName(""java.time.LocalDate"")); types.add(JVM.loadClassForName(""java.time.LocalDateTime"")); types.add(JVM.loadClassForName(""java.time.LocalTime"")); types.add(JVM.loadClassForName(""java.time.MonthDay"")); types.add(JVM.loadClassForName(""java.time.OffsetDateTime"")); types.add(JVM.loadClassForName(""java.time.OffsetTime"")); types.add(JVM.loadClassForName(""java.time.Period"")); types.add(JVM.loadClassForName(""java.time.Ser"")); types.add(JVM.loadClassForName(""java.time.Year"")); types.add(JVM.loadClassForName(""java.time.YearMonth"")); types.add(JVM.loadClassForName(""java.time.ZonedDateTime"")); xstream.allowTypeHierarchy(JVM.loadClassForName(""java.time.ZoneId"")); types.add(JVM.loadClassForName(""java.time.chrono.HijrahDate"")); types.add(JVM.loadClassForName(""java.time.chrono.JapaneseDate"")); types.add(JVM.loadClassForName(""java.time.chrono.JapaneseEra"")); types.add(JVM.loadClassForName(""java.time.chrono.MinguoDate"")); types.add(JVM.loadClassForName(""java.time.chrono.ThaiBuddhistDate"")); types.add(JVM.loadClassForName(""java.time.chrono.Ser"")); xstream.allowTypeHierarchy(JVM.loadClassForName(""java.time.chrono.Chronology"")); types.add(JVM.loadClassForName(""java.time.temporal.ValueRange"")); types.add(JVM.loadClassForName(""java.time.temporal.WeekFields"")); } types.remove(null); final Iterator iter = types.iterator(); final Class[] classes = new Class[types.size()]; for (int i = 0; i < classes.length; ++i) { classes[i] = (Class)iter.next(); } xstream.allowTypes(classes); } else { throw new IllegalArgumentException(""Security framework of XStream instance already initialized""); } } "," public static void setupDefaultSecurity(final XStream xstream) { if (!xstream.securityInitialized) { xstream.addPermission(NoTypePermission.NONE); xstream.addPermission(NullPermission.NULL); xstream.addPermission(PrimitiveTypePermission.PRIMITIVES); xstream.addPermission(ArrayTypePermission.ARRAYS); xstream.addPermission(InterfaceTypePermission.INTERFACES); xstream.allowTypeHierarchy(Calendar.class); xstream.allowTypeHierarchy(Collection.class); xstream.allowTypeHierarchy(Map.class); xstream.allowTypeHierarchy(Map.Entry.class); xstream.allowTypeHierarchy(Member.class); xstream.allowTypeHierarchy(Number.class); xstream.allowTypeHierarchy(Throwable.class); xstream.allowTypeHierarchy(TimeZone.class); Class type = JVM.loadClassForName(""java.lang.Enum""); if (type != null) { xstream.allowTypeHierarchy(type); } type = JVM.loadClassForName(""java.nio.file.Path""); if (type != null) { xstream.allowTypeHierarchy(type); } final Set types = new HashSet(); types.add(BitSet.class); types.add(Charset.class); types.add(Class.class); types.add(Currency.class); types.add(Date.class); types.add(DecimalFormatSymbols.class); types.add(File.class); types.add(Locale.class); types.add(Object.class); types.add(Pattern.class); types.add(StackTraceElement.class); types.add(String.class); types.add(StringBuffer.class); types.add(JVM.loadClassForName(""java.lang.StringBuilder"")); types.add(URL.class); types.add(URI.class); types.add(JVM.loadClassForName(""java.util.UUID"")); if (JVM.isSQLAvailable()) { types.add(JVM.loadClassForName(""java.sql.Timestamp"")); types.add(JVM.loadClassForName(""java.sql.Time"")); types.add(JVM.loadClassForName(""java.sql.Date"")); } if (JVM.isVersion(8)) { xstream.allowTypeHierarchy(JVM.loadClassForName(""java.time.Clock"")); types.add(JVM.loadClassForName(""java.time.Duration"")); types.add(JVM.loadClassForName(""java.time.Instant"")); types.add(JVM.loadClassForName(""java.time.LocalDate"")); types.add(JVM.loadClassForName(""java.time.LocalDateTime"")); types.add(JVM.loadClassForName(""java.time.LocalTime"")); types.add(JVM.loadClassForName(""java.time.MonthDay"")); types.add(JVM.loadClassForName(""java.time.OffsetDateTime"")); types.add(JVM.loadClassForName(""java.time.OffsetTime"")); types.add(JVM.loadClassForName(""java.time.Period"")); types.add(JVM.loadClassForName(""java.time.Ser"")); types.add(JVM.loadClassForName(""java.time.Year"")); types.add(JVM.loadClassForName(""java.time.YearMonth"")); types.add(JVM.loadClassForName(""java.time.ZonedDateTime"")); xstream.allowTypeHierarchy(JVM.loadClassForName(""java.time.ZoneId"")); types.add(JVM.loadClassForName(""java.time.chrono.HijrahDate"")); types.add(JVM.loadClassForName(""java.time.chrono.JapaneseDate"")); types.add(JVM.loadClassForName(""java.time.chrono.JapaneseEra"")); types.add(JVM.loadClassForName(""java.time.chrono.MinguoDate"")); types.add(JVM.loadClassForName(""java.time.chrono.ThaiBuddhistDate"")); types.add(JVM.loadClassForName(""java.time.chrono.Ser"")); xstream.allowTypeHierarchy(JVM.loadClassForName(""java.time.chrono.Chronology"")); types.add(JVM.loadClassForName(""java.time.temporal.ValueRange"")); types.add(JVM.loadClassForName(""java.time.temporal.WeekFields"")); } types.remove(null); final Iterator iter = types.iterator(); final Class[] classes = new Class[types.size()]; for (int i = 0; i < classes.length; ++i) { classes[i] = (Class)iter.next(); } xstream.allowTypes(classes); } else { throw new IllegalArgumentException(""Security framework of XStream instance already initialized""); } } ",TRUE,XStream.java " protected void setupAliases() { if (classAliasingMapper == null) { return; } alias(""null"", Mapper.Null.class); alias(""int"", Integer.class); alias(""float"", Float.class); alias(""double"", Double.class); alias(""long"", Long.class); alias(""short"", Short.class); alias(""char"", Character.class); alias(""byte"", Byte.class); alias(""boolean"", Boolean.class); alias(""number"", Number.class); alias(""object"", Object.class); alias(""big-int"", BigInteger.class); alias(""big-decimal"", BigDecimal.class); alias(""string-buffer"", StringBuffer.class); alias(""string"", String.class); alias(""java-class"", Class.class); alias(""method"", Method.class); alias(""constructor"", Constructor.class); alias(""field"", Field.class); alias(""date"", Date.class); alias(""uri"", URI.class); alias(""url"", URL.class); alias(""bit-set"", BitSet.class); alias(""map"", Map.class); alias(""entry"", Map.Entry.class); alias(""properties"", Properties.class); alias(""list"", List.class); alias(""set"", Set.class); alias(""sorted-set"", SortedSet.class); alias(""linked-list"", LinkedList.class); alias(""vector"", Vector.class); alias(""tree-map"", TreeMap.class); alias(""tree-set"", TreeSet.class); alias(""hashtable"", Hashtable.class); alias(""empty-list"", Collections.EMPTY_LIST.getClass()); alias(""empty-map"", Collections.EMPTY_MAP.getClass()); alias(""empty-set"", Collections.EMPTY_SET.getClass()); alias(""singleton-list"", Collections.singletonList(this).getClass()); alias(""singleton-map"", Collections.singletonMap(this, null).getClass()); alias(""singleton-set"", Collections.singleton(this).getClass()); if (JVM.isAWTAvailable()) { // Instantiating these two classes starts the AWT system, which is undesirable. // Calling loadClass ensures a reference to the class is found but they are not // instantiated. alias(""awt-color"", JVM.loadClassForName(""java.awt.Color"", false)); alias(""awt-font"", JVM.loadClassForName(""java.awt.Font"", false)); alias(""awt-text-attribute"", JVM.loadClassForName(""java.awt.font.TextAttribute"")); } Class type = JVM.loadClassForName(""javax.activation.ActivationDataFlavor""); if (type != null) { alias(""activation-data-flavor"", type); } if (JVM.isSQLAvailable()) { alias(""sql-timestamp"", JVM.loadClassForName(""java.sql.Timestamp"")); alias(""sql-time"", JVM.loadClassForName(""java.sql.Time"")); alias(""sql-date"", JVM.loadClassForName(""java.sql.Date"")); } alias(""file"", File.class); alias(""locale"", Locale.class); alias(""gregorian-calendar"", Calendar.class); if (JVM.isVersion(4)) { aliasDynamically(""auth-subject"", ""javax.security.auth.Subject""); alias(""linked-hash-map"", JVM.loadClassForName(""java.util.LinkedHashMap"")); alias(""linked-hash-set"", JVM.loadClassForName(""java.util.LinkedHashSet"")); alias(""trace"", JVM.loadClassForName(""java.lang.StackTraceElement"")); alias(""currency"", JVM.loadClassForName(""java.util.Currency"")); aliasType(""charset"", JVM.loadClassForName(""java.nio.charset.Charset"")); } if (JVM.isVersion(5)) { aliasDynamically(""xml-duration"", ""javax.xml.datatype.Duration""); alias(""concurrent-hash-map"", JVM.loadClassForName(""java.util.concurrent.ConcurrentHashMap"")); alias(""enum-set"", JVM.loadClassForName(""java.util.EnumSet"")); alias(""enum-map"", JVM.loadClassForName(""java.util.EnumMap"")); alias(""string-builder"", JVM.loadClassForName(""java.lang.StringBuilder"")); alias(""uuid"", JVM.loadClassForName(""java.util.UUID"")); } if (JVM.isVersion(7)) { aliasType(""path"", JVM.loadClassForName(""java.nio.file.Path"")); } if (JVM.isVersion(8)) { alias(""fixed-clock"", JVM.loadClassForName(""java.time.Clock$FixedClock"")); alias(""offset-clock"", JVM.loadClassForName(""java.time.Clock$OffsetClock"")); alias(""system-clock"", JVM.loadClassForName(""java.time.Clock$SystemClock"")); alias(""tick-clock"", JVM.loadClassForName(""java.time.Clock$TickClock"")); alias(""day-of-week"", JVM.loadClassForName(""java.time.DayOfWeek"")); alias(""duration"", JVM.loadClassForName(""java.time.Duration"")); alias(""instant"", JVM.loadClassForName(""java.time.Instant"")); alias(""local-date"", JVM.loadClassForName(""java.time.LocalDate"")); alias(""local-date-time"", JVM.loadClassForName(""java.time.LocalDateTime"")); alias(""local-time"", JVM.loadClassForName(""java.time.LocalTime"")); alias(""month"", JVM.loadClassForName(""java.time.Month"")); alias(""month-day"", JVM.loadClassForName(""java.time.MonthDay"")); alias(""offset-date-time"", JVM.loadClassForName(""java.time.OffsetDateTime"")); alias(""offset-time"", JVM.loadClassForName(""java.time.OffsetTime"")); alias(""period"", JVM.loadClassForName(""java.time.Period"")); alias(""year"", JVM.loadClassForName(""java.time.Year"")); alias(""year-month"", JVM.loadClassForName(""java.time.YearMonth"")); alias(""zoned-date-time"", JVM.loadClassForName(""java.time.ZonedDateTime"")); aliasType(""zone-id"", JVM.loadClassForName(""java.time.ZoneId"")); aliasType(""chronology"", JVM.loadClassForName(""java.time.chrono.Chronology"")); alias(""hijrah-date"", JVM.loadClassForName(""java.time.chrono.HijrahDate"")); alias(""hijrah-era"", JVM.loadClassForName(""java.time.chrono.HijrahEra"")); alias(""japanese-date"", JVM.loadClassForName(""java.time.chrono.JapaneseDate"")); alias(""japanese-era"", JVM.loadClassForName(""java.time.chrono.JapaneseEra"")); alias(""minguo-date"", JVM.loadClassForName(""java.time.chrono.MinguoDate"")); alias(""minguo-era"", JVM.loadClassForName(""java.time.chrono.MinguoEra"")); alias(""thai-buddhist-date"", JVM.loadClassForName(""java.time.chrono.ThaiBuddhistDate"")); alias(""thai-buddhist-era"", JVM.loadClassForName(""java.time.chrono.ThaiBuddhistEra"")); alias(""chrono-field"", JVM.loadClassForName(""java.time.temporal.ChronoField"")); alias(""chrono-unit"", JVM.loadClassForName(""java.time.temporal.ChronoUnit"")); alias(""iso-field"", JVM.loadClassForName(""java.time.temporal.IsoFields$Field"")); alias(""iso-unit"", JVM.loadClassForName(""java.time.temporal.IsoFields$Unit"")); alias(""julian-field"", JVM.loadClassForName(""java.time.temporal.JulianFields$Field"")); alias(""temporal-value-range"", JVM.loadClassForName(""java.time.temporal.ValueRange"")); alias(""week-fields"", JVM.loadClassForName(""java.time.temporal.WeekFields"")); } if (JVM.loadClassForName(""java.lang.invoke.SerializedLambda"") != null) { aliasDynamically(""serialized-lambda"", ""java.lang.invoke.SerializedLambda""); } } "," protected void setupAliases() { if (classAliasingMapper == null) { return; } alias(""null"", Mapper.Null.class); alias(""int"", Integer.class); alias(""float"", Float.class); alias(""double"", Double.class); alias(""long"", Long.class); alias(""short"", Short.class); alias(""char"", Character.class); alias(""byte"", Byte.class); alias(""boolean"", Boolean.class); alias(""number"", Number.class); alias(""object"", Object.class); alias(""big-int"", BigInteger.class); alias(""big-decimal"", BigDecimal.class); alias(""string-buffer"", StringBuffer.class); alias(""string"", String.class); alias(""java-class"", Class.class); alias(""method"", Method.class); alias(""constructor"", Constructor.class); alias(""field"", Field.class); alias(""date"", Date.class); alias(""uri"", URI.class); alias(""url"", URL.class); alias(""bit-set"", BitSet.class); alias(""map"", Map.class); alias(""entry"", Map.Entry.class); alias(""properties"", Properties.class); alias(""list"", List.class); alias(""set"", Set.class); alias(""sorted-set"", SortedSet.class); alias(""linked-list"", LinkedList.class); alias(""vector"", Vector.class); alias(""tree-map"", TreeMap.class); alias(""tree-set"", TreeSet.class); alias(""hashtable"", Hashtable.class); alias(""empty-list"", Collections.EMPTY_LIST.getClass()); alias(""empty-map"", Collections.EMPTY_MAP.getClass()); alias(""empty-set"", Collections.EMPTY_SET.getClass()); alias(""singleton-list"", Collections.singletonList(this).getClass()); alias(""singleton-map"", Collections.singletonMap(this, null).getClass()); alias(""singleton-set"", Collections.singleton(this).getClass()); if (JVM.isAWTAvailable()) { // Instantiating these two classes starts the AWT system, which is undesirable. // Calling loadClass ensures a reference to the class is found but they are not // instantiated. alias(""awt-color"", JVM.loadClassForName(""java.awt.Color"", false)); alias(""awt-font"", JVM.loadClassForName(""java.awt.Font"", false)); alias(""awt-text-attribute"", JVM.loadClassForName(""java.awt.font.TextAttribute"")); } Class type = JVM.loadClassForName(""javax.activation.ActivationDataFlavor""); if (type != null) { alias(""activation-data-flavor"", type); } if (JVM.isSQLAvailable()) { alias(""sql-timestamp"", JVM.loadClassForName(""java.sql.Timestamp"")); alias(""sql-time"", JVM.loadClassForName(""java.sql.Time"")); alias(""sql-date"", JVM.loadClassForName(""java.sql.Date"")); } alias(""file"", File.class); alias(""locale"", Locale.class); alias(""gregorian-calendar"", Calendar.class); if (JVM.isVersion(4)) { aliasDynamically(""auth-subject"", ""javax.security.auth.Subject""); alias(""linked-hash-map"", JVM.loadClassForName(""java.util.LinkedHashMap"")); alias(""linked-hash-set"", JVM.loadClassForName(""java.util.LinkedHashSet"")); alias(""trace"", JVM.loadClassForName(""java.lang.StackTraceElement"")); alias(""currency"", JVM.loadClassForName(""java.util.Currency"")); aliasType(""charset"", JVM.loadClassForName(""java.nio.charset.Charset"")); } if (JVM.isVersion(5)) { aliasDynamically(""xml-duration"", ""javax.xml.datatype.Duration""); alias(""concurrent-hash-map"", JVM.loadClassForName(""java.util.concurrent.ConcurrentHashMap"")); alias(""enum-set"", JVM.loadClassForName(""java.util.EnumSet"")); alias(""enum-map"", JVM.loadClassForName(""java.util.EnumMap"")); alias(""string-builder"", JVM.loadClassForName(""java.lang.StringBuilder"")); alias(""uuid"", JVM.loadClassForName(""java.util.UUID"")); } if (JVM.isVersion(7)) { aliasType(""path"", JVM.loadClassForName(""java.nio.file.Path"")); } if (JVM.isVersion(8)) { alias(""fixed-clock"", JVM.loadClassForName(""java.time.Clock$FixedClock"")); alias(""offset-clock"", JVM.loadClassForName(""java.time.Clock$OffsetClock"")); alias(""system-clock"", JVM.loadClassForName(""java.time.Clock$SystemClock"")); alias(""tick-clock"", JVM.loadClassForName(""java.time.Clock$TickClock"")); alias(""day-of-week"", JVM.loadClassForName(""java.time.DayOfWeek"")); alias(""duration"", JVM.loadClassForName(""java.time.Duration"")); alias(""instant"", JVM.loadClassForName(""java.time.Instant"")); alias(""local-date"", JVM.loadClassForName(""java.time.LocalDate"")); alias(""local-date-time"", JVM.loadClassForName(""java.time.LocalDateTime"")); alias(""local-time"", JVM.loadClassForName(""java.time.LocalTime"")); alias(""month"", JVM.loadClassForName(""java.time.Month"")); alias(""month-day"", JVM.loadClassForName(""java.time.MonthDay"")); alias(""offset-date-time"", JVM.loadClassForName(""java.time.OffsetDateTime"")); alias(""offset-time"", JVM.loadClassForName(""java.time.OffsetTime"")); alias(""period"", JVM.loadClassForName(""java.time.Period"")); alias(""year"", JVM.loadClassForName(""java.time.Year"")); alias(""year-month"", JVM.loadClassForName(""java.time.YearMonth"")); alias(""zoned-date-time"", JVM.loadClassForName(""java.time.ZonedDateTime"")); aliasType(""zone-id"", JVM.loadClassForName(""java.time.ZoneId"")); aliasType(""chronology"", JVM.loadClassForName(""java.time.chrono.Chronology"")); alias(""hijrah-date"", JVM.loadClassForName(""java.time.chrono.HijrahDate"")); alias(""hijrah-era"", JVM.loadClassForName(""java.time.chrono.HijrahEra"")); alias(""japanese-date"", JVM.loadClassForName(""java.time.chrono.JapaneseDate"")); alias(""japanese-era"", JVM.loadClassForName(""java.time.chrono.JapaneseEra"")); alias(""minguo-date"", JVM.loadClassForName(""java.time.chrono.MinguoDate"")); alias(""minguo-era"", JVM.loadClassForName(""java.time.chrono.MinguoEra"")); alias(""thai-buddhist-date"", JVM.loadClassForName(""java.time.chrono.ThaiBuddhistDate"")); alias(""thai-buddhist-era"", JVM.loadClassForName(""java.time.chrono.ThaiBuddhistEra"")); alias(""chrono-field"", JVM.loadClassForName(""java.time.temporal.ChronoField"")); alias(""chrono-unit"", JVM.loadClassForName(""java.time.temporal.ChronoUnit"")); alias(""iso-field"", JVM.loadClassForName(""java.time.temporal.IsoFields$Field"")); alias(""iso-unit"", JVM.loadClassForName(""java.time.temporal.IsoFields$Unit"")); alias(""julian-field"", JVM.loadClassForName(""java.time.temporal.JulianFields$Field"")); alias(""temporal-value-range"", JVM.loadClassForName(""java.time.temporal.ValueRange"")); alias(""week-fields"", JVM.loadClassForName(""java.time.temporal.WeekFields"")); } if (JVM.loadClassForName(""java.lang.invoke.SerializedLambda"") != null) { aliasDynamically(""serialized-lambda"", ""java.lang.invoke.SerializedLambda""); } } ",FALSE,XStream.java " private void aliasDynamically(String alias, String className) { Class type = JVM.loadClassForName(className); if (type != null) { alias(alias, type); } } "," private void aliasDynamically(String alias, String className) { Class type = JVM.loadClassForName(className); if (type != null) { alias(alias, type); } } ",FALSE,XStream.java " protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(TreeSet.class, SortedSet.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } "," protected void setupDefaultImplementations() { if (defaultImplementationsMapper == null) { return; } addDefaultImplementation(HashMap.class, Map.class); addDefaultImplementation(ArrayList.class, List.class); addDefaultImplementation(HashSet.class, Set.class); addDefaultImplementation(TreeSet.class, SortedSet.class); addDefaultImplementation(GregorianCalendar.class, Calendar.class); } ",FALSE,XStream.java " protected void setupConverters() { registerConverter( new ReflectionConverter(mapper, reflectionProvider), PRIORITY_VERY_LOW); registerConverter( new SerializableConverter(mapper, reflectionProvider, classLoaderReference), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper, classLoaderReference), PRIORITY_LOW); registerConverter(new InternalBlackList(), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URIConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonCollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter((Converter)new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if (JVM.isSQLAvailable()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaFieldConverter(classLoaderReference), PRIORITY_NORMAL); if (JVM.isAWTAvailable()) { registerConverter(new FontConverter(mapper), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } if (JVM.isSwingAvailable()) { registerConverter( new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); if (JVM.isVersion(4)) { // late bound converters - allows XStream to be compiled on earlier JDKs registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.SubjectConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.ThrowableConverter"", PRIORITY_NORMAL, new Class[]{ConverterLookup.class}, new Object[]{converterLookup}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.StackTraceElementConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.CurrencyConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.RegexPatternConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.CharsetConverter"", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(5)) { // late bound converters - allows XStream to be compiled on earlier JDKs if (JVM.loadClassForName(""javax.xml.datatype.Duration"") != null) { registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.DurationConverter"", PRIORITY_NORMAL, null, null); } registerConverterDynamically( ""com.thoughtworks.xstream.converters.enums.EnumConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.enums.EnumSetConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.enums.EnumMapConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.basic.StringBuilderConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.basic.UUIDConverter"", PRIORITY_NORMAL, null, null); } if (JVM.loadClassForName(""javax.activation.ActivationDataFlavor"") != null) { registerConverterDynamically(""com.thoughtworks.xstream.converters.extended.ActivationDataFlavorConverter"", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(7)) { registerConverterDynamically(""com.thoughtworks.xstream.converters.extended.PathConverter"", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(8)) { registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ChronologyConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.DurationConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.HijrahDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.JapaneseDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.JapaneseEraConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.InstantConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.LocalDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.LocalDateTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.LocalTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.MinguoDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.MonthDayConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.OffsetTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.PeriodConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.SystemClockConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ValueRangeConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.WeekFieldsConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.YearConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.YearMonthConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ZoneIdConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.reflection.LambdaConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class, ClassLoaderReference.class}, new Object[]{mapper, reflectionProvider, classLoaderReference}); } registerConverter( new SelfStreamingInstanceChecker(converterLookup, this), PRIORITY_NORMAL); } "," protected void setupConverters() { registerConverter( new ReflectionConverter(mapper, reflectionProvider), PRIORITY_VERY_LOW); registerConverter( new SerializableConverter(mapper, reflectionProvider, classLoaderReference), PRIORITY_LOW); registerConverter(new ExternalizableConverter(mapper, classLoaderReference), PRIORITY_LOW); registerConverter(new InternalBlackList(), PRIORITY_LOW); registerConverter(new NullConverter(), PRIORITY_VERY_HIGH); registerConverter(new IntConverter(), PRIORITY_NORMAL); registerConverter(new FloatConverter(), PRIORITY_NORMAL); registerConverter(new DoubleConverter(), PRIORITY_NORMAL); registerConverter(new LongConverter(), PRIORITY_NORMAL); registerConverter(new ShortConverter(), PRIORITY_NORMAL); registerConverter((Converter)new CharConverter(), PRIORITY_NORMAL); registerConverter(new BooleanConverter(), PRIORITY_NORMAL); registerConverter(new ByteConverter(), PRIORITY_NORMAL); registerConverter(new StringConverter(), PRIORITY_NORMAL); registerConverter(new StringBufferConverter(), PRIORITY_NORMAL); registerConverter(new DateConverter(), PRIORITY_NORMAL); registerConverter(new BitSetConverter(), PRIORITY_NORMAL); registerConverter(new URIConverter(), PRIORITY_NORMAL); registerConverter(new URLConverter(), PRIORITY_NORMAL); registerConverter(new BigIntegerConverter(), PRIORITY_NORMAL); registerConverter(new BigDecimalConverter(), PRIORITY_NORMAL); registerConverter(new ArrayConverter(mapper), PRIORITY_NORMAL); registerConverter(new CharArrayConverter(), PRIORITY_NORMAL); registerConverter(new CollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new MapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new TreeSetConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonCollectionConverter(mapper), PRIORITY_NORMAL); registerConverter(new SingletonMapConverter(mapper), PRIORITY_NORMAL); registerConverter(new PropertiesConverter(), PRIORITY_NORMAL); registerConverter((Converter)new EncodedByteArrayConverter(), PRIORITY_NORMAL); registerConverter(new FileConverter(), PRIORITY_NORMAL); if (JVM.isSQLAvailable()) { registerConverter(new SqlTimestampConverter(), PRIORITY_NORMAL); registerConverter(new SqlTimeConverter(), PRIORITY_NORMAL); registerConverter(new SqlDateConverter(), PRIORITY_NORMAL); } registerConverter(new DynamicProxyConverter(mapper, classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaClassConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaMethodConverter(classLoaderReference), PRIORITY_NORMAL); registerConverter(new JavaFieldConverter(classLoaderReference), PRIORITY_NORMAL); if (JVM.isAWTAvailable()) { registerConverter(new FontConverter(mapper), PRIORITY_NORMAL); registerConverter(new ColorConverter(), PRIORITY_NORMAL); registerConverter(new TextAttributeConverter(), PRIORITY_NORMAL); } if (JVM.isSwingAvailable()) { registerConverter( new LookAndFeelConverter(mapper, reflectionProvider), PRIORITY_NORMAL); } registerConverter(new LocaleConverter(), PRIORITY_NORMAL); registerConverter(new GregorianCalendarConverter(), PRIORITY_NORMAL); if (JVM.isVersion(4)) { // late bound converters - allows XStream to be compiled on earlier JDKs registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.SubjectConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.ThrowableConverter"", PRIORITY_NORMAL, new Class[]{ConverterLookup.class}, new Object[]{converterLookup}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.StackTraceElementConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.CurrencyConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.RegexPatternConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.CharsetConverter"", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(5)) { // late bound converters - allows XStream to be compiled on earlier JDKs if (JVM.loadClassForName(""javax.xml.datatype.Duration"") != null) { registerConverterDynamically( ""com.thoughtworks.xstream.converters.extended.DurationConverter"", PRIORITY_NORMAL, null, null); } registerConverterDynamically( ""com.thoughtworks.xstream.converters.enums.EnumConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.enums.EnumSetConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.enums.EnumMapConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically( ""com.thoughtworks.xstream.converters.basic.StringBuilderConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically( ""com.thoughtworks.xstream.converters.basic.UUIDConverter"", PRIORITY_NORMAL, null, null); } if (JVM.loadClassForName(""javax.activation.ActivationDataFlavor"") != null) { registerConverterDynamically(""com.thoughtworks.xstream.converters.extended.ActivationDataFlavorConverter"", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(7)) { registerConverterDynamically(""com.thoughtworks.xstream.converters.extended.PathConverter"", PRIORITY_NORMAL, null, null); } if (JVM.isVersion(8)) { registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ChronologyConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.DurationConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.HijrahDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.JapaneseDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.JapaneseEraConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.InstantConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.LocalDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.LocalDateTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.LocalTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.MinguoDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.MonthDayConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.OffsetDateTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.OffsetTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.PeriodConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.SystemClockConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ThaiBuddhistDateConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ValueRangeConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.WeekFieldsConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class}, new Object[]{mapper}); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.YearConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.YearMonthConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ZonedDateTimeConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.time.ZoneIdConverter"", PRIORITY_NORMAL, null, null); registerConverterDynamically(""com.thoughtworks.xstream.converters.reflection.LambdaConverter"", PRIORITY_NORMAL, new Class[]{Mapper.class, ReflectionProvider.class, ClassLoaderReference.class}, new Object[]{mapper, reflectionProvider, classLoaderReference}); } registerConverter( new SelfStreamingInstanceChecker(converterLookup, this), PRIORITY_NORMAL); } ",FALSE,XStream.java " private void registerConverterDynamically(String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate converter : "" + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate converter : "" + className, e); } } "," private void registerConverterDynamically(String className, int priority, Class[] constructorParamTypes, Object[] constructorParamValues) { try { Class type = Class.forName(className, false, classLoaderReference.getReference()); Constructor constructor = type.getConstructor(constructorParamTypes); Object instance = constructor.newInstance(constructorParamValues); if (instance instanceof Converter) { registerConverter((Converter)instance, priority); } else if (instance instanceof SingleValueConverter) { registerConverter((SingleValueConverter)instance, priority); } } catch (Exception e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate converter : "" + className, e); } catch (LinkageError e) { throw new com.thoughtworks.xstream.InitializationException( ""Could not instantiate converter : "" + className, e); } } ",FALSE,XStream.java " protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class, false); addImmutableType(Boolean.class, false); addImmutableType(byte.class, false); addImmutableType(Byte.class, false); addImmutableType(char.class, false); addImmutableType(Character.class, false); addImmutableType(double.class, false); addImmutableType(Double.class, false); addImmutableType(float.class, false); addImmutableType(Float.class, false); addImmutableType(int.class, false); addImmutableType(Integer.class, false); addImmutableType(long.class, false); addImmutableType(Long.class, false); addImmutableType(short.class, false); addImmutableType(Short.class, false); // additional types addImmutableType(Mapper.Null.class, false); addImmutableType(BigDecimal.class, false); addImmutableType(BigInteger.class, false); addImmutableType(String.class, false); addImmutableType(URL.class, false); addImmutableType(File.class, false); addImmutableType(Class.class, false); if (JVM.isVersion(7)) { Class type = JVM.loadClassForName(""java.nio.file.Paths""); if (type != null) { Method methodGet; try { methodGet = type.getDeclaredMethod(""get"", new Class[] {String.class, String[].class}); if (methodGet != null) { Object path = methodGet.invoke(null, new Object[]{""."", new String[0]}); if (path != null) { addImmutableType(path.getClass(), false); } } } catch (NoSuchMethodException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } } if (JVM.isAWTAvailable()) { addImmutableTypeDynamically(""java.awt.font.TextAttribute"", false); } if (JVM.isVersion(4)) { // late bound types - allows XStream to be compiled on earlier JDKs addImmutableTypeDynamically(""java.nio.charset.Charset"", true); addImmutableTypeDynamically(""java.util.Currency"", true); } if (JVM.isVersion(5)) { addImmutableTypeDynamically(""java.util.UUID"", true); } addImmutableType(URI.class, true); addImmutableType(Collections.EMPTY_LIST.getClass(), true); addImmutableType(Collections.EMPTY_SET.getClass(), true); addImmutableType(Collections.EMPTY_MAP.getClass(), true); if (JVM.isVersion(8)) { addImmutableTypeDynamically(""java.time.Duration"", false); addImmutableTypeDynamically(""java.time.Instant"", false); addImmutableTypeDynamically(""java.time.LocalDate"", false); addImmutableTypeDynamically(""java.time.LocalDateTime"", false); addImmutableTypeDynamically(""java.time.LocalTime"", false); addImmutableTypeDynamically(""java.time.MonthDay"", false); addImmutableTypeDynamically(""java.time.OffsetDateTime"", false); addImmutableTypeDynamically(""java.time.OffsetTime"", false); addImmutableTypeDynamically(""java.time.Period"", false); addImmutableTypeDynamically(""java.time.Year"", false); addImmutableTypeDynamically(""java.time.YearMonth"", false); addImmutableTypeDynamically(""java.time.ZonedDateTime"", false); addImmutableTypeDynamically(""java.time.ZoneId"", false); addImmutableTypeDynamically(""java.time.ZoneOffset"", false); addImmutableTypeDynamically(""java.time.ZoneRegion"", false); addImmutableTypeDynamically(""java.time.chrono.HijrahChronology"", false); addImmutableTypeDynamically(""java.time.chrono.HijrahDate"", false); addImmutableTypeDynamically(""java.time.chrono.IsoChronology"", false); addImmutableTypeDynamically(""java.time.chrono.JapaneseChronology"", false); addImmutableTypeDynamically(""java.time.chrono.JapaneseDate"", false); addImmutableTypeDynamically(""java.time.chrono.JapaneseEra"", false); addImmutableTypeDynamically(""java.time.chrono.MinguoChronology"", false); addImmutableTypeDynamically(""java.time.chrono.MinguoDate"", false); addImmutableTypeDynamically(""java.time.chrono.ThaiBuddhistChronology"", false); addImmutableTypeDynamically(""java.time.chrono.ThaiBuddhistDate"", false); addImmutableTypeDynamically(""java.time.temporal.IsoFields$Field"", false); addImmutableTypeDynamically(""java.time.temporal.IsoFields$Unit"", false); addImmutableTypeDynamically(""java.time.temporal.JulianFields$Field"", false); } } "," protected void setupImmutableTypes() { if (immutableTypesMapper == null) { return; } // primitives are always immutable addImmutableType(boolean.class, false); addImmutableType(Boolean.class, false); addImmutableType(byte.class, false); addImmutableType(Byte.class, false); addImmutableType(char.class, false); addImmutableType(Character.class, false); addImmutableType(double.class, false); addImmutableType(Double.class, false); addImmutableType(float.class, false); addImmutableType(Float.class, false); addImmutableType(int.class, false); addImmutableType(Integer.class, false); addImmutableType(long.class, false); addImmutableType(Long.class, false); addImmutableType(short.class, false); addImmutableType(Short.class, false); // additional types addImmutableType(Mapper.Null.class, false); addImmutableType(BigDecimal.class, false); addImmutableType(BigInteger.class, false); addImmutableType(String.class, false); addImmutableType(URL.class, false); addImmutableType(File.class, false); addImmutableType(Class.class, false); if (JVM.isVersion(7)) { Class type = JVM.loadClassForName(""java.nio.file.Paths""); if (type != null) { Method methodGet; try { methodGet = type.getDeclaredMethod(""get"", new Class[] {String.class, String[].class}); if (methodGet != null) { Object path = methodGet.invoke(null, new Object[]{""."", new String[0]}); if (path != null) { addImmutableType(path.getClass(), false); } } } catch (NoSuchMethodException e) { } catch (SecurityException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } } if (JVM.isAWTAvailable()) { addImmutableTypeDynamically(""java.awt.font.TextAttribute"", false); } if (JVM.isVersion(4)) { // late bound types - allows XStream to be compiled on earlier JDKs addImmutableTypeDynamically(""java.nio.charset.Charset"", true); addImmutableTypeDynamically(""java.util.Currency"", true); } if (JVM.isVersion(5)) { addImmutableTypeDynamically(""java.util.UUID"", true); } addImmutableType(URI.class, true); addImmutableType(Collections.EMPTY_LIST.getClass(), true); addImmutableType(Collections.EMPTY_SET.getClass(), true); addImmutableType(Collections.EMPTY_MAP.getClass(), true); if (JVM.isVersion(8)) { addImmutableTypeDynamically(""java.time.Duration"", false); addImmutableTypeDynamically(""java.time.Instant"", false); addImmutableTypeDynamically(""java.time.LocalDate"", false); addImmutableTypeDynamically(""java.time.LocalDateTime"", false); addImmutableTypeDynamically(""java.time.LocalTime"", false); addImmutableTypeDynamically(""java.time.MonthDay"", false); addImmutableTypeDynamically(""java.time.OffsetDateTime"", false); addImmutableTypeDynamically(""java.time.OffsetTime"", false); addImmutableTypeDynamically(""java.time.Period"", false); addImmutableTypeDynamically(""java.time.Year"", false); addImmutableTypeDynamically(""java.time.YearMonth"", false); addImmutableTypeDynamically(""java.time.ZonedDateTime"", false); addImmutableTypeDynamically(""java.time.ZoneId"", false); addImmutableTypeDynamically(""java.time.ZoneOffset"", false); addImmutableTypeDynamically(""java.time.ZoneRegion"", false); addImmutableTypeDynamically(""java.time.chrono.HijrahChronology"", false); addImmutableTypeDynamically(""java.time.chrono.HijrahDate"", false); addImmutableTypeDynamically(""java.time.chrono.IsoChronology"", false); addImmutableTypeDynamically(""java.time.chrono.JapaneseChronology"", false); addImmutableTypeDynamically(""java.time.chrono.JapaneseDate"", false); addImmutableTypeDynamically(""java.time.chrono.JapaneseEra"", false); addImmutableTypeDynamically(""java.time.chrono.MinguoChronology"", false); addImmutableTypeDynamically(""java.time.chrono.MinguoDate"", false); addImmutableTypeDynamically(""java.time.chrono.ThaiBuddhistChronology"", false); addImmutableTypeDynamically(""java.time.chrono.ThaiBuddhistDate"", false); addImmutableTypeDynamically(""java.time.temporal.IsoFields$Field"", false); addImmutableTypeDynamically(""java.time.temporal.IsoFields$Unit"", false); addImmutableTypeDynamically(""java.time.temporal.JulianFields$Field"", false); } } ",FALSE,XStream.java " private void addImmutableTypeDynamically(String className, boolean isReferenceable) { Class type = JVM.loadClassForName(className); if (type != null) { addImmutableType(type, isReferenceable); } } "," private void addImmutableTypeDynamically(String className, boolean isReferenceable) { Class type = JVM.loadClassForName(className); if (type != null) { addImmutableType(type, isReferenceable); } } ",FALSE,XStream.java " public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } "," public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy) { this.marshallingStrategy = marshallingStrategy; } ",FALSE,XStream.java " public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } "," public String toXML(Object obj) { Writer writer = new StringWriter(); toXML(obj, writer); return writer.toString(); } ",FALSE,XStream.java " public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } "," public void toXML(Object obj, Writer out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } ",FALSE,XStream.java " public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } "," public void toXML(Object obj, OutputStream out) { HierarchicalStreamWriter writer = hierarchicalStreamDriver.createWriter(out); try { marshal(obj, writer); } finally { writer.flush(); } } ",FALSE,XStream.java " public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } "," public void marshal(Object obj, HierarchicalStreamWriter writer) { marshal(obj, writer, null); } ",FALSE,XStream.java " public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } "," public void marshal(Object obj, HierarchicalStreamWriter writer, DataHolder dataHolder) { marshallingStrategy.marshal(writer, obj, converterLookup, mapper, dataHolder); } ",FALSE,XStream.java " public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } "," public Object fromXML(String xml) { return fromXML(new StringReader(xml)); } ",FALSE,XStream.java " public Object fromXML(Reader reader) { return unmarshal(hierarchicalStreamDriver.createReader(reader), null); } "," public Object fromXML(Reader reader) { return unmarshal(hierarchicalStreamDriver.createReader(reader), null); } ",FALSE,XStream.java " public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } "," public Object fromXML(InputStream input) { return unmarshal(hierarchicalStreamDriver.createReader(input), null); } ",FALSE,XStream.java " public Object fromXML(URL url) { return fromXML(url, null); } "," public Object fromXML(URL url) { return fromXML(url, null); } ",FALSE,XStream.java " public Object fromXML(File file) { return fromXML(file, null); } "," public Object fromXML(File file) { return fromXML(file, null); } ",FALSE,XStream.java " public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } "," public Object fromXML(String xml, Object root) { return fromXML(new StringReader(xml), root); } ",FALSE,XStream.java " public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } "," public Object fromXML(Reader xml, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(xml), root); } ",FALSE,XStream.java " public Object fromXML(URL url, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(url), root); } "," public Object fromXML(URL url, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(url), root); } ",FALSE,XStream.java " public Object fromXML(File file, Object root) { HierarchicalStreamReader reader = hierarchicalStreamDriver.createReader(file); try { return unmarshal(reader, root); } finally { reader.close(); } } "," public Object fromXML(File file, Object root) { HierarchicalStreamReader reader = hierarchicalStreamDriver.createReader(file); try { return unmarshal(reader, root); } finally { reader.close(); } } ",FALSE,XStream.java " public Object fromXML(InputStream input, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(input), root); } "," public Object fromXML(InputStream input, Object root) { return unmarshal(hierarchicalStreamDriver.createReader(input), root); } ",FALSE,XStream.java " public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } "," public Object unmarshal(HierarchicalStreamReader reader) { return unmarshal(reader, null, null); } ",FALSE,XStream.java " public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } "," public Object unmarshal(HierarchicalStreamReader reader, Object root) { return unmarshal(reader, root, null); } ",FALSE,XStream.java " public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { try { if (insecureWarning) { insecureWarning = false; System.err.println(""Security framework of XStream not initialized, XStream is probably vulnerable.""); } return marshallingStrategy.unmarshal( root, reader, dataHolder, converterLookup, mapper); } catch (ConversionException e) { Package pkg = getClass().getPackage(); String version = pkg != null ? pkg.getImplementationVersion() : null; e.add(""version"", version != null ? version : ""not available""); throw e; } } "," public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) { try { if (!securityInitialized && !securityWarningGiven) { securityWarningGiven = true; System.err.println(""Security framework of XStream not initialized, XStream is probably vulnerable.""); } return marshallingStrategy.unmarshal( root, reader, dataHolder, converterLookup, mapper); } catch (ConversionException e) { Package pkg = getClass().getPackage(); String version = pkg != null ? pkg.getImplementationVersion() : null; e.add(""version"", version != null ? version : ""not available""); throw e; } } ",TRUE,XStream.java " public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ClassAliasingMapper.class.getName() + "" available""); } classAliasingMapper.addClassAlias(name, type); } "," public void alias(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ClassAliasingMapper.class.getName() + "" available""); } classAliasingMapper.addClassAlias(name, type); } ",FALSE,XStream.java " public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ClassAliasingMapper.class.getName() + "" available""); } classAliasingMapper.addTypeAlias(name, type); } "," public void aliasType(String name, Class type) { if (classAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ClassAliasingMapper.class.getName() + "" available""); } classAliasingMapper.addTypeAlias(name, type); } ",FALSE,XStream.java " public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } "," public void alias(String name, Class type, Class defaultImplementation) { alias(name, type); addDefaultImplementation(defaultImplementation, type); } ",FALSE,XStream.java " public void aliasPackage(String name, String pkgName) { if (packageAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + PackageAliasingMapper.class.getName() + "" available""); } packageAliasingMapper.addPackageAlias(name, pkgName); } "," public void aliasPackage(String name, String pkgName) { if (packageAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + PackageAliasingMapper.class.getName() + "" available""); } packageAliasingMapper.addPackageAlias(name, pkgName); } ",FALSE,XStream.java " public void aliasField(String alias, Class definedIn, String fieldName) { if (fieldAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + FieldAliasingMapper.class.getName() + "" available""); } fieldAliasingMapper.addFieldAlias(alias, definedIn, fieldName); } "," public void aliasField(String alias, Class definedIn, String fieldName) { if (fieldAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + FieldAliasingMapper.class.getName() + "" available""); } fieldAliasingMapper.addFieldAlias(alias, definedIn, fieldName); } ",FALSE,XStream.java " public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeAliasingMapper.class.getName() + "" available""); } attributeAliasingMapper.addAliasFor(attributeName, alias); } "," public void aliasAttribute(String alias, String attributeName) { if (attributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeAliasingMapper.class.getName() + "" available""); } attributeAliasingMapper.addAliasFor(attributeName, alias); } ",FALSE,XStream.java " public void aliasSystemAttribute(String alias, String systemAttributeName) { if (systemAttributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + SystemAttributeAliasingMapper.class.getName() + "" available""); } systemAttributeAliasingMapper.addAliasFor(systemAttributeName, alias); } "," public void aliasSystemAttribute(String alias, String systemAttributeName) { if (systemAttributeAliasingMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + SystemAttributeAliasingMapper.class.getName() + "" available""); } systemAttributeAliasingMapper.addAliasFor(systemAttributeName, alias); } ",FALSE,XStream.java " public void aliasAttribute(Class definedIn, String attributeName, String alias) { aliasField(alias, definedIn, attributeName); useAttributeFor(definedIn, attributeName); } "," public void aliasAttribute(Class definedIn, String attributeName, String alias) { aliasField(alias, definedIn, attributeName); useAttributeFor(definedIn, attributeName); } ",FALSE,XStream.java " public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeMapper.class.getName() + "" available""); } attributeMapper.addAttributeFor(fieldName, type); } "," public void useAttributeFor(String fieldName, Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeMapper.class.getName() + "" available""); } attributeMapper.addAttributeFor(fieldName, type); } ",FALSE,XStream.java " public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeMapper.class.getName() + "" available""); } attributeMapper.addAttributeFor(definedIn, fieldName); } "," public void useAttributeFor(Class definedIn, String fieldName) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeMapper.class.getName() + "" available""); } attributeMapper.addAttributeFor(definedIn, fieldName); } ",FALSE,XStream.java " public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeMapper.class.getName() + "" available""); } attributeMapper.addAttributeFor(type); } "," public void useAttributeFor(Class type) { if (attributeMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + AttributeMapper.class.getName() + "" available""); } attributeMapper.addAttributeFor(type); } ",FALSE,XStream.java " public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + DefaultImplementationsMapper.class.getName() + "" available""); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } "," public void addDefaultImplementation(Class defaultImplementation, Class ofType) { if (defaultImplementationsMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + DefaultImplementationsMapper.class.getName() + "" available""); } defaultImplementationsMapper.addDefaultImplementation(defaultImplementation, ofType); } ",FALSE,XStream.java " public void addImmutableType(Class type) { addImmutableType(type, true); } "," public void addImmutableType(Class type) { addImmutableType(type, true); } ",FALSE,XStream.java " public void addImmutableType(final Class type, final boolean isReferenceable) { if (immutableTypesMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ImmutableTypesMapper.class.getName() + "" available""); } immutableTypesMapper.addImmutableType(type, isReferenceable); } "," public void addImmutableType(final Class type, final boolean isReferenceable) { if (immutableTypesMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ImmutableTypesMapper.class.getName() + "" available""); } immutableTypesMapper.addImmutableType(type, isReferenceable); } ",FALSE,XStream.java " public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } "," public void registerConverter(Converter converter) { registerConverter(converter, PRIORITY_NORMAL); } ",FALSE,XStream.java " public void registerConverter(Converter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(converter, priority); } } "," public void registerConverter(Converter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter(converter, priority); } } ",FALSE,XStream.java " public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } "," public void registerConverter(SingleValueConverter converter) { registerConverter(converter, PRIORITY_NORMAL); } ",FALSE,XStream.java " public void registerConverter(SingleValueConverter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter( new SingleValueConverterWrapper(converter), priority); } } "," public void registerConverter(SingleValueConverter converter, int priority) { if (converterRegistry != null) { converterRegistry.registerConverter( new SingleValueConverterWrapper(converter), priority); } } ",FALSE,XStream.java " public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) { if (localConversionMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + LocalConversionMapper.class.getName() + "" available""); } localConversionMapper.registerLocalConverter(definedIn, fieldName, converter); } "," public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) { if (localConversionMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + LocalConversionMapper.class.getName() + "" available""); } localConversionMapper.registerLocalConverter(definedIn, fieldName, converter); } ",FALSE,XStream.java " public void registerLocalConverter(Class definedIn, String fieldName, SingleValueConverter converter) { registerLocalConverter( definedIn, fieldName, (Converter)new SingleValueConverterWrapper(converter)); } "," public void registerLocalConverter(Class definedIn, String fieldName, SingleValueConverter converter) { registerLocalConverter( definedIn, fieldName, (Converter)new SingleValueConverterWrapper(converter)); } ",FALSE,XStream.java " public Mapper getMapper() { return mapper; } "," public Mapper getMapper() { return mapper; } ",FALSE,XStream.java " public ReflectionProvider getReflectionProvider() { return reflectionProvider; } "," public ReflectionProvider getReflectionProvider() { return reflectionProvider; } ",FALSE,XStream.java " public ConverterLookup getConverterLookup() { return converterLookup; } "," public ConverterLookup getConverterLookup() { return converterLookup; } ",FALSE,XStream.java " public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; case SINGLE_NODE_XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; case SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; default: throw new IllegalArgumentException(""Unknown mode : "" + mode); } } "," public void setMode(int mode) { switch (mode) { case NO_REFERENCES: setMarshallingStrategy(new TreeMarshallingStrategy()); break; case ID_REFERENCES: setMarshallingStrategy(new ReferenceByIdMarshallingStrategy()); break; case XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE)); break; case XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE)); break; case SINGLE_NODE_XPATH_RELATIVE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.RELATIVE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; case SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES: setMarshallingStrategy(new ReferenceByXPathMarshallingStrategy( ReferenceByXPathMarshallingStrategy.ABSOLUTE | ReferenceByXPathMarshallingStrategy.SINGLE_NODE)); break; default: throw new IllegalArgumentException(""Unknown mode : "" + mode); } } ",FALSE,XStream.java " public void addImplicitCollection(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName, null, null); } "," public void addImplicitCollection(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName, null, null); } ",FALSE,XStream.java " public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, null, itemType); } "," public void addImplicitCollection(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, null, itemType); } ",FALSE,XStream.java " public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) { addImplicitMap(ownerType, fieldName, itemFieldName, itemType, null); } "," public void addImplicitCollection(Class ownerType, String fieldName, String itemFieldName, Class itemType) { addImplicitMap(ownerType, fieldName, itemFieldName, itemType, null); } ",FALSE,XStream.java " public void addImplicitArray(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName); } "," public void addImplicitArray(Class ownerType, String fieldName) { addImplicitCollection(ownerType, fieldName); } ",FALSE,XStream.java " public void addImplicitArray(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, itemType); } "," public void addImplicitArray(Class ownerType, String fieldName, Class itemType) { addImplicitCollection(ownerType, fieldName, itemType); } ",FALSE,XStream.java " public void addImplicitArray(Class ownerType, String fieldName, String itemName) { addImplicitCollection(ownerType, fieldName, itemName, null); } "," public void addImplicitArray(Class ownerType, String fieldName, String itemName) { addImplicitCollection(ownerType, fieldName, itemName, null); } ",FALSE,XStream.java " public void addImplicitMap(Class ownerType, String fieldName, Class itemType, String keyFieldName) { addImplicitMap(ownerType, fieldName, null, itemType, keyFieldName); } "," public void addImplicitMap(Class ownerType, String fieldName, Class itemType, String keyFieldName) { addImplicitMap(ownerType, fieldName, null, itemType, keyFieldName); } ",FALSE,XStream.java " public void addImplicitMap(Class ownerType, String fieldName, String itemName, Class itemType, String keyFieldName) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ImplicitCollectionMapper.class.getName() + "" available""); } implicitCollectionMapper.add(ownerType, fieldName, itemName, itemType, keyFieldName); } "," public void addImplicitMap(Class ownerType, String fieldName, String itemName, Class itemType, String keyFieldName) { if (implicitCollectionMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ImplicitCollectionMapper.class.getName() + "" available""); } implicitCollectionMapper.add(ownerType, fieldName, itemName, itemType, keyFieldName); } ",FALSE,XStream.java " public DataHolder newDataHolder() { return new MapBackedDataHolder(); } "," public DataHolder newDataHolder() { return new MapBackedDataHolder(); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(writer), ""object-stream""); } "," public ObjectOutputStream createObjectOutputStream(Writer writer) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(writer), ""object-stream""); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, ""object-stream""); } "," public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer) throws IOException { return createObjectOutputStream(writer, ""object-stream""); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(writer), rootNodeName); } "," public ObjectOutputStream createObjectOutputStream(Writer writer, String rootNodeName) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(writer), rootNodeName); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(OutputStream out) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(out), ""object-stream""); } "," public ObjectOutputStream createObjectOutputStream(OutputStream out) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(out), ""object-stream""); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(OutputStream out, String rootNodeName) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(out), rootNodeName); } "," public ObjectOutputStream createObjectOutputStream(OutputStream out, String rootNodeName) throws IOException { return createObjectOutputStream( hierarchicalStreamDriver.createWriter(out), rootNodeName); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName) throws IOException { return createObjectOutputStream(writer, rootNodeName, null); } "," public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName) throws IOException { return createObjectOutputStream(writer, rootNodeName, null); } ",FALSE,XStream.java " public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName, final DataHolder dataHolder) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(final Object object) { marshal(object, statefulWriter, dataHolder); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException(""not in call to writeObject""); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException(""not in call to writeObject""); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } "," public ObjectOutputStream createObjectOutputStream(final HierarchicalStreamWriter writer, final String rootNodeName, final DataHolder dataHolder) throws IOException { final StatefulWriter statefulWriter = new StatefulWriter(writer); statefulWriter.startNode(rootNodeName, null); return new CustomObjectOutputStream(new CustomObjectOutputStream.StreamCallback() { public void writeToStream(final Object object) { marshal(object, statefulWriter, dataHolder); } public void writeFieldsToStream(Map fields) throws NotActiveException { throw new NotActiveException(""not in call to writeObject""); } public void defaultWriteObject() throws NotActiveException { throw new NotActiveException(""not in call to writeObject""); } public void flush() { statefulWriter.flush(); } public void close() { if (statefulWriter.state() != StatefulWriter.STATE_CLOSED) { statefulWriter.endNode(); statefulWriter.close(); } } }); } ",FALSE,XStream.java " public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } "," public ObjectInputStream createObjectInputStream(Reader xmlReader) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(xmlReader)); } ",FALSE,XStream.java " public ObjectInputStream createObjectInputStream(InputStream in) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(in)); } "," public ObjectInputStream createObjectInputStream(InputStream in) throws IOException { return createObjectInputStream(hierarchicalStreamDriver.createReader(in)); } ",FALSE,XStream.java " public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return createObjectInputStream(reader, null); } "," public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader) throws IOException { return createObjectInputStream(reader, null); } ",FALSE,XStream.java " public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); final Object result = unmarshal(reader, dataHolder); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException(""not in call to readObject""); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException(""not in call to readObject""); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException(""stream inactive""); } public void close() { reader.close(); } }, classLoaderReference); } "," public ObjectInputStream createObjectInputStream(final HierarchicalStreamReader reader, final DataHolder dataHolder) throws IOException { return new CustomObjectInputStream(new CustomObjectInputStream.StreamCallback() { public Object readFromStream() throws EOFException { if (!reader.hasMoreChildren()) { throw new EOFException(); } reader.moveDown(); final Object result = unmarshal(reader, dataHolder); reader.moveUp(); return result; } public Map readFieldsFromStream() throws IOException { throw new NotActiveException(""not in call to readObject""); } public void defaultReadObject() throws NotActiveException { throw new NotActiveException(""not in call to readObject""); } public void registerValidation(ObjectInputValidation validation, int priority) throws NotActiveException { throw new NotActiveException(""stream inactive""); } public void close() { reader.close(); } }, classLoaderReference); } ",FALSE,XStream.java " public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } "," public void setClassLoader(ClassLoader classLoader) { classLoaderReference.setReference(classLoader); } ",FALSE,XStream.java " public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } "," public ClassLoader getClassLoader() { return classLoaderReference.getReference(); } ",FALSE,XStream.java " public ClassLoaderReference getClassLoaderReference() { return classLoaderReference; } "," public ClassLoaderReference getClassLoaderReference() { return classLoaderReference; } ",FALSE,XStream.java " public void omitField(Class definedIn, String fieldName) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ElementIgnoringMapper.class.getName() + "" available""); } elementIgnoringMapper.omitField(definedIn, fieldName); } "," public void omitField(Class definedIn, String fieldName) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ElementIgnoringMapper.class.getName() + "" available""); } elementIgnoringMapper.omitField(definedIn, fieldName); } ",FALSE,XStream.java " public void ignoreUnknownElements() { ignoreUnknownElements(IGNORE_ALL); } "," public void ignoreUnknownElements() { ignoreUnknownElements(IGNORE_ALL); } ",FALSE,XStream.java " public void ignoreUnknownElements(String pattern) { ignoreUnknownElements(Pattern.compile(pattern)); } "," public void ignoreUnknownElements(String pattern) { ignoreUnknownElements(Pattern.compile(pattern)); } ",FALSE,XStream.java " public void ignoreUnknownElements(final Pattern pattern) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ElementIgnoringMapper.class.getName() + "" available""); } elementIgnoringMapper.addElementsToIgnore(pattern); } "," public void ignoreUnknownElements(final Pattern pattern) { if (elementIgnoringMapper == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ElementIgnoringMapper.class.getName() + "" available""); } elementIgnoringMapper.addElementsToIgnore(pattern); } ",FALSE,XStream.java " public void processAnnotations(final Class[] types) { if (annotationConfiguration == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ANNOTATION_MAPPER_TYPE + "" available""); } annotationConfiguration.processAnnotations(types); } "," public void processAnnotations(final Class[] types) { if (annotationConfiguration == null) { throw new com.thoughtworks.xstream.InitializationException(""No "" + ANNOTATION_MAPPER_TYPE + "" available""); } annotationConfiguration.processAnnotations(types); } ",FALSE,XStream.java " public void processAnnotations(final Class type) { processAnnotations(new Class[]{type}); } "," public void processAnnotations(final Class type) { processAnnotations(new Class[]{type}); } ",FALSE,XStream.java " public void autodetectAnnotations(boolean mode) { if (annotationConfiguration != null) { annotationConfiguration.autodetectAnnotations(mode); } } "," public void autodetectAnnotations(boolean mode) { if (annotationConfiguration != null) { annotationConfiguration.autodetectAnnotations(mode); } } ",FALSE,XStream.java " public void addPermission(TypePermission permission) { if (securityMapper != null) { insecureWarning &= permission != NoTypePermission.NONE; securityMapper.addPermission(permission); } } "," public void addPermission(TypePermission permission) { if (securityMapper != null) { if (permission == AnyTypePermission.ANY) securityInitialized = false; else if (permission == NoTypePermission.NONE) { securityInitialized = true; } securityInitialized = true; securityMapper.addPermission(permission); } } ",TRUE,XStream.java " public void allowTypes(String[] names) { addPermission(new ExplicitTypePermission(names)); } "," public void allowTypes(String[] names) { addPermission(new ExplicitTypePermission(names)); } ",FALSE,XStream.java " public void allowTypes(Class[] types) { addPermission(new ExplicitTypePermission(types)); } "," public void allowTypes(Class[] types) { addPermission(new ExplicitTypePermission(types)); } ",FALSE,XStream.java " public void allowTypeHierarchy(Class type) { addPermission(new TypeHierarchyPermission(type)); } "," public void allowTypeHierarchy(Class type) { addPermission(new TypeHierarchyPermission(type)); } ",FALSE,XStream.java " public void allowTypesByRegExp(String[] regexps) { addPermission(new RegExpTypePermission(regexps)); } "," public void allowTypesByRegExp(String[] regexps) { addPermission(new RegExpTypePermission(regexps)); } ",FALSE,XStream.java " public void allowTypesByRegExp(Pattern[] regexps) { addPermission(new RegExpTypePermission(regexps)); } "," public void allowTypesByRegExp(Pattern[] regexps) { addPermission(new RegExpTypePermission(regexps)); } ",FALSE,XStream.java " public void allowTypesByWildcard(String[] patterns) { addPermission(new WildcardTypePermission(patterns)); } "," public void allowTypesByWildcard(String[] patterns) { addPermission(new WildcardTypePermission(patterns)); } ",FALSE,XStream.java " public void denyPermission(TypePermission permission) { addPermission(new NoPermission(permission)); } "," public void denyPermission(TypePermission permission) { addPermission(new NoPermission(permission)); } ",FALSE,XStream.java " public void denyTypes(String[] names) { denyPermission(new ExplicitTypePermission(names)); } "," public void denyTypes(String[] names) { denyPermission(new ExplicitTypePermission(names)); } ",FALSE,XStream.java " public void denyTypes(Class[] types) { denyPermission(new ExplicitTypePermission(types)); } "," public void denyTypes(Class[] types) { denyPermission(new ExplicitTypePermission(types)); } ",FALSE,XStream.java " public void denyTypeHierarchy(Class type) { denyPermission(new TypeHierarchyPermission(type)); } "," public void denyTypeHierarchy(Class type) { denyPermission(new TypeHierarchyPermission(type)); } ",FALSE,XStream.java " public void denyTypesByRegExp(String[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } "," public void denyTypesByRegExp(String[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } ",FALSE,XStream.java " public void denyTypesByRegExp(Pattern[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } "," public void denyTypesByRegExp(Pattern[] regexps) { denyPermission(new RegExpTypePermission(regexps)); } ",FALSE,XStream.java " public void denyTypesByWildcard(String[] patterns) { denyPermission(new WildcardTypePermission(patterns)); } "," public void denyTypesByWildcard(String[] patterns) { denyPermission(new WildcardTypePermission(patterns)); } ",FALSE,XStream.java " } "," private Object readResolve() { securityWarningGiven = true; return this; } ",TRUE,XStream.java " public InitializationException(String message, Throwable cause) { super(message, cause); } "," public InitializationException(String message, Throwable cause) { super(message, cause); } ",FALSE,XStream.java " public InitializationException(String message) { super(message); } "," public InitializationException(String message) { super(message); } ",FALSE,XStream.java " public boolean canConvert(final Class type) { return (type == void.class || type == Void.class) || (insecureWarning && type != null && (type.getName().equals(""java.beans.EventHandler"") || type.getName().endsWith(""$LazyIterator"") || type.getName().startsWith(""javax.crypto.""))); } "," public boolean canConvert(final Class type) { return (type == void.class || type == Void.class) || (!securityInitialized && type != null && (type.getName().equals(""java.beans.EventHandler"") || type.getName().endsWith(""$LazyIterator"") || type.getName().startsWith(""javax.crypto.""))); } ",TRUE,XStream.java " public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) { throw new ConversionException(""Security alert. Marshalling rejected.""); } "," public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) { throw new ConversionException(""Security alert. Marshalling rejected.""); } ",FALSE,XStream.java " public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) { throw new ConversionException(""Security alert. Unmarshalling rejected.""); } "," public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) { throw new ConversionException(""Security alert. Unmarshalling rejected.""); } ",FALSE,XStream.java " protected void setUp() throws Exception { super.setUp(); BUFFER.setLength(0); xstream.alias(""runnable"", Runnable.class); xstream.allowTypeHierarchy(Runnable.class); xstream.addPermission(ProxyTypePermission.PROXIES); } "," protected void setUp() throws Exception { super.setUp(); BUFFER.setLength(0); xstream.alias(""runnable"", Runnable.class); xstream.allowTypeHierarchy(Runnable.class); xstream.addPermission(ProxyTypePermission.PROXIES); } ",FALSE,SecurityVulnerabilityTest.java " public void testCannotInjectEventHandler() { final String xml = """" + ""\n"" + "" \n"" + "" java.lang.Runnable\n"" + "" \n"" + "" \n"" + "" exec\n"" + "" \n"" + "" \n"" + """"; try { xstream.fromXML(xml); fail(""Thrown "" + XStreamException.class.getName() + "" expected""); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf(EventHandler.class.getName()) > 0); } assertEquals(0, BUFFER.length()); } "," public void testCannotInjectEventHandler() { final String xml = """" + ""\n"" + "" \n"" + "" java.lang.Runnable\n"" + "" \n"" + "" \n"" + "" exec\n"" + "" \n"" + "" \n"" + """"; try { xstream.fromXML(xml); fail(""Thrown "" + XStreamException.class.getName() + "" expected""); } catch (final XStreamException e) { assertTrue(e.getMessage().indexOf(EventHandler.class.getName()) > 0); } assertEquals(0, BUFFER.length()); } ",FALSE,SecurityVulnerabilityTest.java " } "," public void testCannotInjectEventHandlerWithUnconfiguredSecurityFramework() { xstream = new XStream(createDriver()); xstream.alias(""runnable"", Runnable.class); final String xml = """" + ""\n"" + "" \n"" + "" java.lang.Runnable\n"" + "" \n"" + "" \n"" + "" exec\n"" + "" \n"" + "" \n"" + """"; try { xstream.fromXML(xml); fail(""Thrown "" + XStreamException.class.getName() + "" expected""); } catch (final XStreamException e) { assertTrue(e.getMessage().contains(EventHandler.class.getName())); } assertEquals(0, BUFFER.length()); } ",TRUE,SecurityVulnerabilityTest.java " public void testExplicitlyConvertEventHandler() { final String xml = """" + ""\n"" + "" \n"" + "" java.lang.Runnable\n"" + "" \n"" + "" \n"" + "" exec\n"" + "" \n"" + "" \n"" + """"; xstream.allowTypes(new Class[]{EventHandler.class}); xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream .getReflectionProvider(), EventHandler.class)); final Runnable[] array = (Runnable[])xstream.fromXML(xml); assertEquals(0, BUFFER.length()); array[0].run(); assertEquals(""Executed!"", BUFFER.toString()); } "," public void testExplicitlyConvertEventHandler() { final String xml = """" + ""\n"" + "" \n"" + "" java.lang.Runnable\n"" + "" \n"" + "" \n"" + "" exec\n"" + "" \n"" + "" \n"" + """"; xstream.allowTypes(new Class[]{EventHandler.class}); xstream.registerConverter(new ReflectionConverter(xstream.getMapper(), xstream .getReflectionProvider(), EventHandler.class)); final Runnable[] array = (Runnable[])xstream.fromXML(xml); assertEquals(0, BUFFER.length()); array[0].run(); assertEquals(""Executed!"", BUFFER.toString()); } ",FALSE,SecurityVulnerabilityTest.java " public void exec() { BUFFER.append(""Executed!""); } "," public void exec() { BUFFER.append(""Executed!""); } ",FALSE,SecurityVulnerabilityTest.java " public void testDeniedInstanceOfVoid() { try { xstream.fromXML(""""); fail(""Thrown "" + ForbiddenClassException.class.getName() + "" expected""); } catch (final ForbiddenClassException e) { // OK } } "," public void testDeniedInstanceOfVoid() { try { xstream.fromXML(""""); fail(""Thrown "" + ForbiddenClassException.class.getName() + "" expected""); } catch (final ForbiddenClassException e) { // OK } } ",FALSE,SecurityVulnerabilityTest.java " public void testAllowedInstanceOfVoid() { xstream.allowTypes(new Class[] { void.class, Void.class }); try { xstream.fromXML(""""); fail(""Thrown "" + ConversionException.class.getName() + "" expected""); } catch (final ConversionException e) { assertEquals(""void"", e.get(""required-type"")); } } "," public void testAllowedInstanceOfVoid() { xstream.allowTypes(new Class[] { void.class, Void.class }); try { xstream.fromXML(""""); fail(""Thrown "" + ConversionException.class.getName() + "" expected""); } catch (final ConversionException e) { assertEquals(""void"", e.get(""required-type"")); } } ",FALSE,SecurityVulnerabilityTest.java " protected AbstractUrlBasedTicketValidator(final String casServerUrlPrefix) { this.casServerUrlPrefix = casServerUrlPrefix; CommonUtils.assertNotNull(this.casServerUrlPrefix, ""casServerUrlPrefix cannot be null.""); } "," protected AbstractUrlBasedTicketValidator(final String casServerUrlPrefix) { this.casServerUrlPrefix = casServerUrlPrefix; CommonUtils.assertNotNull(this.casServerUrlPrefix, ""casServerUrlPrefix cannot be null.""); } ",FALSE,AbstractUrlBasedTicketValidator.java " protected void populateUrlAttributeMap(final Map urlParameters) { // nothing to do } "," protected void populateUrlAttributeMap(final Map urlParameters) { // nothing to do } ",FALSE,AbstractUrlBasedTicketValidator.java " protected final String constructValidationUrl(final String ticket, final String serviceUrl) { final Map urlParameters = new HashMap(); logger.debug(""Placing URL parameters in map.""); urlParameters.put(""ticket"", ticket); urlParameters.put(""service"", encodeUrl(serviceUrl)); if (this.renew) { urlParameters.put(""renew"", ""true""); } logger.debug(""Calling template URL attribute map.""); populateUrlAttributeMap(urlParameters); logger.debug(""Loading custom parameters from configuration.""); if (this.customParameters != null) { urlParameters.putAll(this.customParameters); } final String suffix = getUrlSuffix(); final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length() + suffix.length() + 1); int i = 0; buffer.append(this.casServerUrlPrefix); if (!this.casServerUrlPrefix.endsWith(""/"")) { buffer.append(""/""); } buffer.append(suffix); for (Map.Entry entry : urlParameters.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (value != null) { buffer.append(i++ == 0 ? ""?"" : ""&""); buffer.append(key); buffer.append(""=""); buffer.append(value); } } return buffer.toString(); } "," protected final String constructValidationUrl(final String ticket, final String serviceUrl) { final Map urlParameters = new HashMap(); logger.debug(""Placing URL parameters in map.""); urlParameters.put(""ticket"", ticket); urlParameters.put(""service"", serviceUrl); if (this.renew) { urlParameters.put(""renew"", ""true""); } logger.debug(""Calling template URL attribute map.""); populateUrlAttributeMap(urlParameters); logger.debug(""Loading custom parameters from configuration.""); if (this.customParameters != null) { urlParameters.putAll(this.customParameters); } final String suffix = getUrlSuffix(); final StringBuilder buffer = new StringBuilder(urlParameters.size() * 10 + this.casServerUrlPrefix.length() + suffix.length() + 1); int i = 0; buffer.append(this.casServerUrlPrefix); if (!this.casServerUrlPrefix.endsWith(""/"")) { buffer.append(""/""); } buffer.append(suffix); for (Map.Entry entry : urlParameters.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (value != null) { buffer.append(i++ == 0 ? ""?"" : ""&""); buffer.append(key); buffer.append(""=""); final String encodedValue = encodeUrl(value); buffer.append(encodedValue); } } return buffer.toString(); } ",TRUE,AbstractUrlBasedTicketValidator.java " protected final String encodeUrl(final String url) { if (url == null) { return null; } try { return URLEncoder.encode(url, ""UTF-8""); } catch (final UnsupportedEncodingException e) { return url; } } "," protected final String encodeUrl(final String url) { if (url == null) { return null; } try { return URLEncoder.encode(url, ""UTF-8""); } catch (final UnsupportedEncodingException e) { return url; } } ",FALSE,AbstractUrlBasedTicketValidator.java " public final Assertion validate(final String ticket, final String service) throws TicketValidationException { final String validationUrl = constructValidationUrl(ticket, service); logger.debug(""Constructing validation url: {}"", validationUrl); try { logger.debug(""Retrieving response from server.""); final String serverResponse = retrieveResponseFromServer(new URL(validationUrl), ticket); if (serverResponse == null) { throw new TicketValidationException(""The CAS server returned no response.""); } logger.debug(""Server response: {}"", serverResponse); return parseResponseFromServer(serverResponse); } catch (final MalformedURLException e) { throw new TicketValidationException(e); } } "," public final Assertion validate(final String ticket, final String service) throws TicketValidationException { final String validationUrl = constructValidationUrl(ticket, service); logger.debug(""Constructing validation url: {}"", validationUrl); try { logger.debug(""Retrieving response from server.""); final String serverResponse = retrieveResponseFromServer(new URL(validationUrl), ticket); if (serverResponse == null) { throw new TicketValidationException(""The CAS server returned no response.""); } logger.debug(""Server response: {}"", serverResponse); return parseResponseFromServer(serverResponse); } catch (final MalformedURLException e) { throw new TicketValidationException(e); } } ",FALSE,AbstractUrlBasedTicketValidator.java " public final void setRenew(final boolean renew) { this.renew = renew; } "," public final void setRenew(final boolean renew) { this.renew = renew; } ",FALSE,AbstractUrlBasedTicketValidator.java " public final void setCustomParameters(final Map customParameters) { this.customParameters = customParameters; } "," public final void setCustomParameters(final Map customParameters) { this.customParameters = customParameters; } ",FALSE,AbstractUrlBasedTicketValidator.java " public final void setEncoding(final String encoding) { this.encoding = encoding; } "," public final void setEncoding(final String encoding) { this.encoding = encoding; } ",FALSE,AbstractUrlBasedTicketValidator.java " protected final String getEncoding() { return this.encoding; } "," protected final String getEncoding() { return this.encoding; } ",FALSE,AbstractUrlBasedTicketValidator.java " protected final boolean isRenew() { return this.renew; } "," protected final boolean isRenew() { return this.renew; } ",FALSE,AbstractUrlBasedTicketValidator.java " protected final String getCasServerUrlPrefix() { return this.casServerUrlPrefix; } "," protected final String getCasServerUrlPrefix() { return this.casServerUrlPrefix; } ",FALSE,AbstractUrlBasedTicketValidator.java " protected final Map getCustomParameters() { return this.customParameters; } "," protected final Map getCustomParameters() { return this.customParameters; } ",FALSE,AbstractUrlBasedTicketValidator.java " protected HttpURLConnectionFactory getURLConnectionFactory() { return this.urlConnectionFactory; } "," protected HttpURLConnectionFactory getURLConnectionFactory() { return this.urlConnectionFactory; } ",FALSE,AbstractUrlBasedTicketValidator.java " public void setURLConnectionFactory(final HttpURLConnectionFactory urlConnectionFactory) { this.urlConnectionFactory = urlConnectionFactory; } "," public void setURLConnectionFactory(final HttpURLConnectionFactory urlConnectionFactory) { this.urlConnectionFactory = urlConnectionFactory; } ",FALSE,AbstractUrlBasedTicketValidator.java " public Cas20ServiceTicketValidator(final String casServerUrlPrefix) { super(casServerUrlPrefix); this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory()); } "," public Cas20ServiceTicketValidator(final String casServerUrlPrefix) { super(casServerUrlPrefix); this.proxyRetriever = new Cas20ProxyRetriever(casServerUrlPrefix, getEncoding(), getURLConnectionFactory()); } ",FALSE,Cas20ServiceTicketValidator.java " protected final void populateUrlAttributeMap(final Map urlParameters) { urlParameters.put(""pgtUrl"", encodeUrl(this.proxyCallbackUrl)); } "," protected final void populateUrlAttributeMap(final Map urlParameters) { urlParameters.put(""pgtUrl"", this.proxyCallbackUrl); } ",TRUE,Cas20ServiceTicketValidator.java " protected String getUrlSuffix() { return ""serviceValidate""; } "," protected String getUrlSuffix() { return ""serviceValidate""; } ",FALSE,Cas20ServiceTicketValidator.java " protected final Assertion parseResponseFromServer(final String response) throws TicketValidationException { final String error = XmlUtils.getTextForElement(response, ""authenticationFailure""); if (CommonUtils.isNotBlank(error)) { throw new TicketValidationException(error); } final String principal = XmlUtils.getTextForElement(response, ""user""); final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, ""proxyGrantingTicket""); final String proxyGrantingTicket; if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) { proxyGrantingTicket = null; } else { proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou); } if (CommonUtils.isEmpty(principal)) { throw new TicketValidationException(""No principal was found in the response from the CAS server.""); } final Assertion assertion; final Map attributes = extractCustomAttributes(response); if (CommonUtils.isNotBlank(proxyGrantingTicket)) { final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes, proxyGrantingTicket, this.proxyRetriever); assertion = new AssertionImpl(attributePrincipal); } else { assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes)); } customParseResponse(response, assertion); return assertion; } "," protected final Assertion parseResponseFromServer(final String response) throws TicketValidationException { final String error = XmlUtils.getTextForElement(response, ""authenticationFailure""); if (CommonUtils.isNotBlank(error)) { throw new TicketValidationException(error); } final String principal = XmlUtils.getTextForElement(response, ""user""); final String proxyGrantingTicketIou = XmlUtils.getTextForElement(response, ""proxyGrantingTicket""); final String proxyGrantingTicket; if (CommonUtils.isBlank(proxyGrantingTicketIou) || this.proxyGrantingTicketStorage == null) { proxyGrantingTicket = null; } else { proxyGrantingTicket = this.proxyGrantingTicketStorage.retrieve(proxyGrantingTicketIou); } if (CommonUtils.isEmpty(principal)) { throw new TicketValidationException(""No principal was found in the response from the CAS server.""); } final Assertion assertion; final Map attributes = extractCustomAttributes(response); if (CommonUtils.isNotBlank(proxyGrantingTicket)) { final AttributePrincipal attributePrincipal = new AttributePrincipalImpl(principal, attributes, proxyGrantingTicket, this.proxyRetriever); assertion = new AssertionImpl(attributePrincipal); } else { assertion = new AssertionImpl(new AttributePrincipalImpl(principal, attributes)); } customParseResponse(response, assertion); return assertion; } ",FALSE,Cas20ServiceTicketValidator.java " protected Map extractCustomAttributes(final String xml) { final SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); try { final SAXParser saxParser = spf.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final CustomAttributeHandler handler = new CustomAttributeHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(xml))); return handler.getAttributes(); } catch (final Exception e) { logger.error(e.getMessage(), e); return Collections.emptyMap(); } } "," protected Map extractCustomAttributes(final String xml) { final SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); spf.setValidating(false); try { final SAXParser saxParser = spf.newSAXParser(); final XMLReader xmlReader = saxParser.getXMLReader(); final CustomAttributeHandler handler = new CustomAttributeHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(xml))); return handler.getAttributes(); } catch (final Exception e) { logger.error(e.getMessage(), e); return Collections.emptyMap(); } } ",FALSE,Cas20ServiceTicketValidator.java " protected void customParseResponse(final String response, final Assertion assertion) throws TicketValidationException { // nothing to do } "," protected void customParseResponse(final String response, final Assertion assertion) throws TicketValidationException { // nothing to do } ",FALSE,Cas20ServiceTicketValidator.java " public final void setProxyCallbackUrl(final String proxyCallbackUrl) { this.proxyCallbackUrl = proxyCallbackUrl; } "," public final void setProxyCallbackUrl(final String proxyCallbackUrl) { this.proxyCallbackUrl = proxyCallbackUrl; } ",FALSE,Cas20ServiceTicketValidator.java " public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) { this.proxyGrantingTicketStorage = proxyGrantingTicketStorage; } "," public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) { this.proxyGrantingTicketStorage = proxyGrantingTicketStorage; } ",FALSE,Cas20ServiceTicketValidator.java " public final void setProxyRetriever(final ProxyRetriever proxyRetriever) { this.proxyRetriever = proxyRetriever; } "," public final void setProxyRetriever(final ProxyRetriever proxyRetriever) { this.proxyRetriever = proxyRetriever; } ",FALSE,Cas20ServiceTicketValidator.java " protected final String getProxyCallbackUrl() { return this.proxyCallbackUrl; } "," protected final String getProxyCallbackUrl() { return this.proxyCallbackUrl; } ",FALSE,Cas20ServiceTicketValidator.java " protected final ProxyGrantingTicketStorage getProxyGrantingTicketStorage() { return this.proxyGrantingTicketStorage; } "," protected final ProxyGrantingTicketStorage getProxyGrantingTicketStorage() { return this.proxyGrantingTicketStorage; } ",FALSE,Cas20ServiceTicketValidator.java " protected final ProxyRetriever getProxyRetriever() { return this.proxyRetriever; } "," protected final ProxyRetriever getProxyRetriever() { return this.proxyRetriever; } ",FALSE,Cas20ServiceTicketValidator.java " public void startDocument() throws SAXException { this.attributes = new HashMap(); } "," public void startDocument() throws SAXException { this.attributes = new HashMap(); } ",FALSE,Cas20ServiceTicketValidator.java " public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes attributes) throws SAXException { if (""attributes"".equals(localName)) { this.foundAttributes = true; } else if (this.foundAttributes) { this.value = new StringBuilder(); this.currentAttribute = localName; } } "," public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes attributes) throws SAXException { if (""attributes"".equals(localName)) { this.foundAttributes = true; } else if (this.foundAttributes) { this.value = new StringBuilder(); this.currentAttribute = localName; } } ",FALSE,Cas20ServiceTicketValidator.java " public void characters(final char[] chars, final int start, final int length) throws SAXException { if (this.currentAttribute != null) { value.append(chars, start, length); } } "," public void characters(final char[] chars, final int start, final int length) throws SAXException { if (this.currentAttribute != null) { value.append(chars, start, length); } } ",FALSE,Cas20ServiceTicketValidator.java " public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { if (""attributes"".equals(localName)) { this.foundAttributes = false; this.currentAttribute = null; } else if (this.foundAttributes) { final Object o = this.attributes.get(this.currentAttribute); if (o == null) { this.attributes.put(this.currentAttribute, this.value.toString()); } else { final List items; if (o instanceof List) { items = (List) o; } else { items = new LinkedList(); items.add(o); this.attributes.put(this.currentAttribute, items); } items.add(this.value.toString()); } } } "," public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { if (""attributes"".equals(localName)) { this.foundAttributes = false; this.currentAttribute = null; } else if (this.foundAttributes) { final Object o = this.attributes.get(this.currentAttribute); if (o == null) { this.attributes.put(this.currentAttribute, this.value.toString()); } else { final List items; if (o instanceof List) { items = (List) o; } else { items = new LinkedList(); items.add(o); this.attributes.put(this.currentAttribute, items); } items.add(this.value.toString()); } } } ",FALSE,Cas20ServiceTicketValidator.java " public Map getAttributes() { return this.attributes; } "," public Map getAttributes() { return this.attributes; } ",FALSE,Cas20ServiceTicketValidator.java " public Cas10TicketValidatorTests() { super(); } "," public Cas10TicketValidatorTests() { super(); } ",FALSE,Cas10TicketValidatorTests.java " public void setUp() throws Exception { this.ticketValidator = new Cas10TicketValidator(CONST_CAS_SERVER_URL_PREFIX + ""8090""); } "," public void setUp() throws Exception { this.ticketValidator = new Cas10TicketValidator(CONST_CAS_SERVER_URL_PREFIX + ""8090""); } ",FALSE,Cas10TicketValidatorTests.java " public void testNoResponse() throws Exception { server.content = ""no\n\n"".getBytes(server.encoding); try { this.ticketValidator.validate(""testTicket"", ""myService""); fail(""ValidationException expected.""); } catch (final TicketValidationException e) { // expected } } "," public void testNoResponse() throws Exception { server.content = ""no\n\n"".getBytes(server.encoding); try { this.ticketValidator.validate(""testTicket"", ""myService""); fail(""ValidationException expected.""); } catch (final TicketValidationException e) { // expected } } ",FALSE,Cas10TicketValidatorTests.java " public void testYesResponse() throws TicketValidationException, UnsupportedEncodingException { server.content = ""yes\nusername\n\n"".getBytes(server.encoding); final Assertion assertion = this.ticketValidator.validate(""testTicket"", ""myService""); assertEquals(CONST_USERNAME, assertion.getPrincipal().getName()); } "," public void testYesResponse() throws TicketValidationException, UnsupportedEncodingException { server.content = ""yes\nusername\n\n"".getBytes(server.encoding); final Assertion assertion = this.ticketValidator.validate(""testTicket"", ""myService""); assertEquals(CONST_USERNAME, assertion.getPrincipal().getName()); } ",FALSE,Cas10TicketValidatorTests.java " public void testBadResponse() throws UnsupportedEncodingException { server.content = ""falalala\n\n"".getBytes(server.encoding); try { this.ticketValidator.validate(""testTicket"", ""myService""); fail(""ValidationException expected.""); } catch (final TicketValidationException e) { // expected } } "," public void testBadResponse() throws UnsupportedEncodingException { server.content = ""falalala\n\n"".getBytes(server.encoding); try { this.ticketValidator.validate(""testTicket"", ""myService""); fail(""ValidationException expected.""); } catch (final TicketValidationException e) { // expected } } ",FALSE,Cas10TicketValidatorTests.java " } "," public void urlEncodedValues() { final String ticket = ""ST-1-owKEOtYJjg77iHcCQpkl-cas01.example.org%26%73%65%72%76%69%63%65%3d%68%74%74%70%25%33%41%25%32%46%25%32%46%31%32%37%2e%30%2e%30%2e%31%25%32%46%62%6f%72%69%6e%67%25%32%46%23""; final String service = ""foobar""; final String url = this.ticketValidator.constructValidationUrl(ticket, service); final String encodedValue = this.ticketValidator.encodeUrl(ticket); assertTrue(url.contains(encodedValue)); assertFalse(url.contains(ticket)); } ",TRUE,Cas10TicketValidatorTests.java " public static final boolean isMultipartContent(RequestContext ctx) { String contentType = ctx.getContentType(); if (contentType == null) { return false; } if (contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) { return true; } return false; } "," public static final boolean isMultipartContent(RequestContext ctx) { String contentType = ctx.getContentType(); if (contentType == null) { return false; } if (contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART)) { return true; } return false; } ",FALSE,FileUploadBase.java " public static boolean isMultipartContent(HttpServletRequest req) { return ServletFileUpload.isMultipartContent(req); } "," public static boolean isMultipartContent(HttpServletRequest req) { return ServletFileUpload.isMultipartContent(req); } ",FALSE,FileUploadBase.java " public long getSizeMax() { return sizeMax; } "," public long getSizeMax() { return sizeMax; } ",FALSE,FileUploadBase.java " public void setSizeMax(long sizeMax) { this.sizeMax = sizeMax; } "," public void setSizeMax(long sizeMax) { this.sizeMax = sizeMax; } ",FALSE,FileUploadBase.java " public long getFileSizeMax() { return fileSizeMax; } "," public long getFileSizeMax() { return fileSizeMax; } ",FALSE,FileUploadBase.java " public void setFileSizeMax(long fileSizeMax) { this.fileSizeMax = fileSizeMax; } "," public void setFileSizeMax(long fileSizeMax) { this.fileSizeMax = fileSizeMax; } ",FALSE,FileUploadBase.java " public String getHeaderEncoding() { return headerEncoding; } "," public String getHeaderEncoding() { return headerEncoding; } ",FALSE,FileUploadBase.java " public void setHeaderEncoding(String encoding) { headerEncoding = encoding; } "," public void setHeaderEncoding(String encoding) { headerEncoding = encoding; } ",FALSE,FileUploadBase.java " public List parseRequest(HttpServletRequest req) throws FileUploadException { return parseRequest(new ServletRequestContext(req)); } "," public List parseRequest(HttpServletRequest req) throws FileUploadException { return parseRequest(new ServletRequestContext(req)); } ",FALSE,FileUploadBase.java " public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { try { return new FileItemIteratorImpl(ctx); } catch (FileUploadIOException e) { // unwrap encapsulated SizeException throw (FileUploadException) e.getCause(); } } "," public FileItemIterator getItemIterator(RequestContext ctx) throws FileUploadException, IOException { try { return new FileItemIteratorImpl(ctx); } catch (FileUploadIOException e) { // unwrap encapsulated SizeException throw (FileUploadException) e.getCause(); } } ",FALSE,FileUploadBase.java " public List parseRequest(RequestContext ctx) throws FileUploadException { List items = new ArrayList(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException(""No FileItemFactory has been set.""); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException(format(""Processing of %s request failed. %s"", MULTIPART_FORM_DATA, e.getMessage()), e); } final FileItemHeaders fih = item.getHeaders(); fileItem.setHeaders(fih); } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (FileItem fileItem : items) { try { fileItem.delete(); } catch (Throwable e) { // ignore it } } } } } "," public List parseRequest(RequestContext ctx) throws FileUploadException { List items = new ArrayList(); boolean successful = false; try { FileItemIterator iter = getItemIterator(ctx); FileItemFactory fac = getFileItemFactory(); if (fac == null) { throw new NullPointerException(""No FileItemFactory has been set.""); } while (iter.hasNext()) { final FileItemStream item = iter.next(); // Don't use getName() here to prevent an InvalidFileNameException. final String fileName = ((FileItemIteratorImpl.FileItemStreamImpl) item).name; FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName); items.add(fileItem); try { Streams.copy(item.openStream(), fileItem.getOutputStream(), true); } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new IOFileUploadException(format(""Processing of %s request failed. %s"", MULTIPART_FORM_DATA, e.getMessage()), e); } final FileItemHeaders fih = item.getHeaders(); fileItem.setHeaders(fih); } successful = true; return items; } catch (FileUploadIOException e) { throw (FileUploadException) e.getCause(); } catch (IOException e) { throw new FileUploadException(e.getMessage(), e); } finally { if (!successful) { for (FileItem fileItem : items) { try { fileItem.delete(); } catch (Throwable e) { // ignore it } } } } } ",FALSE,FileUploadBase.java " public Map> parseParameterMap(RequestContext ctx) throws FileUploadException { final List items = parseRequest(ctx); final Map> itemsMap = new HashMap>(items.size()); for (FileItem fileItem : items) { String fieldName = fileItem.getFieldName(); List mappedItems = itemsMap.get(fieldName); if (mappedItems == null) { mappedItems = new ArrayList(); itemsMap.put(fieldName, mappedItems); } mappedItems.add(fileItem); } return itemsMap; } "," public Map> parseParameterMap(RequestContext ctx) throws FileUploadException { final List items = parseRequest(ctx); final Map> itemsMap = new HashMap>(items.size()); for (FileItem fileItem : items) { String fieldName = fileItem.getFieldName(); List mappedItems = itemsMap.get(fieldName); if (mappedItems == null) { mappedItems = new ArrayList(); itemsMap.put(fieldName, mappedItems); } mappedItems.add(fileItem); } return itemsMap; } ",FALSE,FileUploadBase.java " protected byte[] getBoundary(String contentType) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(contentType, new char[] {';', ','}); String boundaryStr = params.get(""boundary""); if (boundaryStr == null) { return null; } byte[] boundary; try { boundary = boundaryStr.getBytes(""ISO-8859-1""); } catch (UnsupportedEncodingException e) { boundary = boundaryStr.getBytes(); // Intentionally falls back to default charset } return boundary; } "," protected byte[] getBoundary(String contentType) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(contentType, new char[] {';', ','}); String boundaryStr = params.get(""boundary""); if (boundaryStr == null) { return null; } byte[] boundary; try { boundary = boundaryStr.getBytes(""ISO-8859-1""); } catch (UnsupportedEncodingException e) { boundary = boundaryStr.getBytes(); // Intentionally falls back to default charset } return boundary; } ",FALSE,FileUploadBase.java " protected String getFileName(Map headers) { return getFileName(getHeader(headers, CONTENT_DISPOSITION)); } "," protected String getFileName(Map headers) { return getFileName(getHeader(headers, CONTENT_DISPOSITION)); } ",FALSE,FileUploadBase.java " protected String getFileName(FileItemHeaders headers) { return getFileName(headers.getHeader(CONTENT_DISPOSITION)); } "," protected String getFileName(FileItemHeaders headers) { return getFileName(headers.getHeader(CONTENT_DISPOSITION)); } ",FALSE,FileUploadBase.java " private String getFileName(String pContentDisposition) { String fileName = null; if (pContentDisposition != null) { String cdl = pContentDisposition.toLowerCase(Locale.ENGLISH); if (cdl.startsWith(FORM_DATA) || cdl.startsWith(ATTACHMENT)) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(pContentDisposition, ';'); if (params.containsKey(""filename"")) { fileName = params.get(""filename""); if (fileName != null) { fileName = fileName.trim(); } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. fileName = """"; } } } } return fileName; } "," private String getFileName(String pContentDisposition) { String fileName = null; if (pContentDisposition != null) { String cdl = pContentDisposition.toLowerCase(Locale.ENGLISH); if (cdl.startsWith(FORM_DATA) || cdl.startsWith(ATTACHMENT)) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(pContentDisposition, ';'); if (params.containsKey(""filename"")) { fileName = params.get(""filename""); if (fileName != null) { fileName = fileName.trim(); } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. fileName = """"; } } } } return fileName; } ",FALSE,FileUploadBase.java " protected String getFieldName(FileItemHeaders headers) { return getFieldName(headers.getHeader(CONTENT_DISPOSITION)); } "," protected String getFieldName(FileItemHeaders headers) { return getFieldName(headers.getHeader(CONTENT_DISPOSITION)); } ",FALSE,FileUploadBase.java " private String getFieldName(String pContentDisposition) { String fieldName = null; if (pContentDisposition != null && pContentDisposition.toLowerCase(Locale.ENGLISH).startsWith(FORM_DATA)) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(pContentDisposition, ';'); fieldName = params.get(""name""); if (fieldName != null) { fieldName = fieldName.trim(); } } return fieldName; } "," private String getFieldName(String pContentDisposition) { String fieldName = null; if (pContentDisposition != null && pContentDisposition.toLowerCase(Locale.ENGLISH).startsWith(FORM_DATA)) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map params = parser.parse(pContentDisposition, ';'); fieldName = params.get(""name""); if (fieldName != null) { fieldName = fieldName.trim(); } } return fieldName; } ",FALSE,FileUploadBase.java " protected String getFieldName(Map headers) { return getFieldName(getHeader(headers, CONTENT_DISPOSITION)); } "," protected String getFieldName(Map headers) { return getFieldName(getHeader(headers, CONTENT_DISPOSITION)); } ",FALSE,FileUploadBase.java " protected FileItem createItem(Map headers, boolean isFormField) throws FileUploadException { return getFileItemFactory().createItem(getFieldName(headers), getHeader(headers, CONTENT_TYPE), isFormField, getFileName(headers)); } "," protected FileItem createItem(Map headers, boolean isFormField) throws FileUploadException { return getFileItemFactory().createItem(getFieldName(headers), getHeader(headers, CONTENT_TYPE), isFormField, getFileName(headers)); } ",FALSE,FileUploadBase.java " protected FileItemHeaders getParsedHeaders(String headerPart) { final int len = headerPart.length(); FileItemHeadersImpl headers = newFileItemHeaders(); int start = 0; for (;;) { int end = parseEndOfLine(headerPart, start); if (start == end) { break; } StringBuilder header = new StringBuilder(headerPart.substring(start, end)); start = end + 2; while (start < len) { int nonWs = start; while (nonWs < len) { char c = headerPart.charAt(nonWs); if (c != ' ' && c != '\t') { break; } ++nonWs; } if (nonWs == start) { break; } // Continuation line found end = parseEndOfLine(headerPart, nonWs); header.append("" "").append(headerPart.substring(nonWs, end)); start = end + 2; } parseHeaderLine(headers, header.toString()); } return headers; } "," protected FileItemHeaders getParsedHeaders(String headerPart) { final int len = headerPart.length(); FileItemHeadersImpl headers = newFileItemHeaders(); int start = 0; for (;;) { int end = parseEndOfLine(headerPart, start); if (start == end) { break; } StringBuilder header = new StringBuilder(headerPart.substring(start, end)); start = end + 2; while (start < len) { int nonWs = start; while (nonWs < len) { char c = headerPart.charAt(nonWs); if (c != ' ' && c != '\t') { break; } ++nonWs; } if (nonWs == start) { break; } // Continuation line found end = parseEndOfLine(headerPart, nonWs); header.append("" "").append(headerPart.substring(nonWs, end)); start = end + 2; } parseHeaderLine(headers, header.toString()); } return headers; } ",FALSE,FileUploadBase.java " protected FileItemHeadersImpl newFileItemHeaders() { return new FileItemHeadersImpl(); } "," protected FileItemHeadersImpl newFileItemHeaders() { return new FileItemHeadersImpl(); } ",FALSE,FileUploadBase.java " protected Map parseHeaders(String headerPart) { FileItemHeaders headers = getParsedHeaders(headerPart); Map result = new HashMap(); for (Iterator iter = headers.getHeaderNames(); iter.hasNext();) { String headerName = iter.next(); Iterator iter2 = headers.getHeaders(headerName); StringBuilder headerValue = new StringBuilder(iter2.next()); while (iter2.hasNext()) { headerValue.append("","").append(iter2.next()); } result.put(headerName, headerValue.toString()); } return result; } "," protected Map parseHeaders(String headerPart) { FileItemHeaders headers = getParsedHeaders(headerPart); Map result = new HashMap(); for (Iterator iter = headers.getHeaderNames(); iter.hasNext();) { String headerName = iter.next(); Iterator iter2 = headers.getHeaders(headerName); StringBuilder headerValue = new StringBuilder(iter2.next()); while (iter2.hasNext()) { headerValue.append("","").append(iter2.next()); } result.put(headerName, headerValue.toString()); } return result; } ",FALSE,FileUploadBase.java " private int parseEndOfLine(String headerPart, int end) { int index = end; for (;;) { int offset = headerPart.indexOf('\r', index); if (offset == -1 || offset + 1 >= headerPart.length()) { throw new IllegalStateException( ""Expected headers to be terminated by an empty line.""); } if (headerPart.charAt(offset + 1) == '\n') { return offset; } index = offset + 1; } } "," private int parseEndOfLine(String headerPart, int end) { int index = end; for (;;) { int offset = headerPart.indexOf('\r', index); if (offset == -1 || offset + 1 >= headerPart.length()) { throw new IllegalStateException( ""Expected headers to be terminated by an empty line.""); } if (headerPart.charAt(offset + 1) == '\n') { return offset; } index = offset + 1; } } ",FALSE,FileUploadBase.java " private void parseHeaderLine(FileItemHeadersImpl headers, String header) { final int colonOffset = header.indexOf(':'); if (colonOffset == -1) { // This header line is malformed, skip it. return; } String headerName = header.substring(0, colonOffset).trim(); String headerValue = header.substring(header.indexOf(':') + 1).trim(); headers.addHeader(headerName, headerValue); } "," private void parseHeaderLine(FileItemHeadersImpl headers, String header) { final int colonOffset = header.indexOf(':'); if (colonOffset == -1) { // This header line is malformed, skip it. return; } String headerName = header.substring(0, colonOffset).trim(); String headerValue = header.substring(header.indexOf(':') + 1).trim(); headers.addHeader(headerName, headerValue); } ",FALSE,FileUploadBase.java " protected final String getHeader(Map headers, String name) { return headers.get(name.toLowerCase(Locale.ENGLISH)); } "," protected final String getHeader(Map headers, String name) { return headers.get(name.toLowerCase(Locale.ENGLISH)); } ",FALSE,FileUploadBase.java " FileItemStreamImpl(String pName, String pFieldName, String pContentType, boolean pFormField, long pContentLength) throws IOException { name = pName; fieldName = pFieldName; contentType = pContentType; formField = pFormField; final ItemInputStream itemStream = multi.newInputStream(); InputStream istream = itemStream; if (fileSizeMax != -1) { if (pContentLength != -1 && pContentLength > fileSizeMax) { FileSizeLimitExceededException e = new FileSizeLimitExceededException( format(""The field %s exceeds its maximum permitted size of %s bytes."", fieldName, Long.valueOf(fileSizeMax)), pContentLength, fileSizeMax); e.setFileName(pName); e.setFieldName(pFieldName); throw new FileUploadIOException(e); } istream = new LimitedInputStream(istream, fileSizeMax) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { itemStream.close(true); FileSizeLimitExceededException e = new FileSizeLimitExceededException( format(""The field %s exceeds its maximum permitted size of %s bytes."", fieldName, Long.valueOf(pSizeMax)), pCount, pSizeMax); e.setFieldName(fieldName); e.setFileName(name); throw new FileUploadIOException(e); } }; } stream = istream; } "," FileItemStreamImpl(String pName, String pFieldName, String pContentType, boolean pFormField, long pContentLength) throws IOException { name = pName; fieldName = pFieldName; contentType = pContentType; formField = pFormField; final ItemInputStream itemStream = multi.newInputStream(); InputStream istream = itemStream; if (fileSizeMax != -1) { if (pContentLength != -1 && pContentLength > fileSizeMax) { FileSizeLimitExceededException e = new FileSizeLimitExceededException( format(""The field %s exceeds its maximum permitted size of %s bytes."", fieldName, Long.valueOf(fileSizeMax)), pContentLength, fileSizeMax); e.setFileName(pName); e.setFieldName(pFieldName); throw new FileUploadIOException(e); } istream = new LimitedInputStream(istream, fileSizeMax) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { itemStream.close(true); FileSizeLimitExceededException e = new FileSizeLimitExceededException( format(""The field %s exceeds its maximum permitted size of %s bytes."", fieldName, Long.valueOf(pSizeMax)), pCount, pSizeMax); e.setFieldName(fieldName); e.setFileName(name); throw new FileUploadIOException(e); } }; } stream = istream; } ",FALSE,FileUploadBase.java " public String getContentType() { return contentType; } "," public String getContentType() { return contentType; } ",FALSE,FileUploadBase.java " public String getFieldName() { return fieldName; } "," public String getFieldName() { return fieldName; } ",FALSE,FileUploadBase.java " public String getName() { return Streams.checkFileName(name); } "," public String getName() { return Streams.checkFileName(name); } ",FALSE,FileUploadBase.java " public boolean isFormField() { return formField; } "," public boolean isFormField() { return formField; } ",FALSE,FileUploadBase.java " public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( ""The stream was already opened.""); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; } "," public InputStream openStream() throws IOException { if (opened) { throw new IllegalStateException( ""The stream was already opened.""); } if (((Closeable) stream).isClosed()) { throw new FileItemStream.ItemSkippedException(); } return stream; } ",FALSE,FileUploadBase.java " void close() throws IOException { stream.close(); } "," void close() throws IOException { stream.close(); } ",FALSE,FileUploadBase.java " public FileItemHeaders getHeaders() { return headers; } "," public FileItemHeaders getHeaders() { return headers; } ",FALSE,FileUploadBase.java " public void setHeaders(FileItemHeaders pHeaders) { headers = pHeaders; } "," public void setHeaders(FileItemHeaders pHeaders) { headers = pHeaders; } ",FALSE,FileUploadBase.java " FileItemIteratorImpl(RequestContext ctx) throws FileUploadException, IOException { if (ctx == null) { throw new NullPointerException(""ctx parameter""); } String contentType = ctx.getContentType(); if ((null == contentType) || (!contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART))) { throw new InvalidContentTypeException( format(""the request doesn't contain a %s or %s stream, content type header is %s"", MULTIPART_FORM_DATA, MULTIPART_FORM_DATA, contentType)); } InputStream input = ctx.getInputStream(); @SuppressWarnings(""deprecation"") // still has to be backward compatible final int contentLengthInt = ctx.getContentLength(); final long requestSize = UploadContext.class.isAssignableFrom(ctx.getClass()) // Inline conditional is OK here CHECKSTYLE:OFF ? ((UploadContext) ctx).contentLength() : contentLengthInt; // CHECKSTYLE:ON if (sizeMax >= 0) { if (requestSize != -1 && requestSize > sizeMax) { throw new SizeLimitExceededException( format(""the request was rejected because its size (%s) exceeds the configured maximum (%s)"", Long.valueOf(requestSize), Long.valueOf(sizeMax)), requestSize, sizeMax); } input = new LimitedInputStream(input, sizeMax) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { FileUploadException ex = new SizeLimitExceededException( format(""the request was rejected because its size (%s) exceeds the configured maximum (%s)"", Long.valueOf(pCount), Long.valueOf(pSizeMax)), pCount, pSizeMax); throw new FileUploadIOException(ex); } }; } String charEncoding = headerEncoding; if (charEncoding == null) { charEncoding = ctx.getCharacterEncoding(); } boundary = getBoundary(contentType); if (boundary == null) { throw new FileUploadException(""the request was rejected because no multipart boundary was found""); } notifier = new MultipartStream.ProgressNotifier(listener, requestSize); multi = new MultipartStream(input, boundary, notifier); multi.setHeaderEncoding(charEncoding); skipPreamble = true; findNextItem(); } "," FileItemIteratorImpl(RequestContext ctx) throws FileUploadException, IOException { if (ctx == null) { throw new NullPointerException(""ctx parameter""); } String contentType = ctx.getContentType(); if ((null == contentType) || (!contentType.toLowerCase(Locale.ENGLISH).startsWith(MULTIPART))) { throw new InvalidContentTypeException( format(""the request doesn't contain a %s or %s stream, content type header is %s"", MULTIPART_FORM_DATA, MULTIPART_FORM_DATA, contentType)); } InputStream input = ctx.getInputStream(); @SuppressWarnings(""deprecation"") // still has to be backward compatible final int contentLengthInt = ctx.getContentLength(); final long requestSize = UploadContext.class.isAssignableFrom(ctx.getClass()) // Inline conditional is OK here CHECKSTYLE:OFF ? ((UploadContext) ctx).contentLength() : contentLengthInt; // CHECKSTYLE:ON if (sizeMax >= 0) { if (requestSize != -1 && requestSize > sizeMax) { throw new SizeLimitExceededException( format(""the request was rejected because its size (%s) exceeds the configured maximum (%s)"", Long.valueOf(requestSize), Long.valueOf(sizeMax)), requestSize, sizeMax); } input = new LimitedInputStream(input, sizeMax) { @Override protected void raiseError(long pSizeMax, long pCount) throws IOException { FileUploadException ex = new SizeLimitExceededException( format(""the request was rejected because its size (%s) exceeds the configured maximum (%s)"", Long.valueOf(pCount), Long.valueOf(pSizeMax)), pCount, pSizeMax); throw new FileUploadIOException(ex); } }; } String charEncoding = headerEncoding; if (charEncoding == null) { charEncoding = ctx.getCharacterEncoding(); } boundary = getBoundary(contentType); if (boundary == null) { throw new FileUploadException(""the request was rejected because no multipart boundary was found""); } notifier = new MultipartStream.ProgressNotifier(listener, requestSize); try { multi = new MultipartStream(input, boundary, notifier); } catch (IllegalArgumentException iae) { throw new InvalidContentTypeException( format(""The boundary specified in the %s header is too long"", CONTENT_TYPE), iae); } multi.setHeaderEncoding(charEncoding); skipPreamble = true; findNextItem(); } ",TRUE,FileUploadBase.java " private boolean findNextItem() throws IOException { if (eof) { return false; } if (currentItem != null) { currentItem.close(); currentItem = null; } for (;;) { boolean nextPart; if (skipPreamble) { nextPart = multi.skipPreamble(); } else { nextPart = multi.readBoundary(); } if (!nextPart) { if (currentFieldName == null) { // Outer multipart terminated -> No more data eof = true; return false; } // Inner multipart terminated -> Return to parsing the outer multi.setBoundary(boundary); currentFieldName = null; continue; } FileItemHeaders headers = getParsedHeaders(multi.readHeaders()); if (currentFieldName == null) { // We're parsing the outer multipart String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = headers.getHeader(CONTENT_TYPE); if (subContentType != null && subContentType.toLowerCase(Locale.ENGLISH) .startsWith(MULTIPART_MIXED)) { currentFieldName = fieldName; // Multiple files associated with this field name byte[] subBoundary = getBoundary(subContentType); multi.setBoundary(subBoundary); skipPreamble = true; continue; } String fileName = getFileName(headers); currentItem = new FileItemStreamImpl(fileName, fieldName, headers.getHeader(CONTENT_TYPE), fileName == null, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } else { String fileName = getFileName(headers); if (fileName != null) { currentItem = new FileItemStreamImpl(fileName, currentFieldName, headers.getHeader(CONTENT_TYPE), false, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } multi.discardBodyData(); } } "," private boolean findNextItem() throws IOException { if (eof) { return false; } if (currentItem != null) { currentItem.close(); currentItem = null; } for (;;) { boolean nextPart; if (skipPreamble) { nextPart = multi.skipPreamble(); } else { nextPart = multi.readBoundary(); } if (!nextPart) { if (currentFieldName == null) { // Outer multipart terminated -> No more data eof = true; return false; } // Inner multipart terminated -> Return to parsing the outer multi.setBoundary(boundary); currentFieldName = null; continue; } FileItemHeaders headers = getParsedHeaders(multi.readHeaders()); if (currentFieldName == null) { // We're parsing the outer multipart String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = headers.getHeader(CONTENT_TYPE); if (subContentType != null && subContentType.toLowerCase(Locale.ENGLISH) .startsWith(MULTIPART_MIXED)) { currentFieldName = fieldName; // Multiple files associated with this field name byte[] subBoundary = getBoundary(subContentType); multi.setBoundary(subBoundary); skipPreamble = true; continue; } String fileName = getFileName(headers); currentItem = new FileItemStreamImpl(fileName, fieldName, headers.getHeader(CONTENT_TYPE), fileName == null, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } else { String fileName = getFileName(headers); if (fileName != null) { currentItem = new FileItemStreamImpl(fileName, currentFieldName, headers.getHeader(CONTENT_TYPE), false, getContentLength(headers)); currentItem.setHeaders(headers); notifier.noteItem(); itemValid = true; return true; } } multi.discardBodyData(); } } ",FALSE,FileUploadBase.java " private long getContentLength(FileItemHeaders pHeaders) { try { return Long.parseLong(pHeaders.getHeader(CONTENT_LENGTH)); } catch (Exception e) { return -1; } } "," private long getContentLength(FileItemHeaders pHeaders) { try { return Long.parseLong(pHeaders.getHeader(CONTENT_LENGTH)); } catch (Exception e) { return -1; } } ",FALSE,FileUploadBase.java " public boolean hasNext() throws FileUploadException, IOException { if (eof) { return false; } if (itemValid) { return true; } try { return findNextItem(); } catch (FileUploadIOException e) { // unwrap encapsulated SizeException throw (FileUploadException) e.getCause(); } } "," public boolean hasNext() throws FileUploadException, IOException { if (eof) { return false; } if (itemValid) { return true; } try { return findNextItem(); } catch (FileUploadIOException e) { // unwrap encapsulated SizeException throw (FileUploadException) e.getCause(); } } ",FALSE,FileUploadBase.java " public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; } "," public FileItemStream next() throws FileUploadException, IOException { if (eof || (!itemValid && !hasNext())) { throw new NoSuchElementException(); } itemValid = false; return currentItem; } ",FALSE,FileUploadBase.java " public FileUploadIOException(FileUploadException pCause) { // We're not doing super(pCause) cause of 1.3 compatibility. cause = pCause; } "," public FileUploadIOException(FileUploadException pCause) { // We're not doing super(pCause) cause of 1.3 compatibility. cause = pCause; } ",FALSE,FileUploadBase.java " public Throwable getCause() { return cause; } "," public Throwable getCause() { return cause; } ",FALSE,FileUploadBase.java " public InvalidContentTypeException() { // Nothing to do. } "," public InvalidContentTypeException() { super(); } ",TRUE,FileUploadBase.java " public InvalidContentTypeException(String message) { super(message); } "," public InvalidContentTypeException(String message) { super(message); } ",FALSE,FileUploadBase.java " "," public InvalidContentTypeException(String msg, Throwable cause) { super(msg, cause); } ",TRUE,FileUploadBase.java " public IOFileUploadException(String pMsg, IOException pException) { super(pMsg); cause = pException; } "," public IOFileUploadException(String pMsg, IOException pException) { super(pMsg); cause = pException; } ",FALSE,FileUploadBase.java " public Throwable getCause() { return cause; } "," public Throwable getCause() { return cause; } ",FALSE,FileUploadBase.java " protected SizeException(String message, long actual, long permitted) { super(message); this.actual = actual; this.permitted = permitted; } "," protected SizeException(String message, long actual, long permitted) { super(message); this.actual = actual; this.permitted = permitted; } ",FALSE,FileUploadBase.java " public long getActualSize() { return actual; } "," public long getActualSize() { return actual; } ",FALSE,FileUploadBase.java " public long getPermittedSize() { return permitted; } "," public long getPermittedSize() { return permitted; } ",FALSE,FileUploadBase.java " public UnknownSizeException() { super(); } "," public UnknownSizeException() { super(); } ",FALSE,FileUploadBase.java " public UnknownSizeException(String message) { super(message); } "," public UnknownSizeException(String message) { super(message); } ",FALSE,FileUploadBase.java " public SizeLimitExceededException() { this(null, 0, 0); } "," public SizeLimitExceededException() { this(null, 0, 0); } ",FALSE,FileUploadBase.java " public SizeLimitExceededException(String message) { this(message, 0, 0); } "," public SizeLimitExceededException(String message) { this(message, 0, 0); } ",FALSE,FileUploadBase.java " public SizeLimitExceededException(String message, long actual, long permitted) { super(message, actual, permitted); } "," public SizeLimitExceededException(String message, long actual, long permitted) { super(message, actual, permitted); } ",FALSE,FileUploadBase.java " public FileSizeLimitExceededException(String message, long actual, long permitted) { super(message, actual, permitted); } "," public FileSizeLimitExceededException(String message, long actual, long permitted) { super(message, actual, permitted); } ",FALSE,FileUploadBase.java " public String getFileName() { return fileName; } "," public String getFileName() { return fileName; } ",FALSE,FileUploadBase.java " public void setFileName(String pFileName) { fileName = pFileName; } "," public void setFileName(String pFileName) { fileName = pFileName; } ",FALSE,FileUploadBase.java " public String getFieldName() { return fieldName; } "," public String getFieldName() { return fieldName; } ",FALSE,FileUploadBase.java " public void setFieldName(String pFieldName) { fieldName = pFieldName; } "," public void setFieldName(String pFieldName) { fieldName = pFieldName; } ",FALSE,FileUploadBase.java " public ProgressListener getProgressListener() { return listener; } "," public ProgressListener getProgressListener() { return listener; } ",FALSE,FileUploadBase.java " public void setProgressListener(ProgressListener pListener) { listener = pListener; } "," public void setProgressListener(ProgressListener pListener) { listener = pListener; } ",FALSE,FileUploadBase.java " ProgressNotifier(ProgressListener pListener, long pContentLength) { listener = pListener; contentLength = pContentLength; } "," ProgressNotifier(ProgressListener pListener, long pContentLength) { listener = pListener; contentLength = pContentLength; } ",FALSE,MultipartStream.java " void noteBytesRead(int pBytes) { /* Indicates, that the given number of bytes have been read from * the input stream. */ bytesRead += pBytes; notifyListener(); } "," void noteBytesRead(int pBytes) { /* Indicates, that the given number of bytes have been read from * the input stream. */ bytesRead += pBytes; notifyListener(); } ",FALSE,MultipartStream.java " void noteItem() { ++items; notifyListener(); } "," void noteItem() { ++items; notifyListener(); } ",FALSE,MultipartStream.java " private void notifyListener() { if (listener != null) { listener.update(bytesRead, contentLength, items); } } "," private void notifyListener() { if (listener != null) { listener.update(bytesRead, contentLength, items); } } ",FALSE,MultipartStream.java " public MultipartStream() { this(null, null, null); } "," public MultipartStream() { this(null, null, null); } ",FALSE,MultipartStream.java " public MultipartStream(InputStream input, byte[] boundary, int bufSize) { this(input, boundary, bufSize, null); } "," public MultipartStream(InputStream input, byte[] boundary, int bufSize) { this(input, boundary, bufSize, null); } ",FALSE,MultipartStream.java " public MultipartStream(InputStream input, byte[] boundary, int bufSize, ProgressNotifier pNotifier) { this.input = input; this.bufSize = bufSize; this.buffer = new byte[bufSize]; this.notifier = pNotifier; // We prepend CR/LF to the boundary to chop trailing CR/LF from // body-data tokens. this.boundary = new byte[boundary.length + BOUNDARY_PREFIX.length]; this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length; this.keepRegion = this.boundary.length; System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length); System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); head = 0; tail = 0; } "," public MultipartStream(InputStream input, byte[] boundary, int bufSize, ProgressNotifier pNotifier) { this.input = input; this.bufSize = bufSize; this.buffer = new byte[bufSize]; this.notifier = pNotifier; // We prepend CR/LF to the boundary to chop trailing CR/LF from // body-data tokens. this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length; if (bufSize < this.boundaryLength + 1) { throw new IllegalArgumentException( ""The buffer size specified for the MultipartStream is too small""); } this.boundary = new byte[this.boundaryLength]; this.keepRegion = this.boundary.length; System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length); System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); head = 0; tail = 0; } ",TRUE,MultipartStream.java " MultipartStream(InputStream input, byte[] boundary, ProgressNotifier pNotifier) { this(input, boundary, DEFAULT_BUFSIZE, pNotifier); } "," MultipartStream(InputStream input, byte[] boundary, ProgressNotifier pNotifier) { this(input, boundary, DEFAULT_BUFSIZE, pNotifier); } ",FALSE,MultipartStream.java " public MultipartStream(InputStream input, byte[] boundary) { this(input, boundary, DEFAULT_BUFSIZE, null); } "," public MultipartStream(InputStream input, byte[] boundary) { this(input, boundary, DEFAULT_BUFSIZE, null); } ",FALSE,MultipartStream.java " public String getHeaderEncoding() { return headerEncoding; } "," public String getHeaderEncoding() { return headerEncoding; } ",FALSE,MultipartStream.java " public void setHeaderEncoding(String encoding) { headerEncoding = encoding; } "," public void setHeaderEncoding(String encoding) { headerEncoding = encoding; } ",FALSE,MultipartStream.java " public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException(""No more data is available""); } if (notifier != null) { notifier.noteBytesRead(tail); } } return buffer[head++]; } "," public byte readByte() throws IOException { // Buffer depleted ? if (head == tail) { head = 0; // Refill. tail = input.read(buffer, head, bufSize); if (tail == -1) { // No more data available. throw new IOException(""No more data is available""); } if (notifier != null) { notifier.noteBytesRead(tail); } } return buffer[head++]; } ",FALSE,MultipartStream.java " public boolean readBoundary() throws FileUploadIOException, MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( ""Unexpected characters follow a boundary""); } } catch (FileUploadIOException e) { // wraps a SizeException, re-throw as it will be unwrapped later throw e; } catch (IOException e) { throw new MalformedStreamException(""Stream ended unexpectedly""); } return nextChunk; } "," public boolean readBoundary() throws FileUploadIOException, MalformedStreamException { byte[] marker = new byte[2]; boolean nextChunk = false; head += boundaryLength; try { marker[0] = readByte(); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte(); if (arrayequals(marker, STREAM_TERMINATOR, 2)) { nextChunk = false; } else if (arrayequals(marker, FIELD_SEPARATOR, 2)) { nextChunk = true; } else { throw new MalformedStreamException( ""Unexpected characters follow a boundary""); } } catch (FileUploadIOException e) { // wraps a SizeException, re-throw as it will be unwrapped later throw e; } catch (IOException e) { throw new MalformedStreamException(""Stream ended unexpectedly""); } return nextChunk; } ",FALSE,MultipartStream.java " public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( ""The length of a boundary token can not be changed""); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); } "," public void setBoundary(byte[] boundary) throws IllegalBoundaryException { if (boundary.length != boundaryLength - BOUNDARY_PREFIX.length) { throw new IllegalBoundaryException( ""The length of a boundary token can not be changed""); } System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); } ",FALSE,MultipartStream.java " public String readHeaders() throws FileUploadIOException, MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (FileUploadIOException e) { // wraps a SizeException, re-throw as it will be unwrapped later throw e; } catch (IOException e) { throw new MalformedStreamException(""Stream ended unexpectedly""); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException( format(""Header section has more than %s bytes (maybe it is not properly terminated)"", Integer.valueOf(HEADER_PART_SIZE_MAX))); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; } "," public String readHeaders() throws FileUploadIOException, MalformedStreamException { int i = 0; byte b; // to support multi-byte characters ByteArrayOutputStream baos = new ByteArrayOutputStream(); int size = 0; while (i < HEADER_SEPARATOR.length) { try { b = readByte(); } catch (FileUploadIOException e) { // wraps a SizeException, re-throw as it will be unwrapped later throw e; } catch (IOException e) { throw new MalformedStreamException(""Stream ended unexpectedly""); } if (++size > HEADER_PART_SIZE_MAX) { throw new MalformedStreamException( format(""Header section has more than %s bytes (maybe it is not properly terminated)"", Integer.valueOf(HEADER_PART_SIZE_MAX))); } if (b == HEADER_SEPARATOR[i]) { i++; } else { i = 0; } baos.write(b); } String headers = null; if (headerEncoding != null) { try { headers = baos.toString(headerEncoding); } catch (UnsupportedEncodingException e) { // Fall back to platform default if specified encoding is not // supported. headers = baos.toString(); } } else { headers = baos.toString(); } return headers; } ",FALSE,MultipartStream.java " public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); } "," public int readBodyData(OutputStream output) throws MalformedStreamException, IOException { final InputStream istream = newInputStream(); return (int) Streams.copy(istream, output, false); } ",FALSE,MultipartStream.java " ItemInputStream newInputStream() { return new ItemInputStream(); } "," ItemInputStream newInputStream() { return new ItemInputStream(); } ",FALSE,MultipartStream.java " public int discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); } "," public int discardBodyData() throws MalformedStreamException, IOException { return readBodyData(null); } ",FALSE,MultipartStream.java " public boolean skipPreamble() throws IOException { // First delimiter may be not preceeded with a CRLF. System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2); boundaryLength = boundary.length - 2; try { // Discard all data up to the delimiter. discardBodyData(); // Read boundary - if succeeded, the stream contains an // encapsulation. return readBoundary(); } catch (MalformedStreamException e) { return false; } finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = CR; boundary[1] = LF; } } "," public boolean skipPreamble() throws IOException { // First delimiter may be not preceeded with a CRLF. System.arraycopy(boundary, 2, boundary, 0, boundary.length - 2); boundaryLength = boundary.length - 2; try { // Discard all data up to the delimiter. discardBodyData(); // Read boundary - if succeeded, the stream contains an // encapsulation. return readBoundary(); } catch (MalformedStreamException e) { return false; } finally { // Restore delimiter. System.arraycopy(boundary, 0, boundary, 2, boundary.length - 2); boundaryLength = boundary.length; boundary[0] = CR; boundary[1] = LF; } } ",FALSE,MultipartStream.java " public static boolean arrayequals(byte[] a, byte[] b, int count) { for (int i = 0; i < count; i++) { if (a[i] != b[i]) { return false; } } return true; } "," public static boolean arrayequals(byte[] a, byte[] b, int count) { for (int i = 0; i < count; i++) { if (a[i] != b[i]) { return false; } } return true; } ",FALSE,MultipartStream.java " protected int findByte(byte value, int pos) { for (int i = pos; i < tail; i++) { if (buffer[i] == value) { return i; } } return -1; } "," protected int findByte(byte value, int pos) { for (int i = pos; i < tail; i++) { if (buffer[i] == value) { return i; } } return -1; } ",FALSE,MultipartStream.java " protected int findSeparator() { int first; int match = 0; int maxpos = tail - boundaryLength; for (first = head; (first <= maxpos) && (match != boundaryLength); first++) { first = findByte(boundary[0], first); if (first == -1 || (first > maxpos)) { return -1; } for (match = 1; match < boundaryLength; match++) { if (buffer[first + match] != boundary[match]) { break; } } } if (match == boundaryLength) { return first - 1; } return -1; } "," protected int findSeparator() { int first; int match = 0; int maxpos = tail - boundaryLength; for (first = head; (first <= maxpos) && (match != boundaryLength); first++) { first = findByte(boundary[0], first); if (first == -1 || (first > maxpos)) { return -1; } for (match = 1; match < boundaryLength; match++) { if (buffer[first + match] != boundary[match]) { break; } } } if (match == boundaryLength) { return first - 1; } return -1; } ",FALSE,MultipartStream.java " public MalformedStreamException() { super(); } "," public MalformedStreamException() { super(); } ",FALSE,MultipartStream.java " public MalformedStreamException(String message) { super(message); } "," public MalformedStreamException(String message) { super(message); } ",FALSE,MultipartStream.java " public IllegalBoundaryException() { super(); } "," public IllegalBoundaryException() { super(); } ",FALSE,MultipartStream.java " public IllegalBoundaryException(String message) { super(message); } "," public IllegalBoundaryException(String message) { super(message); } ",FALSE,MultipartStream.java " ItemInputStream() { findSeparator(); } "," ItemInputStream() { findSeparator(); } ",FALSE,MultipartStream.java " private void findSeparator() { pos = MultipartStream.this.findSeparator(); if (pos == -1) { if (tail - head > keepRegion) { pad = keepRegion; } else { pad = tail - head; } } } "," private void findSeparator() { pos = MultipartStream.this.findSeparator(); if (pos == -1) { if (tail - head > keepRegion) { pad = keepRegion; } else { pad = tail - head; } } } ",FALSE,MultipartStream.java " public long getBytesRead() { return total; } "," public long getBytesRead() { return total; } ",FALSE,MultipartStream.java " public int available() throws IOException { if (pos == -1) { return tail - head - pad; } return pos - head; } "," public int available() throws IOException { if (pos == -1) { return tail - head - pad; } return pos - head; } ",FALSE,MultipartStream.java " public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0 && makeAvailable() == 0) { return -1; } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; } "," public int read() throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (available() == 0 && makeAvailable() == 0) { return -1; } ++total; int b = buffer[head++]; if (b >= 0) { return b; } return b + BYTE_POSITIVE_OFFSET; } ",FALSE,MultipartStream.java " public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; } "," public int read(byte[] b, int off, int len) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } if (len == 0) { return 0; } int res = available(); if (res == 0) { res = makeAvailable(); if (res == 0) { return -1; } } res = Math.min(res, len); System.arraycopy(buffer, head, b, off, res); head += res; total += res; return res; } ",FALSE,MultipartStream.java " public void close() throws IOException { close(false); } "," public void close() throws IOException { close(false); } ",FALSE,MultipartStream.java " public void close(boolean pCloseUnderlying) throws IOException { if (closed) { return; } if (pCloseUnderlying) { closed = true; input.close(); } else { for (;;) { int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { break; } } skip(av); } } closed = true; } "," public void close(boolean pCloseUnderlying) throws IOException { if (closed) { return; } if (pCloseUnderlying) { closed = true; input.close(); } else { for (;;) { int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { break; } } skip(av); } } closed = true; } ",FALSE,MultipartStream.java " public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; } "," public long skip(long bytes) throws IOException { if (closed) { throw new FileItemStream.ItemSkippedException(); } int av = available(); if (av == 0) { av = makeAvailable(); if (av == 0) { return 0; } } long res = Math.min(av, bytes); head += res; return res; } ",FALSE,MultipartStream.java " private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (;;) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = ""Stream ended unexpectedly""; throw new MalformedStreamException(msg); } if (notifier != null) { notifier.noteBytesRead(bytesRead); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } } "," private int makeAvailable() throws IOException { if (pos != -1) { return 0; } // Move the data to the beginning of the buffer. total += tail - head - pad; System.arraycopy(buffer, tail - pad, buffer, 0, pad); // Refill buffer with new data. head = 0; tail = pad; for (;;) { int bytesRead = input.read(buffer, tail, bufSize - tail); if (bytesRead == -1) { // The last pad amount is left in the buffer. // Boundary can't be in there so signal an error // condition. final String msg = ""Stream ended unexpectedly""; throw new MalformedStreamException(msg); } if (notifier != null) { notifier.noteBytesRead(bytesRead); } tail += bytesRead; findSeparator(); int av = available(); if (av > 0 || pos != -1) { return av; } } } ",FALSE,MultipartStream.java " public boolean isClosed() { return closed; } "," public boolean isClosed() { return closed; } ",FALSE,MultipartStream.java " public void testThreeParamConstructor() throws Exception { final String strData = ""foobar""; final byte[] contents = strData.getBytes(); InputStream input = new ByteArrayInputStream(contents); byte[] boundary = BOUNDARY_TEXT.getBytes(); int iBufSize = boundary.length; MultipartStream ms = new MultipartStream( input, boundary, iBufSize, new MultipartStream.ProgressNotifier(null, contents.length)); assertNotNull(ms); } "," public void testThreeParamConstructor() throws Exception { final String strData = ""foobar""; final byte[] contents = strData.getBytes(); InputStream input = new ByteArrayInputStream(contents); byte[] boundary = BOUNDARY_TEXT.getBytes(); int iBufSize = boundary.length + MultipartStream.BOUNDARY_PREFIX.length + 1; MultipartStream ms = new MultipartStream( input, boundary, iBufSize, new MultipartStream.ProgressNotifier(null, contents.length)); assertNotNull(ms); } ",TRUE,MultipartStreamTest.java " "," public void testSmallBuffer() throws Exception { final String strData = ""foobar""; final byte[] contents = strData.getBytes(); InputStream input = new ByteArrayInputStream(contents); byte[] boundary = BOUNDARY_TEXT.getBytes(); int iBufSize = 1; @SuppressWarnings(""unused"") MultipartStream ms = new MultipartStream( input, boundary, iBufSize, new MultipartStream.ProgressNotifier(null, contents.length)); } ",TRUE,MultipartStreamTest.java " public void testTwoParamConstructor() throws Exception { final String strData = ""foobar""; final byte[] contents = strData.getBytes(); InputStream input = new ByteArrayInputStream(contents); byte[] boundary = BOUNDARY_TEXT.getBytes(); MultipartStream ms = new MultipartStream( input, boundary, new MultipartStream.ProgressNotifier(null, contents.length)); assertNotNull(ms); } "," public void testTwoParamConstructor() throws Exception { final String strData = ""foobar""; final byte[] contents = strData.getBytes(); InputStream input = new ByteArrayInputStream(contents); byte[] boundary = BOUNDARY_TEXT.getBytes(); MultipartStream ms = new MultipartStream( input, boundary, new MultipartStream.ProgressNotifier(null, contents.length)); assertNotNull(ms); } ",FALSE,MultipartStreamTest.java " public AbstractUnArchiver() { // no op } "," public AbstractUnArchiver() { // no op } ",FALSE,AbstractUnArchiver.java " public AbstractUnArchiver( final File sourceFile ) { this.sourceFile = sourceFile; } "," public AbstractUnArchiver( final File sourceFile ) { this.sourceFile = sourceFile; } ",FALSE,AbstractUnArchiver.java " public File getDestDirectory() { return destDirectory; } "," public File getDestDirectory() { return destDirectory; } ",FALSE,AbstractUnArchiver.java " public void setDestDirectory( final File destDirectory ) { this.destDirectory = destDirectory; } "," public void setDestDirectory( final File destDirectory ) { this.destDirectory = destDirectory; } ",FALSE,AbstractUnArchiver.java " public File getDestFile() { return destFile; } "," public File getDestFile() { return destFile; } ",FALSE,AbstractUnArchiver.java " public void setDestFile( final File destFile ) { this.destFile = destFile; } "," public void setDestFile( final File destFile ) { this.destFile = destFile; } ",FALSE,AbstractUnArchiver.java " public File getSourceFile() { return sourceFile; } "," public File getSourceFile() { return sourceFile; } ",FALSE,AbstractUnArchiver.java " public void setSourceFile( final File sourceFile ) { this.sourceFile = sourceFile; } "," public void setSourceFile( final File sourceFile ) { this.sourceFile = sourceFile; } ",FALSE,AbstractUnArchiver.java " public boolean isOverwrite() { return overwrite; } "," public boolean isOverwrite() { return overwrite; } ",FALSE,AbstractUnArchiver.java " public void setOverwrite( final boolean b ) { overwrite = b; } "," public void setOverwrite( final boolean b ) { overwrite = b; } ",FALSE,AbstractUnArchiver.java " public final void extract() throws ArchiverException { validate(); execute(); runArchiveFinalizers(); } "," public final void extract() throws ArchiverException { validate(); execute(); runArchiveFinalizers(); } ",FALSE,AbstractUnArchiver.java " public final void extract( final String path, final File outputDirectory ) throws ArchiverException { validate( path, outputDirectory ); execute( path, outputDirectory ); runArchiveFinalizers(); } "," public final void extract( final String path, final File outputDirectory ) throws ArchiverException { validate( path, outputDirectory ); execute( path, outputDirectory ); runArchiveFinalizers(); } ",FALSE,AbstractUnArchiver.java " public void addArchiveFinalizer( final ArchiveFinalizer finalizer ) { if ( finalizers == null ) { finalizers = new ArrayList(); } finalizers.add( finalizer ); } "," public void addArchiveFinalizer( final ArchiveFinalizer finalizer ) { if ( finalizers == null ) { finalizers = new ArrayList(); } finalizers.add( finalizer ); } ",FALSE,AbstractUnArchiver.java " public void setArchiveFinalizers( final List archiveFinalizers ) { finalizers = archiveFinalizers; } "," public void setArchiveFinalizers( final List archiveFinalizers ) { finalizers = archiveFinalizers; } ",FALSE,AbstractUnArchiver.java " private void runArchiveFinalizers() throws ArchiverException { if ( finalizers != null ) { for ( Object finalizer1 : finalizers ) { final ArchiveFinalizer finalizer = (ArchiveFinalizer) finalizer1; finalizer.finalizeArchiveExtraction( this ); } } } "," private void runArchiveFinalizers() throws ArchiverException { if ( finalizers != null ) { for ( Object finalizer1 : finalizers ) { final ArchiveFinalizer finalizer = (ArchiveFinalizer) finalizer1; finalizer.finalizeArchiveExtraction( this ); } } } ",FALSE,AbstractUnArchiver.java " protected void validate( final String path, final File outputDirectory ) { } "," protected void validate( final String path, final File outputDirectory ) { } ",FALSE,AbstractUnArchiver.java " protected void validate() throws ArchiverException { if ( sourceFile == null ) { throw new ArchiverException( ""The source file isn't defined."" ); } if ( sourceFile.isDirectory() ) { throw new ArchiverException( ""The source must not be a directory."" ); } if ( !sourceFile.exists() ) { throw new ArchiverException( ""The source file "" + sourceFile + "" doesn't exist."" ); } if ( destDirectory == null && destFile == null ) { throw new ArchiverException( ""The destination isn't defined."" ); } if ( destDirectory != null && destFile != null ) { throw new ArchiverException( ""You must choose between a destination directory and a destination file."" ); } if ( destDirectory != null && !destDirectory.isDirectory() ) { destFile = destDirectory; destDirectory = null; } if ( destFile != null && destFile.isDirectory() ) { destDirectory = destFile; destFile = null; } } "," protected void validate() throws ArchiverException { if ( sourceFile == null ) { throw new ArchiverException( ""The source file isn't defined."" ); } if ( sourceFile.isDirectory() ) { throw new ArchiverException( ""The source must not be a directory."" ); } if ( !sourceFile.exists() ) { throw new ArchiverException( ""The source file "" + sourceFile + "" doesn't exist."" ); } if ( destDirectory == null && destFile == null ) { throw new ArchiverException( ""The destination isn't defined."" ); } if ( destDirectory != null && destFile != null ) { throw new ArchiverException( ""You must choose between a destination directory and a destination file."" ); } if ( destDirectory != null && !destDirectory.isDirectory() ) { destFile = destDirectory; destDirectory = null; } if ( destFile != null && destFile.isDirectory() ) { destDirectory = destFile; destFile = null; } } ",FALSE,AbstractUnArchiver.java " public void setFileSelectors( final FileSelector[] fileSelectors ) { this.fileSelectors = fileSelectors; } "," public void setFileSelectors( final FileSelector[] fileSelectors ) { this.fileSelectors = fileSelectors; } ",FALSE,AbstractUnArchiver.java " public FileSelector[] getFileSelectors() { return fileSelectors; } "," public FileSelector[] getFileSelectors() { return fileSelectors; } ",FALSE,AbstractUnArchiver.java " protected boolean isSelected( final String fileName, final PlexusIoResource fileInfo ) throws ArchiverException { if ( fileSelectors != null ) { for ( FileSelector fileSelector : fileSelectors ) { try { if ( !fileSelector.isSelected( fileInfo ) ) { return false; } } catch ( final IOException e ) { throw new ArchiverException( ""Failed to check, whether "" + fileInfo.getName() + "" is selected: "" + e.getMessage(), e ); } } } return true; } "," protected boolean isSelected( final String fileName, final PlexusIoResource fileInfo ) throws ArchiverException { if ( fileSelectors != null ) { for ( FileSelector fileSelector : fileSelectors ) { try { if ( !fileSelector.isSelected( fileInfo ) ) { return false; } } catch ( final IOException e ) { throw new ArchiverException( ""Failed to check, whether "" + fileInfo.getName() + "" is selected: "" + e.getMessage(), e ); } } } return true; } ",FALSE,AbstractUnArchiver.java " public boolean isUseJvmChmod() { return useJvmChmod; } "," public boolean isUseJvmChmod() { return useJvmChmod; } ",FALSE,AbstractUnArchiver.java " public void setUseJvmChmod( final boolean useJvmChmod ) { this.useJvmChmod = useJvmChmod; } "," public void setUseJvmChmod( final boolean useJvmChmod ) { this.useJvmChmod = useJvmChmod; } ",FALSE,AbstractUnArchiver.java " public boolean isIgnorePermissions() { return ignorePermissions; } "," public boolean isIgnorePermissions() { return ignorePermissions; } ",FALSE,AbstractUnArchiver.java " public void setIgnorePermissions( final boolean ignorePermissions ) { this.ignorePermissions = ignorePermissions; } "," public void setIgnorePermissions( final boolean ignorePermissions ) { this.ignorePermissions = ignorePermissions; } ",FALSE,AbstractUnArchiver.java " protected void extractFile( final File srcF, final File dir, final InputStream compressedInputStream, final String entryName, final Date entryDate, final boolean isDirectory, final Integer mode, String symlinkDestination ) throws IOException, ArchiverException { // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing... final File f = FileUtils.resolveFile( dir, entryName ); try { if ( !isOverwrite() && f.exists() && ( f.lastModified() >= entryDate.getTime() ) ) { return; } // create intermediary directories - sometimes zip don't add them final File dirF = f.getParentFile(); if ( dirF != null ) { dirF.mkdirs(); } if ( !StringUtils.isEmpty( symlinkDestination ) ) { SymlinkUtils.createSymbolicLink( f, new File( symlinkDestination ) ); } else if ( isDirectory ) { f.mkdirs(); } else { OutputStream out = null; try { out = new FileOutputStream( f ); IOUtil.copy( compressedInputStream, out ); out.close(); out = null; } finally { IOUtil.close( out ); } } f.setLastModified( entryDate.getTime() ); if ( !isIgnorePermissions() && mode != null && !isDirectory ) { ArchiveEntryUtils.chmod( f, mode ); } } catch ( final FileNotFoundException ex ) { getLogger().warn( ""Unable to expand to file "" + f.getPath() ); } } "," protected void extractFile( final File srcF, final File dir, final InputStream compressedInputStream, final String entryName, final Date entryDate, final boolean isDirectory, final Integer mode, String symlinkDestination ) throws IOException, ArchiverException { // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing... final File f = FileUtils.resolveFile( dir, entryName ); // Make sure that the resolved path of the extracted file doesn't escape the destination directory String canonicalDirPath = dir.getCanonicalPath(); String canonicalDestPath = f.getCanonicalPath(); if ( !canonicalDestPath.startsWith( canonicalDirPath ) ) { throw new ArchiverException( ""Entry is outside of the target directory ("" + entryName + "")"" ); } try { if ( !isOverwrite() && f.exists() && ( f.lastModified() >= entryDate.getTime() ) ) { return; } // create intermediary directories - sometimes zip don't add them final File dirF = f.getParentFile(); if ( dirF != null ) { dirF.mkdirs(); } if ( !StringUtils.isEmpty( symlinkDestination ) ) { SymlinkUtils.createSymbolicLink( f, new File( symlinkDestination ) ); } else if ( isDirectory ) { f.mkdirs(); } else { OutputStream out = null; try { out = new FileOutputStream( f ); IOUtil.copy( compressedInputStream, out ); out.close(); out = null; } finally { IOUtil.close( out ); } } f.setLastModified( entryDate.getTime() ); if ( !isIgnorePermissions() && mode != null && !isDirectory ) { ArchiveEntryUtils.chmod( f, mode ); } } catch ( final FileNotFoundException ex ) { getLogger().warn( ""Unable to expand to file "" + f.getPath() ); } } ",TRUE,AbstractUnArchiver.java " public void testExtractingZipPreservesExecutableFlag() throws Exception { String s = ""target/zip-unarchiver-tests""; File testZip = new File( getBasedir(), ""src/test/jars/test.zip"" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.extract( """", outputDirectory ); File testScript = new File( outputDirectory, ""test.sh"" ); final Method canExecute; try { canExecute = File.class.getMethod( ""canExecute"" ); canExecute.invoke( testScript ); assertTrue( (Boolean) canExecute.invoke( testScript ) ); } catch ( NoSuchMethodException ignore ) { } } "," public void testExtractingZipPreservesExecutableFlag() throws Exception { String s = ""target/zip-unarchiver-tests""; File testZip = new File( getBasedir(), ""src/test/jars/test.zip"" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.extract( """", outputDirectory ); File testScript = new File( outputDirectory, ""test.sh"" ); final Method canExecute; try { canExecute = File.class.getMethod( ""canExecute"" ); canExecute.invoke( testScript ); assertTrue( (Boolean) canExecute.invoke( testScript ) ); } catch ( NoSuchMethodException ignore ) { } } ",FALSE,ZipUnArchiverTest.java " public void testZeroFileModeInZip() throws Exception { String s = ""target/zip-unarchiver-filemode-tests""; File testZip = new File( getBasedir(), ""src/test/resources/zeroFileMode/foobar.zip"" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.setIgnorePermissions( false ); zu.extract( """", outputDirectory ); File testScript = new File( outputDirectory, ""foo.txt"" ); final Method canRead; try { canRead = File.class.getMethod( ""canRead"" ); canRead.invoke( testScript ); assertTrue( (Boolean) canRead.invoke( testScript ) ); } catch ( NoSuchMethodException ignore ) { } } "," public void testZeroFileModeInZip() throws Exception { String s = ""target/zip-unarchiver-filemode-tests""; File testZip = new File( getBasedir(), ""src/test/resources/zeroFileMode/foobar.zip"" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.setIgnorePermissions( false ); zu.extract( """", outputDirectory ); File testScript = new File( outputDirectory, ""foo.txt"" ); final Method canRead; try { canRead = File.class.getMethod( ""canRead"" ); canRead.invoke( testScript ); assertTrue( (Boolean) canRead.invoke( testScript ) ); } catch ( NoSuchMethodException ignore ) { } } ",FALSE,ZipUnArchiverTest.java " public void testUnarchiveUtf8() throws Exception { File dest = new File( ""target/output/unzip/utf8"" ); dest.mkdirs(); final File zipFile = new File( ""target/output/unzip/utf8-default.zip"" ); final ZipArchiver zipArchiver = getZipArchiver( zipFile ); zipArchiver.addDirectory( new File( ""src/test/resources/miscUtf8"" ) ); zipArchiver.createArchive(); final ZipUnArchiver unarchiver = getZipUnArchiver( zipFile ); unarchiver.setDestFile( dest ); unarchiver.extract(); assertTrue( new File( dest, ""aPi\u00F1ata.txt"" ).exists() ); assertTrue( new File( dest, ""an\u00FCmlaut.txt"" ).exists() ); assertTrue( new File( dest, ""\u20acuro.txt"" ).exists() ); } "," public void testUnarchiveUtf8() throws Exception { File dest = new File( ""target/output/unzip/utf8"" ); dest.mkdirs(); final File zipFile = new File( ""target/output/unzip/utf8-default.zip"" ); final ZipArchiver zipArchiver = getZipArchiver( zipFile ); zipArchiver.addDirectory( new File( ""src/test/resources/miscUtf8"" ) ); zipArchiver.createArchive(); final ZipUnArchiver unarchiver = getZipUnArchiver( zipFile ); unarchiver.setDestFile( dest ); unarchiver.extract(); assertTrue( new File( dest, ""aPi\u00F1ata.txt"" ).exists() ); assertTrue( new File( dest, ""an\u00FCmlaut.txt"" ).exists() ); assertTrue( new File( dest, ""\u20acuro.txt"" ).exists() ); } ",FALSE,ZipUnArchiverTest.java " private void runUnarchiver( String path, FileSelector[] selectors, boolean[] results ) throws Exception { String s = ""target/zip-unarchiver-tests""; File testJar = new File( getBasedir(), ""src/test/jars/test.jar"" ); File outputDirectory = new File( getBasedir(), s ); ZipUnArchiver zu = getZipUnArchiver( testJar ); zu.setFileSelectors( selectors ); FileUtils.deleteDirectory( outputDirectory ); zu.extract( path, outputDirectory ); File f0 = new File( getBasedir(), s + ""/resources/artifactId/test.properties"" ); assertEquals( results[0], f0.exists() ); File f1 = new File( getBasedir(), s + ""/resources/artifactId/directory/test.properties"" ); assertEquals( results[1], f1.exists() ); File f2 = new File( getBasedir(), s + ""/META-INF/MANIFEST.MF"" ); assertEquals( results[2], f2.exists() ); } "," private void runUnarchiver( String path, FileSelector[] selectors, boolean[] results ) throws Exception { String s = ""target/zip-unarchiver-tests""; File testJar = new File( getBasedir(), ""src/test/jars/test.jar"" ); File outputDirectory = new File( getBasedir(), s ); ZipUnArchiver zu = getZipUnArchiver( testJar ); zu.setFileSelectors( selectors ); FileUtils.deleteDirectory( outputDirectory ); zu.extract( path, outputDirectory ); File f0 = new File( getBasedir(), s + ""/resources/artifactId/test.properties"" ); assertEquals( results[0], f0.exists() ); File f1 = new File( getBasedir(), s + ""/resources/artifactId/directory/test.properties"" ); assertEquals( results[1], f1.exists() ); File f2 = new File( getBasedir(), s + ""/META-INF/MANIFEST.MF"" ); assertEquals( results[2], f2.exists() ); } ",FALSE,ZipUnArchiverTest.java " private ZipUnArchiver getZipUnArchiver( File testJar ) throws Exception { ZipUnArchiver zu = (ZipUnArchiver) lookup( UnArchiver.ROLE, ""zip"" ); zu.setSourceFile( testJar ); return zu; } "," private ZipUnArchiver getZipUnArchiver( File testJar ) throws Exception { ZipUnArchiver zu = (ZipUnArchiver) lookup( UnArchiver.ROLE, ""zip"" ); zu.setSourceFile( testJar ); return zu; } ",FALSE,ZipUnArchiverTest.java " public void testExtractingADirectoryFromAJarFile() throws Exception { runUnarchiver( ""resources/artifactId"", null, new boolean[] { true, true, false } ); runUnarchiver( """", null, new boolean[] { true, true, true } ); } "," public void testExtractingADirectoryFromAJarFile() throws Exception { runUnarchiver( ""resources/artifactId"", null, new boolean[] { true, true, false } ); runUnarchiver( """", null, new boolean[] { true, true, true } ); } ",FALSE,ZipUnArchiverTest.java " public void testSelectors() throws Exception { IncludeExcludeFileSelector fileSelector = new IncludeExcludeFileSelector(); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { true, true, true } ); fileSelector.setExcludes( new String[] { ""**/test.properties"" } ); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { false, false, true } ); fileSelector.setIncludes( new String[] { ""**/test.properties"" } ); fileSelector.setExcludes( null ); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { true, true, false } ); fileSelector.setExcludes( new String[] { ""resources/artifactId/directory/test.properties"" } ); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { true, false, false } ); } "," public void testSelectors() throws Exception { IncludeExcludeFileSelector fileSelector = new IncludeExcludeFileSelector(); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { true, true, true } ); fileSelector.setExcludes( new String[] { ""**/test.properties"" } ); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { false, false, true } ); fileSelector.setIncludes( new String[] { ""**/test.properties"" } ); fileSelector.setExcludes( null ); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { true, true, false } ); fileSelector.setExcludes( new String[] { ""resources/artifactId/directory/test.properties"" } ); runUnarchiver( """", new FileSelector[] { fileSelector }, new boolean[] { true, false, false } ); } ",FALSE,ZipUnArchiverTest.java " "," public void testExtractingZipWithEntryOutsideDestDirThrowsException() throws Exception { Exception ex = null; String s = ""target/zip-unarchiver-slip-tests""; File testZip = new File( getBasedir(), ""src/test/zips/zip-slip.zip"" ); File outputDirectory = new File( getBasedir(), s ); FileUtils.deleteDirectory( outputDirectory ); try { ZipUnArchiver zu = getZipUnArchiver( testZip ); zu.extract( """", outputDirectory ); } catch ( Exception e ) { ex = e; } assertNotNull( ex ); assertTrue( ex.getMessage().startsWith( ""Entry is outside of the target directory"" ) ); } ",TRUE,ZipUnArchiverTest.java " private ZipArchiver getZipArchiver() { try { return (ZipArchiver) lookup( Archiver.ROLE, ""zip"" ); } catch ( Exception e ) { throw new RuntimeException( e ); } } "," private ZipArchiver getZipArchiver() { try { return (ZipArchiver) lookup( Archiver.ROLE, ""zip"" ); } catch ( Exception e ) { throw new RuntimeException( e ); } } ",FALSE,ZipUnArchiverTest.java " private ZipArchiver getZipArchiver( File destFile ) { final ZipArchiver zipArchiver = getZipArchiver(); zipArchiver.setDestFile( destFile ); return zipArchiver; } "," private ZipArchiver getZipArchiver( File destFile ) { final ZipArchiver zipArchiver = getZipArchiver(); zipArchiver.setDestFile( destFile ); return zipArchiver; } ",FALSE,ZipUnArchiverTest.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); // Be particular about decoding an unsecured JWT. If the JWT is signed or any verifiers were provided don't do it. if (header.algorithm == Algorithm.none && parts.length == 2 && verifiers.length == 0) { return Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class); } // 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); } ",TRUE,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); String[] parts = getParts(encodedJWT); Header header = Mapper.deserialize(base64Decode(parts[0].getBytes(StandardCharsets.UTF_8)), Header.class); // Be particular about decoding an unsecured JWT. If the JWT is signed or any verifiers were provided don't do it. if (header.algorithm == Algorithm.none && parts.length == 2 && verifiers.isEmpty()) { return Mapper.deserialize(base64Decode(parts[1].getBytes(StandardCharsets.UTF_8)), JWT.class); } // 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); 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); } ",TRUE,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() + ""]""); } 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) { 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; } ",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 decoding_performance() throws Exception { String secret = JWTUtils.generateSHA256HMACSecret(); Signer hmacSigner = HMACSigner.newSHA256Signer(secret); Signer rsaSigner = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_2048.pem"")))); Verifier hmacVerifier = HMACVerifier.newVerifier(secret); Verifier rsaVerifier = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem"")))); JWT jwt = new JWT().setSubject(UUID.randomUUID().toString()) .addClaim(""exp"", ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).toInstant().toEpochMilli()) .setAudience(UUID.randomUUID().toString()) .addClaim(""roles"", new ArrayList<>(Arrays.asList(""admin"", ""user""))) .addClaim(""iat"", ZonedDateTime.now(ZoneOffset.UTC).toInstant().toEpochMilli()) .setIssuer(""inversoft.com""); long iterationCount = 250_000; for (Verifier verifier : Arrays.asList(hmacVerifier, rsaVerifier)) { Instant start = Instant.now(); Signer signer = verifier instanceof HMACVerifier ? hmacSigner : rsaSigner; // Uncomment the following line to run without a signer, no signature, no verification is very fast. // Signer signer = new UnsecuredSigner(); String encodedJWT = JWT.getEncoder().encode(jwt, signer); for (int i = 0; i < iterationCount; i++) { JWT.getDecoder().decode(encodedJWT, verifier); // Uncomment the following line to run without a signer, no signature, no verification is very fast. // JWT.getDecoder().decode(encodedJWT); // no verifier, no signature } Duration duration = Duration.between(start, Instant.now()); BigDecimal durationInMillis = BigDecimal.valueOf(duration.toMillis()); BigDecimal average = durationInMillis.divide(BigDecimal.valueOf(iterationCount), RoundingMode.HALF_DOWN); long perSecond = iterationCount / (duration.toMillis() / 1000); System.out.println(""["" + signer.getAlgorithm().getName() + ""] "" + duration.toMillis() + "" milliseconds total. ["" + iterationCount + ""] iterations. ["" + average + ""] milliseconds per iteration. Approx. ["" + perSecond + ""] per second.""); } } "," public void decoding_performance() throws Exception { String secret = JWTUtils.generateSHA256HMACSecret(); Signer hmacSigner = HMACSigner.newSHA256Signer(secret); Signer rsaSigner = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_2048.pem"")))); Verifier hmacVerifier = HMACVerifier.newVerifier(secret); Verifier rsaVerifier = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem"")))); JWT jwt = new JWT().setSubject(UUID.randomUUID().toString()) .addClaim(""exp"", ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).toInstant().toEpochMilli()) .setAudience(UUID.randomUUID().toString()) .addClaim(""roles"", new ArrayList<>(Arrays.asList(""admin"", ""user""))) .addClaim(""iat"", ZonedDateTime.now(ZoneOffset.UTC).toInstant().toEpochMilli()) .setIssuer(""inversoft.com""); long iterationCount = 250_000; for (Verifier verifier : Arrays.asList(hmacVerifier, rsaVerifier)) { Instant start = Instant.now(); Signer signer = verifier instanceof HMACVerifier ? hmacSigner : rsaSigner; // Uncomment the following line to run without a signer, no signature, no verification is very fast. // Signer signer = new UnsecuredSigner(); String encodedJWT = JWT.getEncoder().encode(jwt, signer); for (int i = 0; i < iterationCount; i++) { JWT.getDecoder().decode(encodedJWT, verifier); // Uncomment the following line to run without a signer, no signature, no verification is very fast. // JWT.getDecoder().decode(encodedJWT); // no verifier, no signature } Duration duration = Duration.between(start, Instant.now()); BigDecimal durationInMillis = BigDecimal.valueOf(duration.toMillis()); BigDecimal average = durationInMillis.divide(BigDecimal.valueOf(iterationCount), RoundingMode.HALF_DOWN); long perSecond = iterationCount / (duration.toMillis() / 1000); System.out.println(""["" + signer.getAlgorithm().getName() + ""] "" + duration.toMillis() + "" milliseconds total. ["" + iterationCount + ""] iterations. ["" + average + ""] milliseconds per iteration. Approx. ["" + perSecond + ""] per second.""); } } ",FALSE,JWTTest.java " public void encoding_performance() throws Exception { Signer hmacSigner = HMACSigner.newSHA256Signer(JWTUtils.generateSHA256HMACSecret()); Signer rsaSigner = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_2048.pem"")))); JWT jwt = new JWT().setSubject(UUID.randomUUID().toString()) .addClaim(""exp"", ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).toInstant().toEpochMilli()) .setAudience(UUID.randomUUID().toString()) .addClaim(""roles"", new ArrayList<>(Arrays.asList(""admin"", ""user""))) .addClaim(""iat"", ZonedDateTime.now(ZoneOffset.UTC).toInstant().toEpochMilli()) .setIssuer(""inversoft.com""); long iterationCount = 10_000; for (Signer signer : Arrays.asList(hmacSigner, rsaSigner)) { // Uncomment the following line to run without a signer, no signature, no verification is very fast. // signer = new UnsecuredSigner(); Instant start = Instant.now(); for (int i = 0; i < iterationCount; i++) { JWT.getEncoder().encode(jwt, signer); } Duration duration = Duration.between(start, Instant.now()); BigDecimal durationInMillis = BigDecimal.valueOf(duration.toMillis()); BigDecimal average = durationInMillis.divide(BigDecimal.valueOf(iterationCount), RoundingMode.HALF_DOWN); long perSecond = iterationCount / (duration.toMillis() / 1000); System.out.println(""["" + signer.getAlgorithm().getName() + ""] "" + duration.toMillis() + "" milliseconds total. ["" + iterationCount + ""] iterations. ["" + average + ""] milliseconds per iteration. Approx. ["" + perSecond + ""] per second.""); } } "," public void encoding_performance() throws Exception { Signer hmacSigner = HMACSigner.newSHA256Signer(JWTUtils.generateSHA256HMACSecret()); Signer rsaSigner = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_2048.pem"")))); JWT jwt = new JWT().setSubject(UUID.randomUUID().toString()) .addClaim(""exp"", ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).toInstant().toEpochMilli()) .setAudience(UUID.randomUUID().toString()) .addClaim(""roles"", new ArrayList<>(Arrays.asList(""admin"", ""user""))) .addClaim(""iat"", ZonedDateTime.now(ZoneOffset.UTC).toInstant().toEpochMilli()) .setIssuer(""inversoft.com""); long iterationCount = 10_000; for (Signer signer : Arrays.asList(hmacSigner, rsaSigner)) { // Uncomment the following line to run without a signer, no signature, no verification is very fast. // signer = new UnsecuredSigner(); Instant start = Instant.now(); for (int i = 0; i < iterationCount; i++) { JWT.getEncoder().encode(jwt, signer); } Duration duration = Duration.between(start, Instant.now()); BigDecimal durationInMillis = BigDecimal.valueOf(duration.toMillis()); BigDecimal average = durationInMillis.divide(BigDecimal.valueOf(iterationCount), RoundingMode.HALF_DOWN); long perSecond = iterationCount / (duration.toMillis() / 1000); System.out.println(""["" + signer.getAlgorithm().getName() + ""] "" + duration.toMillis() + "" milliseconds total. ["" + iterationCount + ""] iterations. ["" + average + ""] milliseconds per iteration. Approx. ["" + perSecond + ""] per second.""); } } ",FALSE,JWTTest.java " public void expired() throws Exception { // no expiration assertFalse(new JWT() .setSubject(""123456789"").isExpired()); assertFalse(new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(1)) .setSubject(""123456789"").isExpired()); assertTrue(new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(1)) .setSubject(""123456789"").isExpired()); } "," public void expired() throws Exception { // no expiration assertFalse(new JWT() .setSubject(""123456789"").isExpired()); assertFalse(new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(1)) .setSubject(""123456789"").isExpired()); assertTrue(new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(1)) .setSubject(""123456789"").isExpired()); } ",FALSE,JWTTest.java " public void test_HS256() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = HMACSigner.newSHA256Signer(""secret""); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.qHdut1UR4-2FSAvh7U3YdeRR5r5boVqjIGQ16Ztp894""); } "," public void test_HS256() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = HMACSigner.newSHA256Signer(""secret""); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.qHdut1UR4-2FSAvh7U3YdeRR5r5boVqjIGQ16Ztp894""); } ",FALSE,JWTTest.java " public void test_HS256_manualAddedClaim() throws Exception { JWT jwt = new JWT().addClaim(""test"", ""123456789""); Signer signer = HMACSigner.newSHA256Signer(""secret""); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoiMTIzNDU2Nzg5In0.0qgr4ztqB0mNXA8mtqaBSL6UJT3aqEyjHMrWDZmT4Bc""); } "," public void test_HS256_manualAddedClaim() throws Exception { JWT jwt = new JWT().addClaim(""test"", ""123456789""); Signer signer = HMACSigner.newSHA256Signer(""secret""); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoiMTIzNDU2Nzg5In0.0qgr4ztqB0mNXA8mtqaBSL6UJT3aqEyjHMrWDZmT4Bc""); } ",FALSE,JWTTest.java " public void test_HS384() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = HMACSigner.newSHA384Signer(""secret""); String encodedJWT = JWT.getEncoder().encode(jwt, signer); assertEquals(encodedJWT, ""eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.sCHKynlQkBveA063_Z-fwcXmRYp_lKQ0fRqGNzplb14qMUj5CV3CfXwluclTF17P""); assertEquals(JWT.getDecoder().decode(encodedJWT, HMACVerifier.newVerifier(""secret"")).subject, jwt.subject); } "," public void test_HS384() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = HMACSigner.newSHA384Signer(""secret""); String encodedJWT = JWT.getEncoder().encode(jwt, signer); assertEquals(encodedJWT, ""eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.sCHKynlQkBveA063_Z-fwcXmRYp_lKQ0fRqGNzplb14qMUj5CV3CfXwluclTF17P""); assertEquals(JWT.getDecoder().decode(encodedJWT, HMACVerifier.newVerifier(""secret"")).subject, jwt.subject); } ",FALSE,JWTTest.java " public void test_HS512() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = HMACSigner.newSHA512Signer(""secret""); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.MgAi9gfGkep-IoFYPHMhHz6w2Kxf0u8TZ-wNeQOLPwc8emLNKOMqBU-5dJXeaY5-8wQ1CvZycWHbEilvHgN6Ug""); } "," public void test_HS512() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = HMACSigner.newSHA512Signer(""secret""); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.MgAi9gfGkep-IoFYPHMhHz6w2Kxf0u8TZ-wNeQOLPwc8emLNKOMqBU-5dJXeaY5-8wQ1CvZycWHbEilvHgN6Ug""); } ",FALSE,JWTTest.java " public void test_RS256() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_4096.pem"")))); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.kRXJkOHC98D0LCT2oPg5fTmQJDFXkMRQJopbt7QM6prmQDHwjJL_xO-_EXRXnbvf5NLORto45By3XNn2ZzWmY3pAOxj46MlQ5elhROx2S-EnHZNLfQhoG8ZXPZ54q-Obz_6K7ZSlkAQ8jmeZUO3Ryi8jRlHQ2PT4LbBtLpaf982SGJfeTyUMw1LbvowZUTZSF-E6JARaokmmx8M2GeLuKcFhU-YsBTXUarKp0IJCy3jpMQ2zW_HGjyVWH8WwSIbSdpBn7ztoQEJYO-R5H3qVaAz2BsTuGLRxoyIu1iy2-QcDp5uTufmX1roXM8ciQMpcfwKGiyNpKVIZm-lF8aROXRL4kk4rqp6KUzJuOPljPXRU--xKSua-DeR0BEerKzI9hbwIMWiblCslAciNminoSc9G7pUyVwV5Z5IT8CGJkVgoyVGELeBmYCDy7LHwXrr0poc0hPbE3mJXhzolga4BB84nCg2Hb9tCNiHU8F-rKgZWCONaSSIdhQ49x8OiPafFh2DJBEBe5Xbm6xdCfh3KVG0qe4XL18R5s98aIP9UIC4i62UEgPy6W7Fr7QgUxpXrjRCERBV3MiNu4L8NNJb3oZleq5lQi72EfdS-Bt8ZUOVInIcAvSmu-3i8jB_2sF38XUXdl8gkW8k_b9dJkzDcivCFehvSqGmm3vBm5X4bNmk""); } "," public void test_RS256() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_4096.pem"")))); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.kRXJkOHC98D0LCT2oPg5fTmQJDFXkMRQJopbt7QM6prmQDHwjJL_xO-_EXRXnbvf5NLORto45By3XNn2ZzWmY3pAOxj46MlQ5elhROx2S-EnHZNLfQhoG8ZXPZ54q-Obz_6K7ZSlkAQ8jmeZUO3Ryi8jRlHQ2PT4LbBtLpaf982SGJfeTyUMw1LbvowZUTZSF-E6JARaokmmx8M2GeLuKcFhU-YsBTXUarKp0IJCy3jpMQ2zW_HGjyVWH8WwSIbSdpBn7ztoQEJYO-R5H3qVaAz2BsTuGLRxoyIu1iy2-QcDp5uTufmX1roXM8ciQMpcfwKGiyNpKVIZm-lF8aROXRL4kk4rqp6KUzJuOPljPXRU--xKSua-DeR0BEerKzI9hbwIMWiblCslAciNminoSc9G7pUyVwV5Z5IT8CGJkVgoyVGELeBmYCDy7LHwXrr0poc0hPbE3mJXhzolga4BB84nCg2Hb9tCNiHU8F-rKgZWCONaSSIdhQ49x8OiPafFh2DJBEBe5Xbm6xdCfh3KVG0qe4XL18R5s98aIP9UIC4i62UEgPy6W7Fr7QgUxpXrjRCERBV3MiNu4L8NNJb3oZleq5lQi72EfdS-Bt8ZUOVInIcAvSmu-3i8jB_2sF38XUXdl8gkW8k_b9dJkzDcivCFehvSqGmm3vBm5X4bNmk""); } ",FALSE,JWTTest.java " public void test_RS384() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = RSASigner.newSHA384Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_4096.pem"")))); String encodedJWT = JWT.getEncoder().encode(jwt, signer); assertEquals(encodedJWT, ""eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.OkmWXzhTm7mtfpeMVNLlFjw3fJvc7yMQ1rgI5BXBPqaLSb_fpLHYAq_q5pQDDaIGg8klg9y2f784smc7-o9czX3JnzEDvO9e_sA10YIEA6Q9qRh17EATNXFG-WzSocpxPgEOQZ8lqSqZ_0waCGaUMwK5J5BB1A_70AcNGPnI7PrX76lWNNHwdK0OjkhkxX7vHR6B-uAIzih0ntQP_afr1UIzXkllmnnb1oU9cgFFD1AGDa3V0XCgitVYZA_ozbGELGMrUl_7fB_uNVEvcreUoZIEI4cfUKI6iZ8Ll4j_iLAdlpH4GRGNiQ7gMLq35AqqxKbEG8r-S-SrlRL6PkKlaJ-viMVLxoHreZow634r8A1fxR1mnrdUnn0vGmOthyjpP_TgfAsER9EJ_UUIamsKC8s6pip2jcPB7G6huHocyKBTxsoxclQgk1jOy4lZq4Js2KKM5sGfcq5SWQTW4B44KlUU1kWWmUg21jtflna38sWFdTk845phi5ITOBZ_ElJ9MdYVAgjvDsRFs_XxFENlwpwKeLD9PsaCiJhdG7EJN5qJvVogYuUMM0wyS-SOGZ1ILsTeYsjc7TtI0JUKndlUXFPubwaaxW_06zrCJR-dvWye99fIDH-u3I74XK5MKhknlgewzsXpsiPdvsMW59WUbdIZqkvok5vdkIlm4XGIqcM""); assertEquals(JWT.getDecoder().decode(encodedJWT, RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_4096.pem""))))).subject, jwt.subject); } "," public void test_RS384() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = RSASigner.newSHA384Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_4096.pem"")))); String encodedJWT = JWT.getEncoder().encode(jwt, signer); assertEquals(encodedJWT, ""eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.OkmWXzhTm7mtfpeMVNLlFjw3fJvc7yMQ1rgI5BXBPqaLSb_fpLHYAq_q5pQDDaIGg8klg9y2f784smc7-o9czX3JnzEDvO9e_sA10YIEA6Q9qRh17EATNXFG-WzSocpxPgEOQZ8lqSqZ_0waCGaUMwK5J5BB1A_70AcNGPnI7PrX76lWNNHwdK0OjkhkxX7vHR6B-uAIzih0ntQP_afr1UIzXkllmnnb1oU9cgFFD1AGDa3V0XCgitVYZA_ozbGELGMrUl_7fB_uNVEvcreUoZIEI4cfUKI6iZ8Ll4j_iLAdlpH4GRGNiQ7gMLq35AqqxKbEG8r-S-SrlRL6PkKlaJ-viMVLxoHreZow634r8A1fxR1mnrdUnn0vGmOthyjpP_TgfAsER9EJ_UUIamsKC8s6pip2jcPB7G6huHocyKBTxsoxclQgk1jOy4lZq4Js2KKM5sGfcq5SWQTW4B44KlUU1kWWmUg21jtflna38sWFdTk845phi5ITOBZ_ElJ9MdYVAgjvDsRFs_XxFENlwpwKeLD9PsaCiJhdG7EJN5qJvVogYuUMM0wyS-SOGZ1ILsTeYsjc7TtI0JUKndlUXFPubwaaxW_06zrCJR-dvWye99fIDH-u3I74XK5MKhknlgewzsXpsiPdvsMW59WUbdIZqkvok5vdkIlm4XGIqcM""); assertEquals(JWT.getDecoder().decode(encodedJWT, RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_4096.pem""))))).subject, jwt.subject); } ",FALSE,JWTTest.java " public void test_RS512() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = RSASigner.newSHA512Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_4096.pem"")))); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.ei28WNoJdUpMlLnHr78HiTnnuKwSRLYcOpgUC3daVInT5RAc0kk2Ipx16Z-bHL_eFLSYgF3TSKdymFpNf8cnEu5T6rH0azYSZLrPmVCetDxjo-ixXK9asPOF3JuIbDjN7ow3K-CMbMCWzWp04ZAh-DNecYEd3HiGgooPVGA4HuVXZFHH8XfQ9TD-64ppBQTWgW32vkna8ILKyIXdwWXSEfCZYfLzLZnilJrz820wZJ5JMXimv2au0OwwRobUMLEBUM4iuEPXLf5wFJU6LcU0XMuovavfIXKDpvP9Yfz6UplMlFvIr9y72xExfaNt32vwneAP-Fpg2x9wYvR0W8LhXKZaFRfcYwhbj17GCAbpx34hjiqnwyFStn5Qx_QHz_Y7ck-ZXB2MGUkiYGj9y_8bQNx-LIaTQUX6sONTNdVVCfnOnMHFqVbupGho24K7885-8BxCRojvA0ggneF6dsKCQvAt2rsVRso0TrCVxwYItb9tRsyhCbWou-zh_08JlYGVXPiGY3RRQDfxCc9RHQUflWRS9CBcPtoaco4mFKZSM-9e_xoYx__DEzM3UjaI4jReLM-IARwlVPoHJa2Vcb5wngZTaxGf2ToMq7R_8KecZymb3OaA2X1e8GS2300ySwsXbOz0sJv2a7_JUncSEBPSsb2vMMurxSJ4E3RTAc4s3aU""); } "," public void test_RS512() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = RSASigner.newSHA512Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_4096.pem"")))); assertEquals(JWT.getEncoder().encode(jwt, signer), ""eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkifQ.ei28WNoJdUpMlLnHr78HiTnnuKwSRLYcOpgUC3daVInT5RAc0kk2Ipx16Z-bHL_eFLSYgF3TSKdymFpNf8cnEu5T6rH0azYSZLrPmVCetDxjo-ixXK9asPOF3JuIbDjN7ow3K-CMbMCWzWp04ZAh-DNecYEd3HiGgooPVGA4HuVXZFHH8XfQ9TD-64ppBQTWgW32vkna8ILKyIXdwWXSEfCZYfLzLZnilJrz820wZJ5JMXimv2au0OwwRobUMLEBUM4iuEPXLf5wFJU6LcU0XMuovavfIXKDpvP9Yfz6UplMlFvIr9y72xExfaNt32vwneAP-Fpg2x9wYvR0W8LhXKZaFRfcYwhbj17GCAbpx34hjiqnwyFStn5Qx_QHz_Y7ck-ZXB2MGUkiYGj9y_8bQNx-LIaTQUX6sONTNdVVCfnOnMHFqVbupGho24K7885-8BxCRojvA0ggneF6dsKCQvAt2rsVRso0TrCVxwYItb9tRsyhCbWou-zh_08JlYGVXPiGY3RRQDfxCc9RHQUflWRS9CBcPtoaco4mFKZSM-9e_xoYx__DEzM3UjaI4jReLM-IARwlVPoHJa2Vcb5wngZTaxGf2ToMq7R_8KecZymb3OaA2X1e8GS2300ySwsXbOz0sJv2a7_JUncSEBPSsb2vMMurxSJ4E3RTAc4s3aU""); } ",FALSE,JWTTest.java " public void test_RSA_1024Key() throws Exception { expectException(InvalidKeyLengthException.class, () -> RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_1024.pem""))))); expectException(InvalidKeyLengthException.class, () -> RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_1024.pem""))))); } "," public void test_RSA_1024Key() throws Exception { expectException(InvalidKeyLengthException.class, () -> RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_1024.pem""))))); expectException(InvalidKeyLengthException.class, () -> RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_1024.pem""))))); } ",FALSE,JWTTest.java " } "," public void test_SingedWithoutSignature() 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)); } ",TRUE,JWTTest.java " public void test_badEncoding() throws Exception { Verifier verifier = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem"")))); // add a space to the header, invalid Base64 character point 20 (space) expectException(InvalidJWTException.class, () -> JWT.getDecoder().decode(""eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9 .foo.bar"", verifier)); } "," public void test_badEncoding() throws Exception { Verifier verifier = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem"")))); // add a space to the header, invalid Base64 character point 20 (space) expectException(InvalidJWTException.class, () -> JWT.getDecoder().decode(""eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9 .foo.bar"", verifier)); } ",FALSE,JWTTest.java " public void test_complexPayload() throws Exception { JWT expectedJWT = new JWT() .setAudience(Arrays.asList(""www.acme.com"", ""www.vandelayindustries.com"")) .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS)) .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)) .setIssuer(""www.inversoft.com"") .setNotBefore(ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(5).truncatedTo(ChronoUnit.SECONDS)) .setUniqueId(UUID.randomUUID().toString()) .setSubject(""123456789"") .addClaim(""foo"", ""bar"") .addClaim(""timestamp"", 1476062602926L) .addClaim(""meaningOfLife"", 42) .addClaim(""bar"", Arrays.asList(""bing"", ""bam"", ""boo"")) .addClaim(""www.inversoft.com/claims/is_admin"", true); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer); JWT actualJwt = JWT.getDecoder().decode(encodedJWT, verifier); assertEquals(actualJwt.audience, expectedJWT.audience); assertEquals(actualJwt.expiration, expectedJWT.expiration); assertEquals(actualJwt.issuedAt, expectedJWT.issuedAt); assertEquals(actualJwt.issuer, expectedJWT.issuer); assertEquals(actualJwt.notBefore, expectedJWT.notBefore); assertEquals(actualJwt.uniqueId, expectedJWT.uniqueId); assertEquals(actualJwt.subject, expectedJWT.subject); assertEquals(actualJwt.getString(""foo""), expectedJWT.getString(""foo"")); assertEquals(actualJwt.getLong(""timestamp""), expectedJWT.getLong(""timestamp"")); assertEquals(actualJwt.getInteger(""meaningOfLife""), expectedJWT.getInteger(""meaningOfLife"")); assertEquals(actualJwt.getObject(""bar""), expectedJWT.getObject(""bar"")); assertEquals(actualJwt.getBoolean(""www.inversoft.com/claims/is_admin""), expectedJWT.getBoolean(""www.inversoft.com/claims/is_admin"")); // validate raw claims Map rawClaims = actualJwt.getRawClaims(); assertEquals(rawClaims.get(""aud""), expectedJWT.audience); assertEquals(rawClaims.get(""exp""), expectedJWT.expiration.toEpochSecond()); assertEquals(rawClaims.get(""iat""), expectedJWT.issuedAt.toEpochSecond()); assertEquals(rawClaims.get(""iss""), expectedJWT.issuer); assertEquals(rawClaims.get(""nbf""), expectedJWT.notBefore.toEpochSecond()); assertEquals(rawClaims.get(""jti""), expectedJWT.uniqueId); assertEquals(rawClaims.get(""sub""), expectedJWT.subject); assertEquals(rawClaims.get(""foo""), expectedJWT.getString(""foo"")); assertEquals(rawClaims.get(""timestamp""), expectedJWT.getLong(""timestamp"")); assertEquals(rawClaims.get(""meaningOfLife""), expectedJWT.getInteger(""meaningOfLife"")); assertEquals(rawClaims.get(""bar""), expectedJWT.getObject(""bar"")); assertEquals(rawClaims.get(""www.inversoft.com/claims/is_admin""), expectedJWT.getBoolean(""www.inversoft.com/claims/is_admin"")); } "," public void test_complexPayload() throws Exception { JWT expectedJWT = new JWT() .setAudience(Arrays.asList(""www.acme.com"", ""www.vandelayindustries.com"")) .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS)) .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)) .setIssuer(""www.inversoft.com"") .setNotBefore(ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(5).truncatedTo(ChronoUnit.SECONDS)) .setUniqueId(UUID.randomUUID().toString()) .setSubject(""123456789"") .addClaim(""foo"", ""bar"") .addClaim(""timestamp"", 1476062602926L) .addClaim(""meaningOfLife"", 42) .addClaim(""bar"", Arrays.asList(""bing"", ""bam"", ""boo"")) .addClaim(""www.inversoft.com/claims/is_admin"", true); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer); JWT actualJwt = JWT.getDecoder().decode(encodedJWT, verifier); assertEquals(actualJwt.audience, expectedJWT.audience); assertEquals(actualJwt.expiration, expectedJWT.expiration); assertEquals(actualJwt.issuedAt, expectedJWT.issuedAt); assertEquals(actualJwt.issuer, expectedJWT.issuer); assertEquals(actualJwt.notBefore, expectedJWT.notBefore); assertEquals(actualJwt.uniqueId, expectedJWT.uniqueId); assertEquals(actualJwt.subject, expectedJWT.subject); assertEquals(actualJwt.getString(""foo""), expectedJWT.getString(""foo"")); assertEquals(actualJwt.getLong(""timestamp""), expectedJWT.getLong(""timestamp"")); assertEquals(actualJwt.getInteger(""meaningOfLife""), expectedJWT.getInteger(""meaningOfLife"")); assertEquals(actualJwt.getObject(""bar""), expectedJWT.getObject(""bar"")); assertEquals(actualJwt.getBoolean(""www.inversoft.com/claims/is_admin""), expectedJWT.getBoolean(""www.inversoft.com/claims/is_admin"")); // validate raw claims Map rawClaims = actualJwt.getRawClaims(); assertEquals(rawClaims.get(""aud""), expectedJWT.audience); assertEquals(rawClaims.get(""exp""), expectedJWT.expiration.toEpochSecond()); assertEquals(rawClaims.get(""iat""), expectedJWT.issuedAt.toEpochSecond()); assertEquals(rawClaims.get(""iss""), expectedJWT.issuer); assertEquals(rawClaims.get(""nbf""), expectedJWT.notBefore.toEpochSecond()); assertEquals(rawClaims.get(""jti""), expectedJWT.uniqueId); assertEquals(rawClaims.get(""sub""), expectedJWT.subject); assertEquals(rawClaims.get(""foo""), expectedJWT.getString(""foo"")); assertEquals(rawClaims.get(""timestamp""), expectedJWT.getLong(""timestamp"")); assertEquals(rawClaims.get(""meaningOfLife""), expectedJWT.getInteger(""meaningOfLife"")); assertEquals(rawClaims.get(""bar""), expectedJWT.getObject(""bar"")); assertEquals(rawClaims.get(""www.inversoft.com/claims/is_admin""), expectedJWT.getBoolean(""www.inversoft.com/claims/is_admin"")); } ",FALSE,JWTTest.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""))); } ",FALSE,JWTTest.java " public void test_expiredThrows() throws Exception { JWT expectedJWT = new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(1).truncatedTo(ChronoUnit.SECONDS)); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer); expectException(JWTExpiredException.class, () -> JWT.getDecoder().decode(encodedJWT, verifier)); } "," public void test_expiredThrows() throws Exception { JWT expectedJWT = new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).minusMinutes(1).truncatedTo(ChronoUnit.SECONDS)); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer); expectException(JWTExpiredException.class, () -> JWT.getDecoder().decode(encodedJWT, verifier)); } ",FALSE,JWTTest.java " public void test_multipleSignersAndVerifiers() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); // Three separate signers Signer signer1 = HMACSigner.newSHA512Signer(""secret1""); Signer signer2 = HMACSigner.newSHA512Signer(""secret2""); Signer signer3 = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_2048.pem"")))); // Encode the same JWT with each signer, writing the Key ID to the header String encodedJWT1 = JWT.getEncoder().encode(jwt, signer1, h -> h.set(""kid"", ""verifier1"")); String encodedJWT2 = JWT.getEncoder().encode(jwt, signer2, h -> h.set(""kid"", ""verifier2"")); String encodedJWT3 = JWT.getEncoder().encode(jwt, signer3, h -> h.set(""kid"", ""verifier3"")); Verifier verifier1 = HMACVerifier.newVerifier(""secret1""); Verifier verifier2 = HMACVerifier.newVerifier(""secret2""); Verifier verifier3 = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem"")))); Map verifiers = new HashMap<>(); verifiers.put(""verifier1"", verifier1); verifiers.put(""verifier2"", verifier2); verifiers.put(""verifier3"", verifier3); // decode all of the encoded JWTs and ensure they come out the same. JWT jwt1 = JWT.getDecoder().decode(encodedJWT1, verifiers); JWT jwt2 = JWT.getDecoder().decode(encodedJWT2, verifiers); JWT jwt3 = JWT.getDecoder().decode(encodedJWT3, verifiers); assertEquals(jwt1.subject, jwt2.subject); assertEquals(jwt2.subject, jwt3.subject); } "," public void test_multipleSignersAndVerifiers() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); // Three separate signers Signer signer1 = HMACSigner.newSHA512Signer(""secret1""); Signer signer2 = HMACSigner.newSHA512Signer(""secret2""); Signer signer3 = RSASigner.newSHA256Signer(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_private_key_2048.pem"")))); // Encode the same JWT with each signer, writing the Key ID to the header String encodedJWT1 = JWT.getEncoder().encode(jwt, signer1, h -> h.set(""kid"", ""verifier1"")); String encodedJWT2 = JWT.getEncoder().encode(jwt, signer2, h -> h.set(""kid"", ""verifier2"")); String encodedJWT3 = JWT.getEncoder().encode(jwt, signer3, h -> h.set(""kid"", ""verifier3"")); Verifier verifier1 = HMACVerifier.newVerifier(""secret1""); Verifier verifier2 = HMACVerifier.newVerifier(""secret2""); Verifier verifier3 = RSAVerifier.newVerifier(new String(Files.readAllBytes(Paths.get(""src/test/resources/rsa_public_key_2048.pem"")))); Map verifiers = new HashMap<>(); verifiers.put(""verifier1"", verifier1); verifiers.put(""verifier2"", verifier2); verifiers.put(""verifier3"", verifier3); // decode all of the encoded JWTs and ensure they come out the same. JWT jwt1 = JWT.getDecoder().decode(encodedJWT1, verifiers); JWT jwt2 = JWT.getDecoder().decode(encodedJWT2, verifiers); JWT jwt3 = JWT.getDecoder().decode(encodedJWT3, verifiers); assertEquals(jwt1.subject, jwt2.subject); assertEquals(jwt2.subject, jwt3.subject); } ",FALSE,JWTTest.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)); } ",FALSE,JWTTest.java " public void test_none() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = new UnsecuredSigner(); String encodedJWT = JWT.getEncoder().encode(jwt, signer); assertEquals(encodedJWT, ""eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkifQ.""); JWT actual = JWT.getDecoder().decode(encodedJWT); assertEquals(actual.subject, jwt.subject); } "," public void test_none() throws Exception { JWT jwt = new JWT().setSubject(""123456789""); Signer signer = new UnsecuredSigner(); String encodedJWT = JWT.getEncoder().encode(jwt, signer); assertEquals(encodedJWT, ""eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjM0NTY3ODkifQ.""); JWT actual = JWT.getDecoder().decode(encodedJWT); assertEquals(actual.subject, jwt.subject); } ",FALSE,JWTTest.java " public void test_notBeforeThrows() throws Exception { JWT expectedJWT = new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS)) .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)) .setIssuer(""www.inversoft.com"") .setNotBefore(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).truncatedTo(ChronoUnit.SECONDS)); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer); expectException(JWTUnavailableForProcessingException.class, () -> JWT.getDecoder().decode(encodedJWT, verifier)); } "," public void test_notBeforeThrows() throws Exception { JWT expectedJWT = new JWT() .setExpiration(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS)) .setIssuedAt(ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS)) .setIssuer(""www.inversoft.com"") .setNotBefore(ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(5).truncatedTo(ChronoUnit.SECONDS)); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT = JWT.getEncoder().encode(expectedJWT, signer); expectException(JWTUnavailableForProcessingException.class, () -> JWT.getDecoder().decode(encodedJWT, verifier)); } ",FALSE,JWTTest.java " public void test_zonedDateTime() throws Exception { ZonedDateTime expiration = ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS); JWT expectedJWT = new JWT().setExpiration(expiration); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT1 = JWT.getEncoder().encode(expectedJWT, signer); JWT actualJWT1 = JWT.getDecoder().decode(encodedJWT1, verifier); assertEquals(actualJWT1.expiration, expectedJWT.expiration); } "," public void test_zonedDateTime() throws Exception { ZonedDateTime expiration = ZonedDateTime.now(ZoneOffset.UTC).plusMinutes(60).truncatedTo(ChronoUnit.SECONDS); JWT expectedJWT = new JWT().setExpiration(expiration); Signer signer = HMACSigner.newSHA256Signer(""secret""); Verifier verifier = HMACVerifier.newVerifier(""secret""); String encodedJWT1 = JWT.getEncoder().encode(expectedJWT, signer); JWT actualJWT1 = JWT.getDecoder().decode(encodedJWT1, verifier); assertEquals(actualJWT1.expiration, expectedJWT.expiration); } ",FALSE,JWTTest.java " private void expectException(Class expected, ThrowingRunnable runnable) { try { runnable.run(); fail(""Expected ["" + expected.getCanonicalName() + ""] to be thrown. No Exception was thrown.""); } catch (Exception e) { if (!e.getClass().isAssignableFrom(expected)) { fail(""Expected ["" + expected.getCanonicalName() + ""] to be thrown. Caught this instead ["" + e.getClass().getCanonicalName() + ""]""); } } } "," private void expectException(Class expected, ThrowingRunnable runnable) { try { runnable.run(); fail(""Expected ["" + expected.getCanonicalName() + ""] to be thrown. No Exception was thrown.""); } catch (Exception e) { if (!e.getClass().isAssignableFrom(expected)) { fail(""Expected ["" + expected.getCanonicalName() + ""] to be thrown. Caught this instead ["" + e.getClass().getCanonicalName() + ""]""); } } } ",FALSE,JWTTest.java " public static String getPathWithinApplication(HttpServletRequest request) { String contextPath = getContextPath(request); String requestUri = getRequestUri(request); if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) { // Normal case: URI contains context path. String path = requestUri.substring(contextPath.length()); return (StringUtils.hasText(path) ? path : ""/""); } else { // Special case: rather unusual. return requestUri; } } "," public static String getPathWithinApplication(HttpServletRequest request) { String contextPath = getContextPath(request); String requestUri = getRequestUri(request); if (StringUtils.startsWithIgnoreCase(requestUri, contextPath)) { // Normal case: URI contains context path. String path = requestUri.substring(contextPath.length()); return (StringUtils.hasText(path) ? path : ""/""); } else { // Special case: rather unusual. return requestUri; } } ",FALSE,WebUtils.java " public static String getRequestUri(HttpServletRequest request) { String uri = (String) request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE); if (uri == null) { uri = request.getRequestURI(); } return normalize(decodeAndCleanUriString(request, uri)); } "," public static String getRequestUri(HttpServletRequest request) { String uri = (String) request.getAttribute(INCLUDE_REQUEST_URI_ATTRIBUTE); if (uri == null) { uri = request.getRequestURI(); } return normalize(decodeAndCleanUriString(request, uri)); } ",FALSE,WebUtils.java " public static String normalize(String path) { return normalize(path, true); } "," public static String normalize(String path) { return normalize(path, true); } ",FALSE,WebUtils.java " private static String normalize(String path, boolean replaceBackSlash) { if (path == null) return null; // Create a place for the normalized path String normalized = path; if (replaceBackSlash && normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (normalized.equals(""/."")) return ""/""; // Add a leading ""/"" if necessary if (!normalized.startsWith(""/"")) normalized = ""/"" + normalized; // Resolve occurrences of ""//"" in the normalized path while (true) { int index = normalized.indexOf(""//""); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of ""/./"" in the normalized path while (true) { int index = normalized.indexOf(""/./""); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of ""/../"" in the normalized path while (true) { int index = normalized.indexOf(""/../""); if (index < 0) break; if (index == 0) return (null); // Trying to go outside our context int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Return the normalized path that we have completed return (normalized); } "," private static String normalize(String path, boolean replaceBackSlash) { if (path == null) return null; // Create a place for the normalized path String normalized = path; if (replaceBackSlash && normalized.indexOf('\\') >= 0) normalized = normalized.replace('\\', '/'); if (normalized.equals(""/."")) return ""/""; // Add a leading ""/"" if necessary if (!normalized.startsWith(""/"")) normalized = ""/"" + normalized; // Resolve occurrences of ""//"" in the normalized path while (true) { int index = normalized.indexOf(""//""); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 1); } // Resolve occurrences of ""/./"" in the normalized path while (true) { int index = normalized.indexOf(""/./""); if (index < 0) break; normalized = normalized.substring(0, index) + normalized.substring(index + 2); } // Resolve occurrences of ""/../"" in the normalized path while (true) { int index = normalized.indexOf(""/../""); if (index < 0) break; if (index == 0) return (null); // Trying to go outside our context int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } // Return the normalized path that we have completed return (normalized); } ",FALSE,WebUtils.java " private static String decodeAndCleanUriString(HttpServletRequest request, String uri) { uri = decodeRequestString(request, uri); int semicolonIndex = uri.indexOf(';'); return (semicolonIndex != -1 ? uri.substring(0, semicolonIndex) : uri); } "," private static String decodeAndCleanUriString(HttpServletRequest request, String uri) { uri = decodeRequestString(request, uri); int semicolonIndex = uri.indexOf(';'); return (semicolonIndex != -1 ? uri.substring(0, semicolonIndex) : uri); } ",FALSE,WebUtils.java " public static String getContextPath(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); if (contextPath == null) { contextPath = request.getContextPath(); } if (""/"".equals(contextPath)) { // Invalid case, but happens for includes on Jetty: silently adapt it. contextPath = """"; } return decodeRequestString(request, contextPath); } "," public static String getContextPath(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); if (contextPath == null) { contextPath = request.getContextPath(); } contextPath = normalize(decodeRequestString(request, contextPath)); if (""/"".equals(contextPath)) { // the normalize method will return a ""/"" and includes on Jetty, will also be a ""/"". contextPath = """"; } return contextPath; } ",TRUE,WebUtils.java " public static WebEnvironment getRequiredWebEnvironment(ServletContext sc) throws IllegalStateException { WebEnvironment we = getWebEnvironment(sc); if (we == null) { throw new IllegalStateException(""No WebEnvironment found: no EnvironmentLoaderListener registered?""); } return we; } "," public static WebEnvironment getRequiredWebEnvironment(ServletContext sc) throws IllegalStateException { WebEnvironment we = getWebEnvironment(sc); if (we == null) { throw new IllegalStateException(""No WebEnvironment found: no EnvironmentLoaderListener registered?""); } return we; } ",FALSE,WebUtils.java " public static WebEnvironment getWebEnvironment(ServletContext sc) { return getWebEnvironment(sc, EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY); } "," public static WebEnvironment getWebEnvironment(ServletContext sc) { return getWebEnvironment(sc, EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY); } ",FALSE,WebUtils.java " public static WebEnvironment getWebEnvironment(ServletContext sc, String attrName) { if (sc == null) { throw new IllegalArgumentException(""ServletContext argument must not be null.""); } Object attr = sc.getAttribute(attrName); if (attr == null) { return null; } if (attr instanceof RuntimeException) { throw (RuntimeException) attr; } if (attr instanceof Error) { throw (Error) attr; } if (attr instanceof Exception) { throw new IllegalStateException((Exception) attr); } if (!(attr instanceof WebEnvironment)) { throw new IllegalStateException(""Context attribute is not of type WebEnvironment: "" + attr); } return (WebEnvironment) attr; } "," public static WebEnvironment getWebEnvironment(ServletContext sc, String attrName) { if (sc == null) { throw new IllegalArgumentException(""ServletContext argument must not be null.""); } Object attr = sc.getAttribute(attrName); if (attr == null) { return null; } if (attr instanceof RuntimeException) { throw (RuntimeException) attr; } if (attr instanceof Error) { throw (Error) attr; } if (attr instanceof Exception) { throw new IllegalStateException((Exception) attr); } if (!(attr instanceof WebEnvironment)) { throw new IllegalStateException(""Context attribute is not of type WebEnvironment: "" + attr); } return (WebEnvironment) attr; } ",FALSE,WebUtils.java " public static String decodeRequestString(HttpServletRequest request, String source) { String enc = determineEncoding(request); try { return URLDecoder.decode(source, enc); } catch (UnsupportedEncodingException ex) { if (log.isWarnEnabled()) { log.warn(""Could not decode request string ["" + source + ""] with encoding '"" + enc + ""': falling back to platform default encoding; exception message: "" + ex.getMessage()); } return URLDecoder.decode(source); } } "," public static String decodeRequestString(HttpServletRequest request, String source) { String enc = determineEncoding(request); try { return URLDecoder.decode(source, enc); } catch (UnsupportedEncodingException ex) { if (log.isWarnEnabled()) { log.warn(""Could not decode request string ["" + source + ""] with encoding '"" + enc + ""': falling back to platform default encoding; exception message: "" + ex.getMessage()); } return URLDecoder.decode(source); } } ",FALSE,WebUtils.java " protected static String determineEncoding(HttpServletRequest request) { String enc = request.getCharacterEncoding(); if (enc == null) { enc = DEFAULT_CHARACTER_ENCODING; } return enc; } "," protected static String determineEncoding(HttpServletRequest request) { String enc = request.getCharacterEncoding(); if (enc == null) { enc = DEFAULT_CHARACTER_ENCODING; } return enc; } ",FALSE,WebUtils.java " public static boolean isWeb(Object requestPairSource) { return requestPairSource instanceof RequestPairSource && isWeb((RequestPairSource) requestPairSource); } "," public static boolean isWeb(Object requestPairSource) { return requestPairSource instanceof RequestPairSource && isWeb((RequestPairSource) requestPairSource); } ",FALSE,WebUtils.java " public static boolean isHttp(Object requestPairSource) { return requestPairSource instanceof RequestPairSource && isHttp((RequestPairSource) requestPairSource); } "," public static boolean isHttp(Object requestPairSource) { return requestPairSource instanceof RequestPairSource && isHttp((RequestPairSource) requestPairSource); } ",FALSE,WebUtils.java " public static ServletRequest getRequest(Object requestPairSource) { if (requestPairSource instanceof RequestPairSource) { return ((RequestPairSource) requestPairSource).getServletRequest(); } return null; } "," public static ServletRequest getRequest(Object requestPairSource) { if (requestPairSource instanceof RequestPairSource) { return ((RequestPairSource) requestPairSource).getServletRequest(); } return null; } ",FALSE,WebUtils.java " public static ServletResponse getResponse(Object requestPairSource) { if (requestPairSource instanceof RequestPairSource) { return ((RequestPairSource) requestPairSource).getServletResponse(); } return null; } "," public static ServletResponse getResponse(Object requestPairSource) { if (requestPairSource instanceof RequestPairSource) { return ((RequestPairSource) requestPairSource).getServletResponse(); } return null; } ",FALSE,WebUtils.java " public static HttpServletRequest getHttpRequest(Object requestPairSource) { ServletRequest request = getRequest(requestPairSource); if (request instanceof HttpServletRequest) { return (HttpServletRequest) request; } return null; } "," public static HttpServletRequest getHttpRequest(Object requestPairSource) { ServletRequest request = getRequest(requestPairSource); if (request instanceof HttpServletRequest) { return (HttpServletRequest) request; } return null; } ",FALSE,WebUtils.java " public static HttpServletResponse getHttpResponse(Object requestPairSource) { ServletResponse response = getResponse(requestPairSource); if (response instanceof HttpServletResponse) { return (HttpServletResponse) response; } return null; } "," public static HttpServletResponse getHttpResponse(Object requestPairSource) { ServletResponse response = getResponse(requestPairSource); if (response instanceof HttpServletResponse) { return (HttpServletResponse) response; } return null; } ",FALSE,WebUtils.java " private static boolean isWeb(RequestPairSource source) { ServletRequest request = source.getServletRequest(); ServletResponse response = source.getServletResponse(); return request != null && response != null; } "," private static boolean isWeb(RequestPairSource source) { ServletRequest request = source.getServletRequest(); ServletResponse response = source.getServletResponse(); return request != null && response != null; } ",FALSE,WebUtils.java " private static boolean isHttp(RequestPairSource source) { ServletRequest request = source.getServletRequest(); ServletResponse response = source.getServletResponse(); return request instanceof HttpServletRequest && response instanceof HttpServletResponse; } "," private static boolean isHttp(RequestPairSource source) { ServletRequest request = source.getServletRequest(); ServletResponse response = source.getServletResponse(); return request instanceof HttpServletRequest && response instanceof HttpServletResponse; } ",FALSE,WebUtils.java " public static boolean _isSessionCreationEnabled(Object requestPairSource) { if (requestPairSource instanceof RequestPairSource) { RequestPairSource source = (RequestPairSource) requestPairSource; return _isSessionCreationEnabled(source.getServletRequest()); } return true; //by default } "," public static boolean _isSessionCreationEnabled(Object requestPairSource) { if (requestPairSource instanceof RequestPairSource) { RequestPairSource source = (RequestPairSource) requestPairSource; return _isSessionCreationEnabled(source.getServletRequest()); } return true; //by default } ",FALSE,WebUtils.java " public static boolean _isSessionCreationEnabled(ServletRequest request) { if (request != null) { Object val = request.getAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED); if (val != null && val instanceof Boolean) { return (Boolean) val; } } return true; //by default } "," public static boolean _isSessionCreationEnabled(ServletRequest request) { if (request != null) { Object val = request.getAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED); if (val != null && val instanceof Boolean) { return (Boolean) val; } } return true; //by default } ",FALSE,WebUtils.java " public static HttpServletRequest toHttp(ServletRequest request) { return (HttpServletRequest) request; } "," public static HttpServletRequest toHttp(ServletRequest request) { return (HttpServletRequest) request; } ",FALSE,WebUtils.java " public static HttpServletResponse toHttp(ServletResponse response) { return (HttpServletResponse) response; } "," public static HttpServletResponse toHttp(ServletResponse response) { return (HttpServletResponse) response; } ",FALSE,WebUtils.java " public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams, boolean contextRelative, boolean http10Compatible) throws IOException { RedirectView view = new RedirectView(url, contextRelative, http10Compatible); view.renderMergedOutputModel(queryParams, toHttp(request), toHttp(response)); } "," public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams, boolean contextRelative, boolean http10Compatible) throws IOException { RedirectView view = new RedirectView(url, contextRelative, http10Compatible); view.renderMergedOutputModel(queryParams, toHttp(request), toHttp(response)); } ",FALSE,WebUtils.java " public static void issueRedirect(ServletRequest request, ServletResponse response, String url) throws IOException { issueRedirect(request, response, url, null, true, true); } "," public static void issueRedirect(ServletRequest request, ServletResponse response, String url) throws IOException { issueRedirect(request, response, url, null, true, true); } ",FALSE,WebUtils.java " public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams) throws IOException { issueRedirect(request, response, url, queryParams, true, true); } "," public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams) throws IOException { issueRedirect(request, response, url, queryParams, true, true); } ",FALSE,WebUtils.java " public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams, boolean contextRelative) throws IOException { issueRedirect(request, response, url, queryParams, contextRelative, true); } "," public static void issueRedirect(ServletRequest request, ServletResponse response, String url, Map queryParams, boolean contextRelative) throws IOException { issueRedirect(request, response, url, queryParams, contextRelative, true); } ",FALSE,WebUtils.java " public static boolean isTrue(ServletRequest request, String paramName) { String value = getCleanParam(request, paramName); return value != null && (value.equalsIgnoreCase(""true"") || value.equalsIgnoreCase(""t"") || value.equalsIgnoreCase(""1"") || value.equalsIgnoreCase(""enabled"") || value.equalsIgnoreCase(""y"") || value.equalsIgnoreCase(""yes"") || value.equalsIgnoreCase(""on"")); } "," public static boolean isTrue(ServletRequest request, String paramName) { String value = getCleanParam(request, paramName); return value != null && (value.equalsIgnoreCase(""true"") || value.equalsIgnoreCase(""t"") || value.equalsIgnoreCase(""1"") || value.equalsIgnoreCase(""enabled"") || value.equalsIgnoreCase(""y"") || value.equalsIgnoreCase(""yes"") || value.equalsIgnoreCase(""on"")); } ",FALSE,WebUtils.java " public static String getCleanParam(ServletRequest request, String paramName) { return StringUtils.clean(request.getParameter(paramName)); } "," public static String getCleanParam(ServletRequest request, String paramName) { return StringUtils.clean(request.getParameter(paramName)); } ",FALSE,WebUtils.java " public static void saveRequest(ServletRequest request) { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); HttpServletRequest httpRequest = toHttp(request); SavedRequest savedRequest = new SavedRequest(httpRequest); session.setAttribute(SAVED_REQUEST_KEY, savedRequest); } "," public static void saveRequest(ServletRequest request) { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); HttpServletRequest httpRequest = toHttp(request); SavedRequest savedRequest = new SavedRequest(httpRequest); session.setAttribute(SAVED_REQUEST_KEY, savedRequest); } ",FALSE,WebUtils.java " public static SavedRequest getAndClearSavedRequest(ServletRequest request) { SavedRequest savedRequest = getSavedRequest(request); if (savedRequest != null) { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); session.removeAttribute(SAVED_REQUEST_KEY); } return savedRequest; } "," public static SavedRequest getAndClearSavedRequest(ServletRequest request) { SavedRequest savedRequest = getSavedRequest(request); if (savedRequest != null) { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); session.removeAttribute(SAVED_REQUEST_KEY); } return savedRequest; } ",FALSE,WebUtils.java " public static SavedRequest getSavedRequest(ServletRequest request) { SavedRequest savedRequest = null; Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session != null) { savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST_KEY); } return savedRequest; } "," public static SavedRequest getSavedRequest(ServletRequest request) { SavedRequest savedRequest = null; Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session != null) { savedRequest = (SavedRequest) session.getAttribute(SAVED_REQUEST_KEY); } return savedRequest; } ",FALSE,WebUtils.java " public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl) throws IOException { String successUrl = null; boolean contextRelative = true; SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request); if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) { successUrl = savedRequest.getRequestUrl(); contextRelative = false; } if (successUrl == null) { successUrl = fallbackUrl; } if (successUrl == null) { throw new IllegalStateException(""Success URL not available via saved request or via the "" + ""successUrlFallback method parameter. One of these must be non-null for "" + ""issueSuccessRedirect() to work.""); } WebUtils.issueRedirect(request, response, successUrl, null, contextRelative); } "," public static void redirectToSavedRequest(ServletRequest request, ServletResponse response, String fallbackUrl) throws IOException { String successUrl = null; boolean contextRelative = true; SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request); if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) { successUrl = savedRequest.getRequestUrl(); contextRelative = false; } if (successUrl == null) { successUrl = fallbackUrl; } if (successUrl == null) { throw new IllegalStateException(""Success URL not available via saved request or via the "" + ""successUrlFallback method parameter. One of these must be non-null for "" + ""issueSuccessRedirect() to work.""); } WebUtils.issueRedirect(request, response, successUrl, null, contextRelative); } ",FALSE,WebUtils.java " public Set getSupportedTypes(ParseContext context) { return SUPPORTED_TYPES; } "," public Set getSupportedTypes(ParseContext context) { return SUPPORTED_TYPES; } ",FALSE,IptcAnpaParser.java " public void parse( InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { HashMap properties = this.loadProperties(stream); this.setMetadata(metadata, properties); XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); // TODO: put body content here xhtml.startElement(""p""); String body = clean(properties.get(""body"")); if (body != null) xhtml.characters(body); xhtml.endElement(""p""); xhtml.endDocument(); } "," public void parse( InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { HashMap properties = this.loadProperties(stream); this.setMetadata(metadata, properties); XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); // TODO: put body content here xhtml.startElement(""p""); String body = clean(properties.get(""body"")); if (body != null) xhtml.characters(body); xhtml.endElement(""p""); xhtml.endDocument(); } ",FALSE,IptcAnpaParser.java " public void parse( InputStream stream, ContentHandler handler, Metadata metadata) throws IOException, SAXException, TikaException { parse(stream, handler, metadata, new ParseContext()); } "," public void parse( InputStream stream, ContentHandler handler, Metadata metadata) throws IOException, SAXException, TikaException { parse(stream, handler, metadata, new ParseContext()); } ",FALSE,IptcAnpaParser.java " private HashMap loadProperties(InputStream is) { HashMap properties = new HashMap(); FORMAT = this.scanFormat(is); byte[] residual = this.getSection(is,""residual""); byte[] header = this.getSection(is,""header""); parseHeader(header, properties); byte[] body = this.getSection(is,""body""); parseBody(body, properties); byte[] footer = this.getSection(is,""footer""); parseFooter(footer, properties); return (properties); } "," private HashMap loadProperties(InputStream is) { HashMap properties = new HashMap(); FORMAT = this.scanFormat(is); byte[] residual = this.getSection(is,""residual""); byte[] header = this.getSection(is,""header""); parseHeader(header, properties); byte[] body = this.getSection(is,""body""); parseBody(body, properties); byte[] footer = this.getSection(is,""footer""); parseFooter(footer, properties); return (properties); } ",FALSE,IptcAnpaParser.java " private int scanFormat(InputStream is) { int format = this.FORMAT; int maxsize = 524288; // 512K byte[] buf = new byte[maxsize]; try { if (is.markSupported()) { is.mark(maxsize); } int msgsize = is.read(buf); // read in at least the full data String message = (new String(buf, UTF_8)).toLowerCase(Locale.ROOT); // these are not if-then-else, because we want to go from most common // and fall through to least. this is imperfect, as these tags could // show up in other agency stories, but i can't find a spec or any // explicit codes to identify the wire source in the message itself if (message.contains(""ap-wf"")) { format = this.FMT_IPTC_AP; } if (message.contains(""reuters"")) { format = this.FMT_IPTC_RTR; } if (message.contains(""new york times"")) { format = this.FMT_IPTC_NYT; } if (message.contains(""bloomberg news"")) { format = this.FMT_IPTC_BLM; } } catch (IOException eio) { // we are in an unstable state } try { if (is.markSupported()) { is.reset(); } } catch (IOException eio) { // we are in an unstable state } return (format); } "," private int scanFormat(InputStream is) { int format = this.FORMAT; int maxsize = 524288; // 512K byte[] buf = new byte[maxsize]; try { if (is.markSupported()) { is.mark(maxsize); } int msgsize = is.read(buf); // read in at least the full data String message = (new String(buf, UTF_8)).toLowerCase(Locale.ROOT); // these are not if-then-else, because we want to go from most common // and fall through to least. this is imperfect, as these tags could // show up in other agency stories, but i can't find a spec or any // explicit codes to identify the wire source in the message itself if (message.contains(""ap-wf"")) { format = this.FMT_IPTC_AP; } if (message.contains(""reuters"")) { format = this.FMT_IPTC_RTR; } if (message.contains(""new york times"")) { format = this.FMT_IPTC_NYT; } if (message.contains(""bloomberg news"")) { format = this.FMT_IPTC_BLM; } } catch (IOException eio) { // we are in an unstable state } try { if (is.markSupported()) { is.reset(); } } catch (IOException eio) { // we are in an unstable state } return (format); } ",FALSE,IptcAnpaParser.java " private void setFormat(int format) { this.FORMAT = format; } "," private void setFormat(int format) { this.FORMAT = format; } ",FALSE,IptcAnpaParser.java " private String getFormatName() { String name = """"; if (FORMAT == this.FMT_IPTC_AP) { name = ""Associated Press""; } else if(FORMAT == this.FMT_IPTC_BLM) { name = ""Bloomberg""; } else if(FORMAT == this.FMT_IPTC_NYT) { name = ""New York Times""; } else if(FORMAT == this.FMT_IPTC_RTR) { name = ""Reuters""; } return (name); } "," private String getFormatName() { String name = """"; if (FORMAT == this.FMT_IPTC_AP) { name = ""Associated Press""; } else if(FORMAT == this.FMT_IPTC_BLM) { name = ""Bloomberg""; } else if(FORMAT == this.FMT_IPTC_NYT) { name = ""New York Times""; } else if(FORMAT == this.FMT_IPTC_RTR) { name = ""Reuters""; } return (name); } ",FALSE,IptcAnpaParser.java " private byte[] getSection(InputStream is, String name) { byte[] value = new byte[0]; if (name.equals(""residual"")) { // the header shouldn't be more than 1k, but just being generous here int maxsize = 8192; // 8K byte bstart = SYN; // check for SYN [0x16 : ctrl-v] (may have leftover residue from preceding message) byte bfinish = SOH; // check for SOH [0x01 : ctrl-a] (typically follows a pair of SYN [0x16 : ctrl-v]) value = getSection(is, maxsize, bstart, bfinish, true); } else if(name.equals(""header"")) { // the header shouldn't be more than 1k, but just being generous here int maxsize = 8192; // 8K byte bstart = SOH; // check for SOH [0x01 : ctrl-a] (typically follows a pair of SYN [0x16 : ctrl-v]) byte bfinish = STX; // check for STX [0x02 : ctrl-b] (marks end of header, beginning of message) value = getSection(is, maxsize, bstart, bfinish, true); } else if (name.equals(""body"")) { // the message shouldn't be more than 16k (?), leaving plenty of space int maxsize = 524288; // 512K byte bstart = STX; // check for STX [0x02 : ctrl-b] (marks end of header, beginning of message) byte bfinish = ETX; // check for ETX [0x03 : ctrl-c] (marks end of message, beginning of footer) value = getSection(is, maxsize, bstart, bfinish, true); } else if (name.equals(""footer"")) { // the footer shouldn't be more than 1k , leaving plenty of space int maxsize = 8192; // 8K byte bstart = ETX; // check for ETX [0x03 : ctrl-c] (marks end of message, beginning of footer) byte bfinish = EOT; // check for EOT [0x04 : ctrl-d] (marks end of transmission) value = getSection(is, maxsize, bstart, bfinish, true); } return (value); } "," private byte[] getSection(InputStream is, String name) { byte[] value = new byte[0]; if (name.equals(""residual"")) { // the header shouldn't be more than 1k, but just being generous here int maxsize = 8192; // 8K byte bstart = SYN; // check for SYN [0x16 : ctrl-v] (may have leftover residue from preceding message) byte bfinish = SOH; // check for SOH [0x01 : ctrl-a] (typically follows a pair of SYN [0x16 : ctrl-v]) value = getSection(is, maxsize, bstart, bfinish, true); } else if(name.equals(""header"")) { // the header shouldn't be more than 1k, but just being generous here int maxsize = 8192; // 8K byte bstart = SOH; // check for SOH [0x01 : ctrl-a] (typically follows a pair of SYN [0x16 : ctrl-v]) byte bfinish = STX; // check for STX [0x02 : ctrl-b] (marks end of header, beginning of message) value = getSection(is, maxsize, bstart, bfinish, true); } else if (name.equals(""body"")) { // the message shouldn't be more than 16k (?), leaving plenty of space int maxsize = 524288; // 512K byte bstart = STX; // check for STX [0x02 : ctrl-b] (marks end of header, beginning of message) byte bfinish = ETX; // check for ETX [0x03 : ctrl-c] (marks end of message, beginning of footer) value = getSection(is, maxsize, bstart, bfinish, true); } else if (name.equals(""footer"")) { // the footer shouldn't be more than 1k , leaving plenty of space int maxsize = 8192; // 8K byte bstart = ETX; // check for ETX [0x03 : ctrl-c] (marks end of message, beginning of footer) byte bfinish = EOT; // check for EOT [0x04 : ctrl-d] (marks end of transmission) value = getSection(is, maxsize, bstart, bfinish, true); } return (value); } ",FALSE,IptcAnpaParser.java " private byte[] getSection(InputStream is, int maxsize, byte bstart, byte bfinish, boolean ifincomplete) { byte[] value = new byte[0]; try { boolean started = false; // check if we have found the start flag boolean finished = false; // check if we have found the finish flag int read = 0; // the number of bytes we read int start = 0; // the position after the start flag // TODO: this only pulls back 8K of data on a read, regardless of buffer size // more nefariously, it caps at a total 8K, through all sections int streammax = is.available(); maxsize = Math.min(maxsize, streammax); is.mark(maxsize); byte[] buf = new byte[maxsize]; int totsize = 0; int remainder = maxsize - totsize; while (remainder > 0) { int msgsize = is.read(buf, maxsize-remainder, maxsize); // read in at least the full data if (msgsize == -1) { remainder = msgsize = 0; } remainder -= msgsize; totsize += msgsize; } // scan through the provided input stream for (read=0; read < totsize; read++) { byte b = buf[read]; if (!started) { started = (b == bstart); start = read + 1; continue; } if (finished = (b == bfinish)) { /* is.reset(); long skipped = is.skip((long)read); if (skipped != read) { // we are in an unstable state } is.mark(1); */ break; } // load from the stream until we run out of characters, or hit the termination byte continue; } // move the input stream back to where it was initially is.reset(); if (finished) { // now, we want to reset the stream to be sitting right on top of the finish marker is.skip(read); value = new byte[read-start]; System.arraycopy(buf, start, value, 0, read-start); } else { if (ifincomplete && started) { // the caller wants anything that was read, and we finished the stream or buffer value = new byte[read-start]; System.arraycopy(buf, start, value, 0, read-start); } } } catch (IOException eio) { // something invalid occurred, return an empty string } return (value); } "," private byte[] getSection(InputStream is, int maxsize, byte bstart, byte bfinish, boolean ifincomplete) { byte[] value = new byte[0]; try { boolean started = false; // check if we have found the start flag boolean finished = false; // check if we have found the finish flag int read = 0; // the number of bytes we read int start = 0; // the position after the start flag // TODO: this only pulls back 8K of data on a read, regardless of buffer size // more nefariously, it caps at a total 8K, through all sections int streammax = is.available(); maxsize = Math.min(maxsize, streammax); is.mark(maxsize); byte[] buf = new byte[maxsize]; int totsize = 0; int remainder = maxsize - totsize; while (remainder > 0) { int msgsize = is.read(buf, maxsize-remainder, maxsize); // read in at least the full data if (msgsize == -1) { remainder = msgsize = 0; } remainder -= msgsize; totsize += msgsize; } // scan through the provided input stream for (read=0; read < totsize; read++) { byte b = buf[read]; if (!started) { started = (b == bstart); start = read + 1; continue; } if (finished = (b == bfinish)) { /* is.reset(); long skipped = is.skip((long)read); if (skipped != read) { // we are in an unstable state } is.mark(1); */ break; } // load from the stream until we run out of characters, or hit the termination byte continue; } // move the input stream back to where it was initially is.reset(); if (finished) { // now, we want to reset the stream to be sitting right on top of the finish marker is.skip(read); value = new byte[read-start]; System.arraycopy(buf, start, value, 0, read-start); } else { if (ifincomplete && started) { // the caller wants anything that was read, and we finished the stream or buffer value = new byte[read-start]; System.arraycopy(buf, start, value, 0, read-start); } } } catch (IOException eio) { // something invalid occurred, return an empty string } return (value); } ",FALSE,IptcAnpaParser.java " private boolean parseHeader(byte[] value, HashMap properties) { boolean added = false; String env_serviceid = """"; String env_category = """"; String env_urgency = """"; String hdr_edcode = """"; String hdr_subject = """"; String hdr_date = """"; String hdr_time = """"; int read = 0; while (read < value.length) { // pull apart the envelope, getting the service id (....\x1f) while (read < value.length) { byte val_next = value[read++]; if (val_next != FS) { env_serviceid += (char)(val_next & 0xff); // convert the byte to an unsigned int } else { break; } } // pull apart the envelope, getting the category (....\x13\x11) while (read < value.length) { byte val_next = value[read++]; if (val_next != XS) { // the end of the envelope is marked (\x13) env_category += (char)(val_next & 0xff); // convert the byte to an unsigned int } else { val_next = value[read]; // get the remaining byte (\x11) if (val_next == XQ) { read++; } break; } } // pull apart the envelope, getting the subject heading while (read < value.length) { boolean subject = true; byte val_next = value[read++]; while ((subject) && (val_next != SP) && (val_next != 0x00)) { // ignore the envelope subject hdr_subject += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; while (val_next == SP) { // consume all the spaces subject = false; val_next = (read < value.length) ? value[read++] : 0x00; if (val_next != SP) { --read; // otherwise we eat into the next section } } } if (!subject) { break; } } // pull apart the envelope, getting the date and time while (read < value.length) { byte val_next = value[read++]; if (hdr_date.length() == 0) { while (((val_next >= (byte)0x30) && (val_next <= (byte)0x39)) // consume all numerics and hyphens || (val_next == HY)) { hdr_date += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; } } else if (val_next == SP) { while (val_next == SP) { // consume all the spaces val_next = (read < value.length) ? value[read++] : 0x00; } continue; } else { while (((val_next >= (byte)0x30) && (val_next <= (byte)0x39)) // consume all numerics and hyphens || (val_next == HY)) { hdr_time += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; } } } break; // don't let this run back through and start thrashing metadata } // if we were saving any of these values, we would set the properties map here added = (env_serviceid.length() + env_category.length() + hdr_subject.length() + hdr_date.length() + hdr_time.length()) > 0; return added; } "," private boolean parseHeader(byte[] value, HashMap properties) { boolean added = false; String env_serviceid = """"; String env_category = """"; String env_urgency = """"; String hdr_edcode = """"; String hdr_subject = """"; String hdr_date = """"; String hdr_time = """"; int read = 0; while (read < value.length) { // pull apart the envelope, getting the service id (....\x1f) while (read < value.length) { byte val_next = value[read++]; if (val_next != FS) { env_serviceid += (char)(val_next & 0xff); // convert the byte to an unsigned int } else { break; } } // pull apart the envelope, getting the category (....\x13\x11) while (read < value.length) { byte val_next = value[read++]; if (val_next != XS) { // the end of the envelope is marked (\x13) env_category += (char)(val_next & 0xff); // convert the byte to an unsigned int } else { val_next = value[read]; // get the remaining byte (\x11) if (val_next == XQ) { read++; } break; } } // pull apart the envelope, getting the subject heading while (read < value.length) { boolean subject = true; byte val_next = value[read++]; while ((subject) && (val_next != SP) && (val_next != 0x00)) { // ignore the envelope subject hdr_subject += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; while (val_next == SP) { // consume all the spaces subject = false; val_next = (read < value.length) ? value[read++] : 0x00; if (val_next != SP) { --read; // otherwise we eat into the next section } } } if (!subject) { break; } } // pull apart the envelope, getting the date and time while (read < value.length) { byte val_next = value[read++]; if (hdr_date.length() == 0) { while (((val_next >= (byte)0x30) && (val_next <= (byte)0x39)) // consume all numerics and hyphens || (val_next == HY)) { hdr_date += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; } } else if (val_next == SP) { while (val_next == SP) { // consume all the spaces val_next = (read < value.length) ? value[read++] : 0x00; } continue; } else { while (((val_next >= (byte)0x30) && (val_next <= (byte)0x39)) // consume all numerics and hyphens || (val_next == HY)) { hdr_time += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; } } } break; // don't let this run back through and start thrashing metadata } // if we were saving any of these values, we would set the properties map here added = (env_serviceid.length() + env_category.length() + hdr_subject.length() + hdr_date.length() + hdr_time.length()) > 0; return added; } ",FALSE,IptcAnpaParser.java " private boolean parseBody(byte[] value, HashMap properties) { boolean added = false; String bdy_heading = """"; String bdy_title = """"; String bdy_source = """"; String bdy_author = """"; String bdy_body = """"; int read = 0; boolean done = false; while (!done && (read < value.length)) { // pull apart the body, getting the heading (^....\x0d\x0a) while (read < value.length) { byte val_next = value[read++]; if (val_next == CT) { // start of a new section , first is the heading val_next = (read < value.length) ? value[read++] : 0x00; // AP, NYT, and Bloomberg end with < , Reuters with EOL while ((val_next != LT) && (val_next != CR) && (val_next != LF)) { // less than delimiter (\x3c) and not EOL bdy_heading += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read > value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } while (bdy_heading.length() > 0 && ((val_next == CR) || (val_next == LF))) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } } else { // this will only be hit on poorly-formed files // for reuters, the heading does not start with the ^, so we push one back into the stream if (FORMAT == this.FMT_IPTC_RTR) { if (val_next != CT) { // for any non-whitespace, we need to go back an additional step to non destroy the data if ((val_next != SP) && (val_next != TB) && (val_next != CR) && (val_next != LF)) { // if the very first byte is data, we have to shift the whole array, and stuff in a carat if (read == 1) { byte[] resize = new byte[value.length + 1]; System.arraycopy(value, 0, resize, 1, value.length); value = resize; } } value[--read] = CT; continue; } } } break; } // pull apart the body, getting the title (^....\x0d\x0a) while (read < value.length) { byte val_next = value[read++]; if (val_next == CT) { // start of a new section , first is the heading val_next = (read < value.length) ? value[read++] : 0x00; // AP, NYT, and Bloomberg end with < , Reuters with EOL while ((val_next != LT) && (val_next != CT) && (val_next != CR) && (val_next != LF)) { // less than delimiter (\x3c), or carat (\x5e) and not EOL bdy_title += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read > value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == CT) { // start of a new section , when first didn't finish cleanly --read; } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } while (bdy_title.length() > 0 && ((val_next == CR) || (val_next == LF))) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } } else { // this will only be hit on poorly-formed files // for bloomberg, the title does not start with the ^, so we push one back into the stream if (FORMAT == this.FMT_IPTC_BLM) { if (val_next == TB) { value[--read] = CT; continue; } } // for reuters, the title does not start with the ^, so we push one back into the stream if (FORMAT == this.FMT_IPTC_RTR) { if (val_next != CT) { // for any non-whitespace, we need to go back an additional step to non destroy the data if ((val_next != SP) && (val_next != TB) && (val_next != CR) && (val_next != LF)) { --read; } value[--read] = CT; continue; } } } break; } // at this point, we have a variable number of metadata lines, with various orders // we scan the start of each line for the special character, and run to the end character // pull apart the body, getting the title (^....\x0d\x0a) boolean metastarted = false; String longline = """"; String longkey = """"; while (read < value.length) { byte val_next = value[read++]; // eat up whitespace before committing to the next section if ((val_next == SP) || (val_next == TB) || (val_next == CR) || (val_next == LF)) { continue; } if (val_next == CT) { // start of a new section , could be authors, sources, etc val_next = (read < value.length) ? value[read++] : 0x00; String tmp_line = """"; while ((val_next != LT) && (val_next != CT) && (val_next != CR) && (val_next != LF) && (val_next != 0)) { // less than delimiter (\x3c), maybe also badly formed with just new line tmp_line += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read > value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == CT) { // start of a new section , when first didn't finish cleanly --read; } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } while ((val_next == CR) || (val_next == LF)) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } if (tmp_line.toLowerCase(Locale.ROOT).startsWith(""by"") || longline.equals(""bdy_author"")) { longkey = ""bdy_author""; // prepend a space to subsequent line, so it gets parsed consistent with the lead line tmp_line = (longline.equals(longkey) ? "" "" : """") + tmp_line; // we have an author candidate int term = tmp_line.length(); term = Math.min(term, (tmp_line.contains(""<"") ? tmp_line.indexOf(""<"") : term)); term = Math.min(term, (tmp_line.contains(""="") ? tmp_line.indexOf(""="") : term)); term = Math.min(term, (tmp_line.contains(""\n"") ? tmp_line.indexOf(""\n"") : term)); term = (term > 0 ) ? term : tmp_line.length(); bdy_author += tmp_line.substring(tmp_line.indexOf("" ""), term); metastarted = true; longline = ((tmp_line.contains(""="")) && (!longline.equals(longkey)) ? longkey : """"); } else if (FORMAT == this.FMT_IPTC_BLM) { String byline = "" by ""; if (tmp_line.toLowerCase(Locale.ROOT).contains(byline)) { longkey = ""bdy_author""; int term = tmp_line.length(); term = Math.min(term, (tmp_line.contains(""<"") ? tmp_line.indexOf(""<"") : term)); term = Math.min(term, (tmp_line.contains(""="") ? tmp_line.indexOf(""="") : term)); term = Math.min(term, (tmp_line.contains(""\n"") ? tmp_line.indexOf(""\n"") : term)); term = (term > 0 ) ? term : tmp_line.length(); // for bloomberg, the author line sits below their copyright statement bdy_author += tmp_line.substring(tmp_line.toLowerCase(Locale.ROOT).indexOf(byline) + byline.length(), term) + "" ""; metastarted = true; longline = ((tmp_line.contains(""="")) && (!longline.equals(longkey)) ? longkey : """"); } else if(tmp_line.toLowerCase(Locale.ROOT).startsWith(""c."")) { // the author line for bloomberg is a multiline starting with c.2011 Bloomberg News // then containing the author info on the next line if (val_next == TB) { value[--read] = CT; continue; } } else if(tmp_line.toLowerCase(Locale.ROOT).trim().startsWith(""("") && tmp_line.toLowerCase(Locale.ROOT).trim().endsWith("")"")) { // the author line may have one or more comment lines between the copyright // statement, and the By AUTHORNAME line if (val_next == TB) { value[--read] = CT; continue; } } } else if (tmp_line.toLowerCase(Locale.ROOT).startsWith(""eds"") || longline.equals(""bdy_source"")) { longkey = ""bdy_source""; // prepend a space to subsequent line, so it gets parsed consistent with the lead line tmp_line = (longline.equals(longkey) ? "" "" : """") + tmp_line; // we have a source candidate int term = tmp_line.length(); term = Math.min(term, (tmp_line.contains(""<"") ? tmp_line.indexOf(""<"") : term)); term = Math.min(term, (tmp_line.contains(""="") ? tmp_line.indexOf(""="") : term)); // term = Math.min(term, (tmp_line.indexOf(""\n"") > -1 ? tmp_line.indexOf(""\n"") : term)); term = (term > 0 ) ? term : tmp_line.length(); bdy_source += tmp_line.substring(tmp_line.indexOf("" "") + 1, term) + "" ""; metastarted = true; longline = (!longline.equals(longkey) ? longkey : """"); } else { // this has fallen all the way through. trap it as part of the subject, // rather than just losing it if (!metastarted) { bdy_title += "" , "" + tmp_line; // not sure where else to put this but in the title } else { // what to do with stuff that is metadata, which falls after metadata lines started? bdy_body += "" "" + tmp_line + "" , ""; // not sure where else to put this but in the title } } } else { // we're on to the main body while ((read < value.length) && (val_next != 0)) { // read until the train runs out of tracks bdy_body += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read > value.length) { break; } // shouldn't ever hit this, but save a NPE } } // we would normally break here, but just let this read out to the end } done = true; // don't let this run back through and start thrashing metadata } properties.put(""body"", bdy_body); properties.put(""title"", bdy_title); properties.put(""subject"", bdy_heading); properties.put(""author"", bdy_author); properties.put(""source"", bdy_source); added = (bdy_body.length() + bdy_title.length() + bdy_heading.length() + bdy_author.length() + bdy_source.length()) > 0; return added; } "," private boolean parseBody(byte[] value, HashMap properties) { boolean added = false; String bdy_heading = """"; String bdy_title = """"; String bdy_source = """"; String bdy_author = """"; String bdy_body = """"; int read = 0; boolean done = false; while (!done && (read < value.length)) { // pull apart the body, getting the heading (^....\x0d\x0a) while (read < value.length) { byte val_next = value[read++]; if (val_next == CT) { // start of a new section , first is the heading val_next = (read < value.length) ? value[read++] : 0x00; // AP, NYT, and Bloomberg end with < , Reuters with EOL while ((val_next != LT) && (val_next != CR) && (val_next != LF)) { // less than delimiter (\x3c) and not EOL bdy_heading += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read >= value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } while (bdy_heading.length() > 0 && ((val_next == CR) || (val_next == LF))) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } } else { // this will only be hit on poorly-formed files // for reuters, the heading does not start with the ^, so we push one back into the stream if (FORMAT == this.FMT_IPTC_RTR) { if (val_next != CT) { // for any non-whitespace, we need to go back an additional step to non destroy the data if ((val_next != SP) && (val_next != TB) && (val_next != CR) && (val_next != LF)) { // if the very first byte is data, we have to shift the whole array, and stuff in a carat if (read == 1) { byte[] resize = new byte[value.length + 1]; System.arraycopy(value, 0, resize, 1, value.length); value = resize; } } value[--read] = CT; continue; } } } break; } // pull apart the body, getting the title (^....\x0d\x0a) while (read < value.length) { byte val_next = value[read++]; if (val_next == CT) { // start of a new section , first is the heading val_next = (read < value.length) ? value[read++] : 0x00; // AP, NYT, and Bloomberg end with < , Reuters with EOL while ((val_next != LT) && (val_next != CT) && (val_next != CR) && (val_next != LF)) { // less than delimiter (\x3c), or carat (\x5e) and not EOL bdy_title += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read >= value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == CT) { // start of a new section , when first didn't finish cleanly --read; } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } while (bdy_title.length() > 0 && ((val_next == CR) || (val_next == LF))) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } } else { // this will only be hit on poorly-formed files // for bloomberg, the title does not start with the ^, so we push one back into the stream if (FORMAT == this.FMT_IPTC_BLM) { if (val_next == TB) { value[--read] = CT; continue; } } // for reuters, the title does not start with the ^, so we push one back into the stream if (FORMAT == this.FMT_IPTC_RTR) { if (val_next != CT) { // for any non-whitespace, we need to go back an additional step to non destroy the data if ((val_next != SP) && (val_next != TB) && (val_next != CR) && (val_next != LF)) { --read; } value[--read] = CT; continue; } } } break; } // at this point, we have a variable number of metadata lines, with various orders // we scan the start of each line for the special character, and run to the end character // pull apart the body, getting the title (^....\x0d\x0a) boolean metastarted = false; String longline = """"; String longkey = """"; while (read < value.length) { byte val_next = value[read++]; // eat up whitespace before committing to the next section if ((val_next == SP) || (val_next == TB) || (val_next == CR) || (val_next == LF)) { continue; } if (val_next == CT) { // start of a new section , could be authors, sources, etc val_next = (read < value.length) ? value[read++] : 0x00; String tmp_line = """"; while ((val_next != LT) && (val_next != CT) && (val_next != CR) && (val_next != LF) && (val_next != 0)) { // less than delimiter (\x3c), maybe also badly formed with just new line tmp_line += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read >= value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == CT) { // start of a new section , when first didn't finish cleanly --read; } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } while ((val_next == CR) || (val_next == LF)) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } if (tmp_line.toLowerCase(Locale.ROOT).startsWith(""by"") || longline.equals(""bdy_author"")) { longkey = ""bdy_author""; // prepend a space to subsequent line, so it gets parsed consistent with the lead line tmp_line = (longline.equals(longkey) ? "" "" : """") + tmp_line; // we have an author candidate int term = tmp_line.length(); term = Math.min(term, (tmp_line.contains(""<"") ? tmp_line.indexOf(""<"") : term)); term = Math.min(term, (tmp_line.contains(""="") ? tmp_line.indexOf(""="") : term)); term = Math.min(term, (tmp_line.contains(""\n"") ? tmp_line.indexOf(""\n"") : term)); term = (term > 0 ) ? term : tmp_line.length(); bdy_author += tmp_line.substring(tmp_line.indexOf("" ""), term); metastarted = true; longline = ((tmp_line.contains(""="")) && (!longline.equals(longkey)) ? longkey : """"); } else if (FORMAT == this.FMT_IPTC_BLM) { String byline = "" by ""; if (tmp_line.toLowerCase(Locale.ROOT).contains(byline)) { longkey = ""bdy_author""; int term = tmp_line.length(); term = Math.min(term, (tmp_line.contains(""<"") ? tmp_line.indexOf(""<"") : term)); term = Math.min(term, (tmp_line.contains(""="") ? tmp_line.indexOf(""="") : term)); term = Math.min(term, (tmp_line.contains(""\n"") ? tmp_line.indexOf(""\n"") : term)); term = (term > 0 ) ? term : tmp_line.length(); // for bloomberg, the author line sits below their copyright statement bdy_author += tmp_line.substring(tmp_line.toLowerCase(Locale.ROOT).indexOf(byline) + byline.length(), term) + "" ""; metastarted = true; longline = ((tmp_line.contains(""="")) && (!longline.equals(longkey)) ? longkey : """"); } else if(tmp_line.toLowerCase(Locale.ROOT).startsWith(""c."")) { // the author line for bloomberg is a multiline starting with c.2011 Bloomberg News // then containing the author info on the next line if (val_next == TB) { value[--read] = CT; continue; } } else if(tmp_line.toLowerCase(Locale.ROOT).trim().startsWith(""("") && tmp_line.toLowerCase(Locale.ROOT).trim().endsWith("")"")) { // the author line may have one or more comment lines between the copyright // statement, and the By AUTHORNAME line if (val_next == TB) { value[--read] = CT; continue; } } } else if (tmp_line.toLowerCase(Locale.ROOT).startsWith(""eds"") || longline.equals(""bdy_source"")) { longkey = ""bdy_source""; // prepend a space to subsequent line, so it gets parsed consistent with the lead line tmp_line = (longline.equals(longkey) ? "" "" : """") + tmp_line; // we have a source candidate int term = tmp_line.length(); term = Math.min(term, (tmp_line.contains(""<"") ? tmp_line.indexOf(""<"") : term)); term = Math.min(term, (tmp_line.contains(""="") ? tmp_line.indexOf(""="") : term)); // term = Math.min(term, (tmp_line.indexOf(""\n"") > -1 ? tmp_line.indexOf(""\n"") : term)); term = (term > 0 ) ? term : tmp_line.length(); bdy_source += tmp_line.substring(tmp_line.indexOf("" "") + 1, term) + "" ""; metastarted = true; longline = (!longline.equals(longkey) ? longkey : """"); } else { // this has fallen all the way through. trap it as part of the subject, // rather than just losing it if (!metastarted) { bdy_title += "" , "" + tmp_line; // not sure where else to put this but in the title } else { // what to do with stuff that is metadata, which falls after metadata lines started? bdy_body += "" "" + tmp_line + "" , ""; // not sure where else to put this but in the title } } } else { // we're on to the main body while ((read < value.length) && (val_next != 0)) { // read until the train runs out of tracks bdy_body += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; if (read >= value.length) { break; } // shouldn't ever hit this, but save a NPE } } // we would normally break here, but just let this read out to the end } done = true; // don't let this run back through and start thrashing metadata } properties.put(""body"", bdy_body); properties.put(""title"", bdy_title); properties.put(""subject"", bdy_heading); properties.put(""author"", bdy_author); properties.put(""source"", bdy_source); added = (bdy_body.length() + bdy_title.length() + bdy_heading.length() + bdy_author.length() + bdy_source.length()) > 0; return added; } ",TRUE,IptcAnpaParser.java " private boolean parseFooter(byte[] value, HashMap properties) { boolean added = false; String ftr_source = """"; String ftr_datetime = """"; int read = 0; boolean done = false; while (!done && (read < value.length)) { // pull apart the footer, getting the news feed source (^....\x0d\x0a) byte val_next = value[read++]; byte val_peek = (read < value.length) ? value[read+1] : 0x00; // skip the new lines while (((val_next < (byte)0x30) || (val_next > (byte)0x39)) && (val_next != 0)) { // consume all non-numerics first ftr_source += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read] : 0x00; // attempt to read until end of stream read++; if (read > value.length) { break; } // shouldn't ever hit this, but save a NPE } while ((val_next != LT) && (val_next != CR) && (val_next != LF) && (val_next != 0)) { // get as much timedate as possible // this is an american format, so arrives as mm-dd-yy HHiizzz ftr_datetime += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if (read > value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } if (ftr_datetime.length() > 0) { // we want to pass this back in a more friendly format String format_out = ""yyyy-MM-dd'T'HH:mm:ss'Z'""; Date dateunix = new Date(); try { // standard ap format String format_in = ""MM-dd-yy HHmmzzz""; if (FORMAT == this.FMT_IPTC_RTR) { // standard reuters format format_in = ""HH:mm MM-dd-yy""; } SimpleDateFormat dfi = new SimpleDateFormat(format_in, Locale.ROOT); dfi.setTimeZone(TimeZone.getTimeZone(""UTC"")); dateunix = dfi.parse(ftr_datetime); } catch (ParseException ep) { // failed, but this will just fall through to setting the date to now } SimpleDateFormat dfo = new SimpleDateFormat(format_out, Locale.ROOT); dfo.setTimeZone(TimeZone.getTimeZone(""UTC"")); ftr_datetime = dfo.format(dateunix); } while ((val_next == CR) || (val_next == LF)) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } done = true; // don't let this run back through and start thrashing metadata } properties.put(""publisher"", ftr_source); properties.put(""created"", ftr_datetime); properties.put(""modified"", ftr_datetime); added = (ftr_source.length() + ftr_datetime.length()) > 0; return added; } "," private boolean parseFooter(byte[] value, HashMap properties) { boolean added = false; String ftr_source = """"; String ftr_datetime = """"; int read = 0; boolean done = false; while (!done && (read < value.length)) { // pull apart the footer, getting the news feed source (^....\x0d\x0a) byte val_next = value[read++]; byte val_peek = (read < value.length) ? value[read+1] : 0x00; // skip the new lines while (((val_next < (byte)0x30) || (val_next > (byte)0x39)) && (val_next != 0)) { // consume all non-numerics first ftr_source += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read] : 0x00; // attempt to read until end of stream read++; if (read >= value.length) { break; } // shouldn't ever hit this, but save a NPE } while ((val_next != LT) && (val_next != CR) && (val_next != LF) && (val_next != 0)) { // get as much timedate as possible // this is an american format, so arrives as mm-dd-yy HHiizzz ftr_datetime += (char)(val_next & 0xff); // convert the byte to an unsigned int val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if (read >= value.length) { break; } // shouldn't ever hit this, but save a NPE } if (val_next == LT) { // hit the delimiter, carry on val_next = (read < value.length) ? value[read++] : 0x00; } if (ftr_datetime.length() > 0) { // we want to pass this back in a more friendly format String format_out = ""yyyy-MM-dd'T'HH:mm:ss'Z'""; Date dateunix = new Date(); try { // standard ap format String format_in = ""MM-dd-yy HHmmzzz""; if (FORMAT == this.FMT_IPTC_RTR) { // standard reuters format format_in = ""HH:mm MM-dd-yy""; } SimpleDateFormat dfi = new SimpleDateFormat(format_in, Locale.ROOT); dfi.setTimeZone(TimeZone.getTimeZone(""UTC"")); dateunix = dfi.parse(ftr_datetime); } catch (ParseException ep) { // failed, but this will just fall through to setting the date to now } SimpleDateFormat dfo = new SimpleDateFormat(format_out, Locale.ROOT); dfo.setTimeZone(TimeZone.getTimeZone(""UTC"")); ftr_datetime = dfo.format(dateunix); } while ((val_next == CR) || (val_next == LF)) { val_next = (read < value.length) ? value[read++] : 0x00; // skip the new lines if ((val_next != CR) && (val_next != LF)) { --read; } } done = true; // don't let this run back through and start thrashing metadata } properties.put(""publisher"", ftr_source); properties.put(""created"", ftr_datetime); properties.put(""modified"", ftr_datetime); added = (ftr_source.length() + ftr_datetime.length()) > 0; return added; } ",TRUE,IptcAnpaParser.java " private void setMetadata(Metadata metadata, HashMap properties) { // every property that gets set must be non-null, or it will cause NPE // in other consuming applications, like Lucene metadata.set(Metadata.CONTENT_TYPE, clean(""text/anpa-1312"")); metadata.set(TikaCoreProperties.TITLE, clean(properties.get(""title""))); metadata.set(TikaCoreProperties.SUBJECT, clean(properties.get(""subject""))); metadata.set(TikaCoreProperties.CREATOR, clean(properties.get(""author""))); metadata.set(TikaCoreProperties.CREATED, clean(properties.get(""created""))); metadata.set(TikaCoreProperties.MODIFIED, clean(properties.get(""modified""))); metadata.set(TikaCoreProperties.SOURCE, clean(properties.get(""source""))); // metadata.set(TikaCoreProperties.PUBLISHER, clean(properties.get(""publisher""))); metadata.set(TikaCoreProperties.PUBLISHER, clean(this.getFormatName())); /* metadata.set(TikaCoreProperties.DATE, font.getHeader().getCreated().getTime()); metadata.set( Property.internalDate(TikaCoreProperties.MODIFIED), font.getHeader().getModified().getTime()); */ } "," private void setMetadata(Metadata metadata, HashMap properties) { // every property that gets set must be non-null, or it will cause NPE // in other consuming applications, like Lucene metadata.set(Metadata.CONTENT_TYPE, clean(""text/anpa-1312"")); metadata.set(TikaCoreProperties.TITLE, clean(properties.get(""title""))); metadata.set(TikaCoreProperties.SUBJECT, clean(properties.get(""subject""))); metadata.set(TikaCoreProperties.CREATOR, clean(properties.get(""author""))); metadata.set(TikaCoreProperties.CREATED, clean(properties.get(""created""))); metadata.set(TikaCoreProperties.MODIFIED, clean(properties.get(""modified""))); metadata.set(TikaCoreProperties.SOURCE, clean(properties.get(""source""))); // metadata.set(TikaCoreProperties.PUBLISHER, clean(properties.get(""publisher""))); metadata.set(TikaCoreProperties.PUBLISHER, clean(this.getFormatName())); /* metadata.set(TikaCoreProperties.DATE, font.getHeader().getCreated().getTime()); metadata.set( Property.internalDate(TikaCoreProperties.MODIFIED), font.getHeader().getModified().getTime()); */ } ",FALSE,IptcAnpaParser.java " private String clean(String value) { if (value == null) { value = """"; } value = value.replaceAll(""``"", ""`""); value = value.replaceAll(""''"", ""'""); value = value.replaceAll(new String(new char[] {SL}), ""'""); value = value.replaceAll(new String(new char[] {SR}), ""'""); value = value.replaceAll(new String(new char[] {DL}), ""\""""); value = value.replaceAll(new String(new char[] {DR}), ""\""""); value = value.trim(); return (value); } "," private String clean(String value) { if (value == null) { value = """"; } value = value.replaceAll(""``"", ""`""); value = value.replaceAll(""''"", ""'""); value = value.replaceAll(new String(new char[] {SL}), ""'""); value = value.replaceAll(new String(new char[] {SR}), ""'""); value = value.replaceAll(new String(new char[] {DL}), ""\""""); value = value.replaceAll(new String(new char[] {DR}), ""\""""); value = value.trim(); return (value); } ",FALSE,IptcAnpaParser.java " public XsltRenderer(String template, Driver driver, DriverRequest originalRequest) throws IOException, HttpErrorPage { StringBuilder templateStringBuilder = new StringBuilder(); CloseableHttpResponse response = driver.render(template, originalRequest.getOriginalRequest()); templateStringBuilder.append(HttpResponseUtils.toString(response)); transformer = createTransformer(IOUtils.toInputStream(templateStringBuilder)); } "," public XsltRenderer(String template, Driver driver, DriverRequest originalRequest) throws IOException, HttpErrorPage { StringBuilder templateStringBuilder = new StringBuilder(); CloseableHttpResponse response = driver.render(template, originalRequest.getOriginalRequest()); templateStringBuilder.append(HttpResponseUtils.toString(response)); transformer = createTransformer(IOUtils.toInputStream(templateStringBuilder)); } ",FALSE,XsltRenderer.java " public XsltRenderer(String xsl) throws IOException { InputStream templateStream = IOUtils.toInputStream(xsl); transformer = createTransformer(templateStream); } "," public XsltRenderer(String xsl) throws IOException { InputStream templateStream = IOUtils.toInputStream(xsl); transformer = createTransformer(templateStream); } ",FALSE,XsltRenderer.java " private static Transformer createTransformer(InputStream templateStream) throws IOException { try { return TRANSFORMER_FACTORY.newTransformer(new StreamSource(templateStream)); } catch (TransformerConfigurationException e) { throw new ProcessingFailedException(""Failed to create XSLT template"", e); } finally { templateStream.close(); } } "," private static Transformer createTransformer(InputStream templateStream) throws IOException { try { // Ensure XSLT cannot use advanced extensions during processing. TRANSFORMER_FACTORY.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); return TRANSFORMER_FACTORY.newTransformer(new StreamSource(templateStream)); } catch (TransformerConfigurationException e) { throw new ProcessingFailedException(""Failed to create XSLT template"", e); } finally { templateStream.close(); } } ",TRUE,XsltRenderer.java " public void render(DriverRequest httpRequest, String src, Writer out) throws IOException { try { HtmlDocumentBuilder htmlDocumentBuilder = new HtmlDocumentBuilder(); htmlDocumentBuilder.setDoctypeExpectation(DoctypeExpectation.NO_DOCTYPE_ERRORS); Document document = htmlDocumentBuilder.parse(new InputSource(new StringReader(src))); Source source = new DOMSource(document); DOMResult result = new DOMResult(); transformer.transform(source, result); XhtmlSerializer serializer = new XhtmlSerializer(out); Dom2Sax dom2Sax = new Dom2Sax(serializer, serializer); dom2Sax.parse(result.getNode()); } catch (TransformerException e) { throw new ProcessingFailedException(""Failed to transform source"", e); } catch (SAXException e) { throw new ProcessingFailedException(""Failed serialize transformation result"", e); } } "," public void render(DriverRequest httpRequest, String src, Writer out) throws IOException { try { HtmlDocumentBuilder htmlDocumentBuilder = new HtmlDocumentBuilder(); htmlDocumentBuilder.setDoctypeExpectation(DoctypeExpectation.NO_DOCTYPE_ERRORS); Document document = htmlDocumentBuilder.parse(new InputSource(new StringReader(src))); Source source = new DOMSource(document); DOMResult result = new DOMResult(); transformer.transform(source, result); XhtmlSerializer serializer = new XhtmlSerializer(out); Dom2Sax dom2Sax = new Dom2Sax(serializer, serializer); dom2Sax.parse(result.getNode()); } catch (TransformerException e) { throw new ProcessingFailedException(""Failed to transform source"", e); } catch (SAXException e) { throw new ProcessingFailedException(""Failed serialize transformation result"", e); } } ",FALSE,XsltRenderer.java " public ProcessingInstructionInfo(String target, String data) { this.target = target; this.data = data; } "," public ProcessingInstructionInfo(String target, String data) { this.target = target; this.data = data; } ",FALSE,SAXDocumentFactory.java " public Node createNode(Document doc) { return doc.createProcessingInstruction(target, data); } "," public Node createNode(Document doc) { return doc.createProcessingInstruction(target, data); } ",FALSE,SAXDocumentFactory.java " public CommentInfo(String comment) { this.comment = comment; } "," public CommentInfo(String comment) { this.comment = comment; } ",FALSE,SAXDocumentFactory.java " public Node createNode(Document doc) { return doc.createComment(comment); } "," public Node createNode(Document doc) { return doc.createComment(comment); } ",FALSE,SAXDocumentFactory.java " public CDataInfo(String cdata) { this.cdata = cdata; } "," public CDataInfo(String cdata) { this.cdata = cdata; } ",FALSE,SAXDocumentFactory.java " public Node createNode(Document doc) { return doc.createCDATASection(cdata); } "," public Node createNode(Document doc) { return doc.createCDATASection(cdata); } ",FALSE,SAXDocumentFactory.java " public TextInfo(String text) { this.text = text; } "," public TextInfo(String text) { this.text = text; } ",FALSE,SAXDocumentFactory.java " public Node createNode(Document doc) { return doc.createTextNode(text); } "," public Node createNode(Document doc) { return doc.createTextNode(text); } ",FALSE,SAXDocumentFactory.java " public SAXDocumentFactory(DOMImplementation impl, String parser) { implementation = impl; parserClassName = parser; } "," public SAXDocumentFactory(DOMImplementation impl, String parser) { implementation = impl; parserClassName = parser; } ",FALSE,SAXDocumentFactory.java " public SAXDocumentFactory(DOMImplementation impl, String parser, boolean dd) { implementation = impl; parserClassName = parser; createDocumentDescriptor = dd; } "," public SAXDocumentFactory(DOMImplementation impl, String parser, boolean dd) { implementation = impl; parserClassName = parser; createDocumentDescriptor = dd; } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String ns, String root, String uri) throws IOException { return createDocument(ns, root, uri, new InputSource(uri)); } "," public Document createDocument(String ns, String root, String uri) throws IOException { return createDocument(ns, root, uri, new InputSource(uri)); } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String uri) throws IOException { return createDocument(new InputSource(uri)); } "," public Document createDocument(String uri) throws IOException { return createDocument(new InputSource(uri)); } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String ns, String root, String uri, InputStream is) throws IOException { InputSource inp = new InputSource(is); inp.setSystemId(uri); return createDocument(ns, root, uri, inp); } "," public Document createDocument(String ns, String root, String uri, InputStream is) throws IOException { InputSource inp = new InputSource(is); inp.setSystemId(uri); return createDocument(ns, root, uri, inp); } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String uri, InputStream is) throws IOException { InputSource inp = new InputSource(is); inp.setSystemId(uri); return createDocument(inp); } "," public Document createDocument(String uri, InputStream is) throws IOException { InputSource inp = new InputSource(is); inp.setSystemId(uri); return createDocument(inp); } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String ns, String root, String uri, Reader r) throws IOException { InputSource inp = new InputSource(r); inp.setSystemId(uri); return createDocument(ns, root, uri, inp); } "," public Document createDocument(String ns, String root, String uri, Reader r) throws IOException { InputSource inp = new InputSource(r); inp.setSystemId(uri); return createDocument(ns, root, uri, inp); } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String ns, String root, String uri, XMLReader r) throws IOException { r.setContentHandler(this); r.setDTDHandler(this); r.setEntityResolver(this); try { r.parse(uri); } catch (SAXException e) { Exception ex = e.getException(); if (ex != null && ex instanceof InterruptedIOException) { throw (InterruptedIOException) ex; } throw new SAXIOException(e); } currentNode = null; Document ret = document; document = null; doctype = null; return ret; } "," public Document createDocument(String ns, String root, String uri, XMLReader r) throws IOException { r.setContentHandler(this); r.setDTDHandler(this); r.setEntityResolver(this); try { r.parse(uri); } catch (SAXException e) { Exception ex = e.getException(); if (ex != null && ex instanceof InterruptedIOException) { throw (InterruptedIOException) ex; } throw new SAXIOException(e); } currentNode = null; Document ret = document; document = null; doctype = null; return ret; } ",FALSE,SAXDocumentFactory.java " public Document createDocument(String uri, Reader r) throws IOException { InputSource inp = new InputSource(r); inp.setSystemId(uri); return createDocument(inp); } "," public Document createDocument(String uri, Reader r) throws IOException { InputSource inp = new InputSource(r); inp.setSystemId(uri); return createDocument(inp); } ",FALSE,SAXDocumentFactory.java " protected Document createDocument(String ns, String root, String uri, InputSource is) throws IOException { Document ret = createDocument(is); Element docElem = ret.getDocumentElement(); String lname = root; String nsURI = ns; if (ns == null) { int idx = lname.indexOf(':'); String nsp = (idx == -1 || idx == lname.length()-1) ? """" : lname.substring(0, idx); nsURI = namespaces.get(nsp); if (idx != -1 && idx != lname.length()-1) { lname = lname.substring(idx+1); } } String docElemNS = docElem.getNamespaceURI(); if ((docElemNS != nsURI) && ((docElemNS == null) || (!docElemNS.equals(nsURI)))) throw new IOException (""Root element namespace does not match that requested:\n"" + ""Requested: "" + nsURI + ""\n"" + ""Found: "" + docElemNS); if (docElemNS != null) { if (!docElem.getLocalName().equals(lname)) throw new IOException (""Root element does not match that requested:\n"" + ""Requested: "" + lname + ""\n"" + ""Found: "" + docElem.getLocalName()); } else { if (!docElem.getNodeName().equals(lname)) throw new IOException (""Root element does not match that requested:\n"" + ""Requested: "" + lname + ""\n"" + ""Found: "" + docElem.getNodeName()); } return ret; } "," protected Document createDocument(String ns, String root, String uri, InputSource is) throws IOException { Document ret = createDocument(is); Element docElem = ret.getDocumentElement(); String lname = root; String nsURI = ns; if (ns == null) { int idx = lname.indexOf(':'); String nsp = (idx == -1 || idx == lname.length()-1) ? """" : lname.substring(0, idx); nsURI = namespaces.get(nsp); if (idx != -1 && idx != lname.length()-1) { lname = lname.substring(idx+1); } } String docElemNS = docElem.getNamespaceURI(); if ((docElemNS != nsURI) && ((docElemNS == null) || (!docElemNS.equals(nsURI)))) throw new IOException (""Root element namespace does not match that requested:\n"" + ""Requested: "" + nsURI + ""\n"" + ""Found: "" + docElemNS); if (docElemNS != null) { if (!docElem.getLocalName().equals(lname)) throw new IOException (""Root element does not match that requested:\n"" + ""Requested: "" + lname + ""\n"" + ""Found: "" + docElem.getLocalName()); } else { if (!docElem.getNodeName().equals(lname)) throw new IOException (""Root element does not match that requested:\n"" + ""Requested: "" + lname + ""\n"" + ""Found: "" + docElem.getNodeName()); } return ret; } ",FALSE,SAXDocumentFactory.java " } catch (SAXNotRecognizedException e) { e.printStackTrace(); } catch (SAXNotSupportedException e) { "," } catch (SAXNotRecognizedException e) { e.printStackTrace(); } catch (SAXNotSupportedException e) { ",FALSE,SAXDocumentFactory.java " } catch (SAXNotSupportedException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { "," } catch (SAXNotSupportedException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { ",FALSE,SAXDocumentFactory.java " } catch (ParserConfigurationException e) { e.printStackTrace(); } "," } catch (ParserConfigurationException e) { e.printStackTrace(); } ",FALSE,SAXDocumentFactory.java " protected Document createDocument(InputSource is) throws IOException { try { if (parserClassName != null) { parser = XMLReaderFactory.createXMLReader(parserClassName); } else { SAXParser saxParser; try { saxParser = saxFactory.newSAXParser(); } catch (ParserConfigurationException pce) { throw new IOException(""Could not create SAXParser: "" + pce.getMessage()); } parser = saxParser.getXMLReader(); } parser.setContentHandler(this); parser.setDTDHandler(this); parser.setEntityResolver(this); parser.setErrorHandler((errorHandler == null) ? this : errorHandler); parser.setFeature(""http://xml.org/sax/features/namespaces"", true); parser.setFeature(""http://xml.org/sax/features/namespace-prefixes"", true); parser.setFeature(""http://xml.org/sax/features/validation"", isValidating); parser.setFeature(""http://xml.org/sax/features/external-general-entities"", false); parser.setFeature(""http://xml.org/sax/features/external-parameter-entities"", false); parser.setProperty(""http://xml.org/sax/properties/lexical-handler"", this); parser.parse(is); } catch (SAXException e) { Exception ex = e.getException(); if (ex != null && ex instanceof InterruptedIOException) { throw (InterruptedIOException)ex; } throw new SAXIOException(e); } currentNode = null; Document ret = document; document = null; doctype = null; locator = null; parser = null; return ret; } "," protected Document createDocument(InputSource is) throws IOException { try { if (parserClassName != null) { parser = XMLReaderFactory.createXMLReader(parserClassName); } else { SAXParser saxParser; try { saxParser = saxFactory.newSAXParser(); } catch (ParserConfigurationException pce) { throw new IOException(""Could not create SAXParser: "" + pce.getMessage()); } parser = saxParser.getXMLReader(); } parser.setContentHandler(this); parser.setDTDHandler(this); parser.setEntityResolver(this); parser.setErrorHandler((errorHandler == null) ? this : errorHandler); parser.setFeature(""http://xml.org/sax/features/namespaces"", true); parser.setFeature(""http://xml.org/sax/features/namespace-prefixes"", true); parser.setFeature(""http://xml.org/sax/features/validation"", isValidating); parser.setFeature(""http://xml.org/sax/features/external-general-entities"", false); parser.setFeature(""http://xml.org/sax/features/external-parameter-entities"", false); parser.setFeature(""http://apache.org/xml/features/nonvalidating/load-external-dtd"", false); parser.setProperty(""http://xml.org/sax/properties/lexical-handler"", this); parser.parse(is); } catch (SAXException e) { Exception ex = e.getException(); if (ex != null && ex instanceof InterruptedIOException) { throw (InterruptedIOException)ex; } throw new SAXIOException(e); } currentNode = null; Document ret = document; document = null; doctype = null; locator = null; parser = null; return ret; } ",TRUE,SAXDocumentFactory.java " public DocumentDescriptor getDocumentDescriptor() { return documentDescriptor; } "," public DocumentDescriptor getDocumentDescriptor() { return documentDescriptor; } ",FALSE,SAXDocumentFactory.java " public void setDocumentLocator(Locator l) { locator = l; } "," public void setDocumentLocator(Locator l) { locator = l; } ",FALSE,SAXDocumentFactory.java " public void setValidating(boolean isValidating) { this.isValidating = isValidating; } "," public void setValidating(boolean isValidating) { this.isValidating = isValidating; } ",FALSE,SAXDocumentFactory.java " public boolean isValidating() { return isValidating; } "," public boolean isValidating() { return isValidating; } ",FALSE,SAXDocumentFactory.java " public void setErrorHandler(ErrorHandler eh) { errorHandler = eh; } "," public void setErrorHandler(ErrorHandler eh) { errorHandler = eh; } ",FALSE,SAXDocumentFactory.java " public DOMImplementation getDOMImplementation(String ver) { return implementation; } "," public DOMImplementation getDOMImplementation(String ver) { return implementation; } ",FALSE,SAXDocumentFactory.java " public void fatalError(SAXParseException ex) throws SAXException { throw ex; } "," public void fatalError(SAXParseException ex) throws SAXException { throw ex; } ",FALSE,SAXDocumentFactory.java " public void error(SAXParseException ex) throws SAXException { throw ex; } "," public void error(SAXParseException ex) throws SAXException { throw ex; } ",FALSE,SAXDocumentFactory.java " public void warning(SAXParseException ex) throws SAXException { } "," public void warning(SAXParseException ex) throws SAXException { } ",FALSE,SAXDocumentFactory.java " public void startDocument() throws SAXException { preInfo = new LinkedList(); namespaces = new HashTableStack(); namespaces.put(""xml"", XMLSupport.XML_NAMESPACE_URI); namespaces.put(""xmlns"", XMLSupport.XMLNS_NAMESPACE_URI); namespaces.put("""", null); inDTD = false; inCDATA = false; inProlog = true; currentNode = null; document = null; doctype = null; isStandalone = false; xmlVersion = XMLConstants.XML_VERSION_10; stringBuffer.setLength(0); stringContent = false; if (createDocumentDescriptor) { documentDescriptor = new DocumentDescriptor(); } else { documentDescriptor = null; } } "," public void startDocument() throws SAXException { preInfo = new LinkedList(); namespaces = new HashTableStack(); namespaces.put(""xml"", XMLSupport.XML_NAMESPACE_URI); namespaces.put(""xmlns"", XMLSupport.XMLNS_NAMESPACE_URI); namespaces.put("""", null); inDTD = false; inCDATA = false; inProlog = true; currentNode = null; document = null; doctype = null; isStandalone = false; xmlVersion = XMLConstants.XML_VERSION_10; stringBuffer.setLength(0); stringContent = false; if (createDocumentDescriptor) { documentDescriptor = new DocumentDescriptor(); } else { documentDescriptor = null; } } ",FALSE,SAXDocumentFactory.java " public void startElement(String uri, String localName, String rawName, Attributes attributes) throws SAXException { // Check If we should halt early. if (HaltingThread.hasBeenHalted()) { throw new SAXException(new InterruptedIOException()); } if (inProlog) { inProlog = false; if (parser != null) { try { isStandalone = parser.getFeature (""http://xml.org/sax/features/is-standalone""); } catch (SAXNotRecognizedException ex) { } try { xmlVersion = (String) parser.getProperty (""http://xml.org/sax/properties/document-xml-version""); } catch (SAXNotRecognizedException ex) { } } } // Namespaces resolution int len = attributes.getLength(); namespaces.push(); String version = null; for (int i = 0; i < len; i++) { String aname = attributes.getQName(i); int slen = aname.length(); if (slen < 5) continue; if (aname.equals(""version"")) { version = attributes.getValue(i); continue; } if (!aname.startsWith(""xmlns"")) continue; if (slen == 5) { String ns = attributes.getValue(i); if (ns.length() == 0) ns = null; namespaces.put("""", ns); } else if (aname.charAt(5) == ':') { String ns = attributes.getValue(i); if (ns.length() == 0) { ns = null; } namespaces.put(aname.substring(6), ns); } } // Add any collected String Data before element. appendStringData(); // Element creation Element e; int idx = rawName.indexOf(':'); String nsp = (idx == -1 || idx == rawName.length()-1) ? """" : rawName.substring(0, idx); String nsURI = namespaces.get(nsp); if (currentNode == null) { implementation = getDOMImplementation(version); document = implementation.createDocument(nsURI, rawName, doctype); Iterator i = preInfo.iterator(); currentNode = e = document.getDocumentElement(); while (i.hasNext()) { PreInfo pi = (PreInfo)i.next(); Node n = pi.createNode(document); document.insertBefore(n, e); } preInfo = null; } else { e = document.createElementNS(nsURI, rawName); currentNode.appendChild(e); currentNode = e; } // Storage of the line number. if (createDocumentDescriptor && locator != null) { documentDescriptor.setLocation(e, locator.getLineNumber(), locator.getColumnNumber()); } // Attributes creation for (int i = 0; i < len; i++) { String aname = attributes.getQName(i); if (aname.equals(""xmlns"")) { e.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, aname, attributes.getValue(i)); } else { idx = aname.indexOf(':'); nsURI = (idx == -1) ? null : namespaces.get(aname.substring(0, idx)); e.setAttributeNS(nsURI, aname, attributes.getValue(i)); } } } "," public void startElement(String uri, String localName, String rawName, Attributes attributes) throws SAXException { // Check If we should halt early. if (HaltingThread.hasBeenHalted()) { throw new SAXException(new InterruptedIOException()); } if (inProlog) { inProlog = false; if (parser != null) { try { isStandalone = parser.getFeature (""http://xml.org/sax/features/is-standalone""); } catch (SAXNotRecognizedException ex) { } try { xmlVersion = (String) parser.getProperty (""http://xml.org/sax/properties/document-xml-version""); } catch (SAXNotRecognizedException ex) { } } } // Namespaces resolution int len = attributes.getLength(); namespaces.push(); String version = null; for (int i = 0; i < len; i++) { String aname = attributes.getQName(i); int slen = aname.length(); if (slen < 5) continue; if (aname.equals(""version"")) { version = attributes.getValue(i); continue; } if (!aname.startsWith(""xmlns"")) continue; if (slen == 5) { String ns = attributes.getValue(i); if (ns.length() == 0) ns = null; namespaces.put("""", ns); } else if (aname.charAt(5) == ':') { String ns = attributes.getValue(i); if (ns.length() == 0) { ns = null; } namespaces.put(aname.substring(6), ns); } } // Add any collected String Data before element. appendStringData(); // Element creation Element e; int idx = rawName.indexOf(':'); String nsp = (idx == -1 || idx == rawName.length()-1) ? """" : rawName.substring(0, idx); String nsURI = namespaces.get(nsp); if (currentNode == null) { implementation = getDOMImplementation(version); document = implementation.createDocument(nsURI, rawName, doctype); Iterator i = preInfo.iterator(); currentNode = e = document.getDocumentElement(); while (i.hasNext()) { PreInfo pi = (PreInfo)i.next(); Node n = pi.createNode(document); document.insertBefore(n, e); } preInfo = null; } else { e = document.createElementNS(nsURI, rawName); currentNode.appendChild(e); currentNode = e; } // Storage of the line number. if (createDocumentDescriptor && locator != null) { documentDescriptor.setLocation(e, locator.getLineNumber(), locator.getColumnNumber()); } // Attributes creation for (int i = 0; i < len; i++) { String aname = attributes.getQName(i); if (aname.equals(""xmlns"")) { e.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, aname, attributes.getValue(i)); } else { idx = aname.indexOf(':'); nsURI = (idx == -1) ? null : namespaces.get(aname.substring(0, idx)); e.setAttributeNS(nsURI, aname, attributes.getValue(i)); } } } ",FALSE,SAXDocumentFactory.java " public void endElement(String uri, String localName, String rawName) throws SAXException { appendStringData(); // add string data if any. if (currentNode != null) currentNode = currentNode.getParentNode(); namespaces.pop(); } "," public void endElement(String uri, String localName, String rawName) throws SAXException { appendStringData(); // add string data if any. if (currentNode != null) currentNode = currentNode.getParentNode(); namespaces.pop(); } ",FALSE,SAXDocumentFactory.java " public void appendStringData() { if (!stringContent) return; String str = stringBuffer.toString(); stringBuffer.setLength(0); // reuse buffer. stringContent = false; if (currentNode == null) { if (inCDATA) preInfo.add(new CDataInfo(str)); else preInfo.add(new TextInfo(str)); } else { Node n; if (inCDATA) n = document.createCDATASection(str); else n = document.createTextNode(str); currentNode.appendChild(n); } } "," public void appendStringData() { if (!stringContent) return; String str = stringBuffer.toString(); stringBuffer.setLength(0); // reuse buffer. stringContent = false; if (currentNode == null) { if (inCDATA) preInfo.add(new CDataInfo(str)); else preInfo.add(new TextInfo(str)); } else { Node n; if (inCDATA) n = document.createCDATASection(str); else n = document.createTextNode(str); currentNode.appendChild(n); } } ",FALSE,SAXDocumentFactory.java " public void characters(char[] ch, int start, int length) throws SAXException { stringBuffer.append(ch, start, length); stringContent = true; } "," public void characters(char[] ch, int start, int length) throws SAXException { stringBuffer.append(ch, start, length); stringContent = true; } ",FALSE,SAXDocumentFactory.java " public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { stringBuffer.append(ch, start, length); stringContent = true; } "," public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { stringBuffer.append(ch, start, length); stringContent = true; } ",FALSE,SAXDocumentFactory.java " public void processingInstruction(String target, String data) throws SAXException { if (inDTD) return; appendStringData(); // Add any collected String Data before PI if (currentNode == null) preInfo.add(new ProcessingInstructionInfo(target, data)); else currentNode.appendChild (document.createProcessingInstruction(target, data)); } "," public void processingInstruction(String target, String data) throws SAXException { if (inDTD) return; appendStringData(); // Add any collected String Data before PI if (currentNode == null) preInfo.add(new ProcessingInstructionInfo(target, data)); else currentNode.appendChild (document.createProcessingInstruction(target, data)); } ",FALSE,SAXDocumentFactory.java " public void startDTD(String name, String publicId, String systemId) throws SAXException { appendStringData(); // Add collected string data before entering DTD doctype = implementation.createDocumentType(name, publicId, systemId); inDTD = true; } "," public void startDTD(String name, String publicId, String systemId) throws SAXException { appendStringData(); // Add collected string data before entering DTD doctype = implementation.createDocumentType(name, publicId, systemId); inDTD = true; } ",FALSE,SAXDocumentFactory.java " public void endDTD() throws SAXException { inDTD = false; } "," public void endDTD() throws SAXException { inDTD = false; } ",FALSE,SAXDocumentFactory.java " public void startEntity(String name) throws SAXException { } "," public void startEntity(String name) throws SAXException { } ",FALSE,SAXDocumentFactory.java " public void endEntity(String name) throws SAXException { } "," public void endEntity(String name) throws SAXException { } ",FALSE,SAXDocumentFactory.java " public void startCDATA() throws SAXException { appendStringData(); // Add any collected String Data before CData inCDATA = true; stringContent = true; // always create CDATA even if empty. } "," public void startCDATA() throws SAXException { appendStringData(); // Add any collected String Data before CData inCDATA = true; stringContent = true; // always create CDATA even if empty. } ",FALSE,SAXDocumentFactory.java " public void endCDATA() throws SAXException { appendStringData(); // Add the CDATA section inCDATA = false; } "," public void endCDATA() throws SAXException { appendStringData(); // Add the CDATA section inCDATA = false; } ",FALSE,SAXDocumentFactory.java " public void comment(char[] ch, int start, int length) throws SAXException { if (inDTD) return; appendStringData(); String str = new String(ch, start, length); if (currentNode == null) { preInfo.add(new CommentInfo(str)); } else { currentNode.appendChild(document.createComment(str)); } } "," public void comment(char[] ch, int start, int length) throws SAXException { if (inDTD) return; appendStringData(); String str = new String(ch, start, length); if (currentNode == null) { preInfo.add(new CommentInfo(str)); } else { currentNode.appendChild(document.createComment(str)); } } ",FALSE,SAXDocumentFactory.java " public ScimUserSelfUpdateAllowed(ScimUserProvisioning scimUserProvisioning) { this.scimUserProvisioning = scimUserProvisioning; } "," public ScimUserSelfUpdateAllowed(ScimUserProvisioning scimUserProvisioning) { this.scimUserProvisioning = scimUserProvisioning; } ",FALSE,ScimUserSelfUpdateAllowed.java " public boolean isAllowed(HttpServletRequest request) throws IOException { String requestBody = IOUtils.toString(request.getReader()); ScimUser scimUserFromRequest = JsonUtils.readValue(requestBody, ScimUser.class); String id = UaaUrlUtils.extractPathVariableFromUrl(USER_ID_PATH_PARAMETER_INDEX, UaaUrlUtils.getRequestPath(request)); String zoneId = IdentityZoneHolder.get().getId(); ScimUser scimUserFromDb; try { scimUserFromDb = scimUserProvisioning.retrieve(id, zoneId); } catch (ScimResourceNotFoundException e) { return true; } if (!scimUserFromDb.getPrimaryEmail().equals(scimUserFromRequest.getPrimaryEmail())) { return false; } if (!scimUserFromDb.getUserName().equals(scimUserFromRequest.getUserName())) { return false; } if (scimUserFromDb.isVerified() != scimUserFromRequest.isVerified()) { return false; } if (scimUserFromDb.isActive() != (scimUserFromRequest.isActive())) { return false; } if (!scimUserFromDb.getOrigin().equals(scimUserFromRequest.getOrigin())) { return false; } return true; } "," public boolean isAllowed(HttpServletRequest request) throws IOException { String requestBody = IOUtils.toString(request.getReader()); ScimUser scimUserFromRequest = JsonUtils.readValue(requestBody, ScimUser.class); String id = UaaUrlUtils.extractPathVariableFromUrl(USER_ID_PATH_PARAMETER_INDEX, UaaUrlUtils.getRequestPath(request)); String zoneId = IdentityZoneHolder.get().getId(); ScimUser scimUserFromDb; try { scimUserFromDb = scimUserProvisioning.retrieve(id, zoneId); } catch (ScimResourceNotFoundException e) { return true; } if (!scimUserFromDb.getPrimaryEmail().equals(scimUserFromRequest.getPrimaryEmail())) { return false; } if (!scimUserFromDb.getEmails().containsAll(scimUserFromRequest.getEmails())) { return false; } if (!scimUserFromDb.getUserName().equals(scimUserFromRequest.getUserName())) { return false; } if (scimUserFromDb.isVerified() != scimUserFromRequest.isVerified()) { return false; } if (scimUserFromDb.isActive() != (scimUserFromRequest.isActive())) { return false; } if (!scimUserFromDb.getOrigin().equals(scimUserFromRequest.getOrigin())) { return false; } return true; } ",TRUE,ScimUserSelfUpdateAllowed.java " void setUp() { httpRequest = new MockHttpServletRequest(); mockScimUserProvisioning = mock(ScimUserProvisioning.class); scimUserSelfUpdateAllowed = new ScimUserSelfUpdateAllowed(mockScimUserProvisioning); scimUserFromRequest = new ScimUser(); scimUserID = RandomStringUtils.randomAlphabetic(5); scimUserFromRequest.setUserName(""originalUserName""); scimUserFromRequest.setPrimaryEmail(""originalEmail@uaa.com""); ScimUser.Name scimUserName = new ScimUser.Name(""originalGivenName"", ""originalFamilyName""); scimUserFromRequest.setName(scimUserName); scimUserFromRequest.setVerified(false); scimUserFromRequest.setActive(false); scimUserFromRequest.setOrigin(""originalOrigin""); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); scimUserFromDB = new ScimUser(); scimUserFromDB.setId(scimUserID); scimUserFromDB.setUserName(""originalUserName""); scimUserFromDB.setPrimaryEmail(""originalEmail@uaa.com""); ScimUser.Name scimUserNameFromDB = new ScimUser.Name(""originalGivenName"", ""originalFamilyName""); scimUserFromDB.setName(scimUserNameFromDB); scimUserFromDB.setVerified(false); scimUserFromDB.setActive(false); scimUserFromDB.setOrigin(""originalOrigin""); identityZone = MultitenancyFixture.identityZone(RandomStringUtils.randomAlphabetic(5), RandomStringUtils.randomAlphabetic(5)); IdentityZoneHolder.set(identityZone); when(mockScimUserProvisioning.retrieve(scimUserID, identityZone.getId())).thenReturn(scimUserFromDB); httpRequest.setPathInfo(""/Users/"" + scimUserID); } "," void setUp() { httpRequest = new MockHttpServletRequest(); mockScimUserProvisioning = mock(ScimUserProvisioning.class); scimUserSelfUpdateAllowed = new ScimUserSelfUpdateAllowed(mockScimUserProvisioning); scimUserFromRequest = new ScimUser(); scimUserID = RandomStringUtils.randomAlphabetic(5); scimUserFromRequest.setUserName(""originalUserName""); scimUserFromRequest.setPrimaryEmail(""originalEmail@uaa.com""); ScimUser.Name scimUserName = new ScimUser.Name(""originalGivenName"", ""originalFamilyName""); scimUserFromRequest.setName(scimUserName); scimUserFromRequest.setVerified(false); scimUserFromRequest.setActive(false); scimUserFromRequest.setOrigin(""originalOrigin""); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); scimUserFromDB = new ScimUser(); scimUserFromDB.setId(scimUserID); scimUserFromDB.setUserName(""originalUserName""); scimUserFromDB.setPrimaryEmail(""originalEmail@uaa.com""); ScimUser.Name scimUserNameFromDB = new ScimUser.Name(""originalGivenName"", ""originalFamilyName""); scimUserFromDB.setName(scimUserNameFromDB); scimUserFromDB.setVerified(false); scimUserFromDB.setActive(false); scimUserFromDB.setOrigin(""originalOrigin""); identityZone = MultitenancyFixture.identityZone(RandomStringUtils.randomAlphabetic(5), RandomStringUtils.randomAlphabetic(5)); IdentityZoneHolder.set(identityZone); when(mockScimUserProvisioning.retrieve(scimUserID, identityZone.getId())).thenReturn(scimUserFromDB); httpRequest.setPathInfo(""/Users/"" + scimUserID); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isAllowedToUpdateScimUser_WithSameValue() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(true)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setupNoUserInDB() { when(mockScimUserProvisioning.retrieve(scimUserID, identityZone.getId())).thenThrow(ScimResourceNotFoundException.class); } "," void setupNoUserInDB() { when(mockScimUserProvisioning.retrieve(scimUserID, identityZone.getId())).thenThrow(ScimResourceNotFoundException.class); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isAllowed() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(true)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setup() { scimUserFromRequest.setName(new ScimUser.Name(""updatedGivenName"", ""updatedFamilyName"")); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } "," void setup() { scimUserFromRequest.setName(new ScimUser.Name(""updatedGivenName"", ""updatedFamilyName"")); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isAllowedToUpdateGivenAndFamilyName() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(true)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " "," void setup() { scimUserFromRequest.setEmails(null); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " "," void isNotAllowedToUpdateField() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(false)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setup() { scimUserFromRequest.setEmails(null); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } "," void setup() { scimUserFromRequest.addEmail(""abc""); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " "," void isNotAllowedToUpdateField() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(false)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setup() { scimUserFromRequest.setUserName(null); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } "," void setup() { scimUserFromRequest.setUserName(null); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isNotAllowedToUpdateField() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(false)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setup() { scimUserFromRequest.setVerified(true); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } "," void setup() { scimUserFromRequest.setVerified(true); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isNotAllowedToUpdateField() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(false)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setup() { scimUserFromRequest.setActive(true); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } "," void setup() { scimUserFromRequest.setActive(true); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isNotAllowedToUpdateField() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(false)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " void setup() { scimUserFromRequest.setOrigin(""updatedOrigin""); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } "," void setup() { scimUserFromRequest.setOrigin(""updatedOrigin""); httpRequest.setContent(JsonUtils.writeValueAsBytes(scimUserFromRequest)); } ",FALSE,ScimUserSelfUpdateAllowedTest.java " "," void isNotAllowedToUpdateField() throws IOException { assertThat(scimUserSelfUpdateAllowed.isAllowed(httpRequest), is(false)); } ",TRUE,ScimUserSelfUpdateAllowedTest.java " public ResourceRegion toResourceRegion(Resource resource) { // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards... // Note: custom InputStreamResource subclasses could provide a pre-calculated content length! Assert.isTrue(resource.getClass() != InputStreamResource.class, ""Cannot convert an InputStreamResource to a ResourceRegion""); try { long contentLength = resource.contentLength(); Assert.isTrue(contentLength > 0, ""Resource content length should be > 0""); long start = getRangeStart(contentLength); long end = getRangeEnd(contentLength); return new ResourceRegion(resource, start, end - start + 1); } catch (IOException ex) { throw new IllegalArgumentException(""Failed to convert Resource to ResourceRegion"", ex); } } "," public ResourceRegion toResourceRegion(Resource resource) { // Don't try to determine contentLength on InputStreamResource - cannot be read afterwards... // Note: custom InputStreamResource subclasses could provide a pre-calculated content length! Assert.isTrue(resource.getClass() != InputStreamResource.class, ""Cannot convert an InputStreamResource to a ResourceRegion""); long contentLength = getLengthFor(resource); long start = getRangeStart(contentLength); long end = getRangeEnd(contentLength); return new ResourceRegion(resource, start, end - start + 1); } ",TRUE,HttpRange.java " "," private static long getLengthFor(Resource resource) { long contentLength; try { contentLength = resource.contentLength(); Assert.isTrue(contentLength > 0, ""Resource content length should be > 0""); } catch (IOException ex) { throw new IllegalArgumentException(""Failed to obtain Resource content length"", ex); } return contentLength; } ",TRUE,HttpRange.java " public static HttpRange createByteRange(long firstBytePos) { return new ByteRange(firstBytePos, null); } "," public static HttpRange createByteRange(long firstBytePos) { return new ByteRange(firstBytePos, null); } ",FALSE,HttpRange.java " public static HttpRange createByteRange(long firstBytePos, long lastBytePos) { return new ByteRange(firstBytePos, lastBytePos); } "," public static HttpRange createByteRange(long firstBytePos, long lastBytePos) { return new ByteRange(firstBytePos, lastBytePos); } ",FALSE,HttpRange.java " public static HttpRange createSuffixRange(long suffixLength) { return new SuffixByteRange(suffixLength); } "," public static HttpRange createSuffixRange(long suffixLength) { return new SuffixByteRange(suffixLength); } ",FALSE,HttpRange.java " public static List parseRanges(@Nullable String ranges) { if (!StringUtils.hasLength(ranges)) { return Collections.emptyList(); } if (!ranges.startsWith(BYTE_RANGE_PREFIX)) { throw new IllegalArgumentException(""Range '"" + ranges + ""' does not start with 'bytes='""); } ranges = ranges.substring(BYTE_RANGE_PREFIX.length()); String[] tokens = StringUtils.tokenizeToStringArray(ranges, "",""); List result = new ArrayList<>(tokens.length); for (String token : tokens) { result.add(parseRange(token)); } return result; } "," public static List parseRanges(@Nullable String ranges) { if (!StringUtils.hasLength(ranges)) { return Collections.emptyList(); } if (!ranges.startsWith(BYTE_RANGE_PREFIX)) { throw new IllegalArgumentException(""Range '"" + ranges + ""' does not start with 'bytes='""); } ranges = ranges.substring(BYTE_RANGE_PREFIX.length()); String[] tokens = StringUtils.tokenizeToStringArray(ranges, "",""); Assert.isTrue(tokens.length <= MAX_RANGES, () -> ""Too many ranges "" + tokens.length); List result = new ArrayList<>(tokens.length); for (String token : tokens) { result.add(parseRange(token)); } return result; } ",TRUE,HttpRange.java " private static HttpRange parseRange(String range) { Assert.hasLength(range, ""Range String must not be empty""); int dashIdx = range.indexOf('-'); if (dashIdx > 0) { long firstPos = Long.parseLong(range.substring(0, dashIdx)); if (dashIdx < range.length() - 1) { Long lastPos = Long.parseLong(range.substring(dashIdx + 1, range.length())); return new ByteRange(firstPos, lastPos); } else { return new ByteRange(firstPos, null); } } else if (dashIdx == 0) { long suffixLength = Long.parseLong(range.substring(1)); return new SuffixByteRange(suffixLength); } else { throw new IllegalArgumentException(""Range '"" + range + ""' does not contain \""-\""""); } } "," private static HttpRange parseRange(String range) { Assert.hasLength(range, ""Range String must not be empty""); int dashIdx = range.indexOf('-'); if (dashIdx > 0) { long firstPos = Long.parseLong(range.substring(0, dashIdx)); if (dashIdx < range.length() - 1) { Long lastPos = Long.parseLong(range.substring(dashIdx + 1, range.length())); return new ByteRange(firstPos, lastPos); } else { return new ByteRange(firstPos, null); } } else if (dashIdx == 0) { long suffixLength = Long.parseLong(range.substring(1)); return new SuffixByteRange(suffixLength); } else { throw new IllegalArgumentException(""Range '"" + range + ""' does not contain \""-\""""); } } ",FALSE,HttpRange.java " public static List toResourceRegions(List ranges, Resource resource) { if (CollectionUtils.isEmpty(ranges)) { return Collections.emptyList(); } List regions = new ArrayList<>(ranges.size()); for (HttpRange range : ranges) { regions.add(range.toResourceRegion(resource)); } return regions; } "," public static List toResourceRegions(List ranges, Resource resource) { if (CollectionUtils.isEmpty(ranges)) { return Collections.emptyList(); } List regions = new ArrayList<>(ranges.size()); for (HttpRange range : ranges) { regions.add(range.toResourceRegion(resource)); } if (ranges.size() > 1) { long length = getLengthFor(resource); long total = regions.stream().map(ResourceRegion::getCount).reduce(0L, (count, sum) -> sum + count); Assert.isTrue(total < length, () -> ""The sum of all ranges ("" + total + "") "" + ""should be less than the resource length ("" + length + "")""); } return regions; } ",TRUE,HttpRange.java " public static String toString(Collection ranges) { Assert.notEmpty(ranges, ""Ranges Collection must not be empty""); StringBuilder builder = new StringBuilder(BYTE_RANGE_PREFIX); for (Iterator iterator = ranges.iterator(); iterator.hasNext(); ) { HttpRange range = iterator.next(); builder.append(range); if (iterator.hasNext()) { builder.append("", ""); } } return builder.toString(); } "," public static String toString(Collection ranges) { Assert.notEmpty(ranges, ""Ranges Collection must not be empty""); StringBuilder builder = new StringBuilder(BYTE_RANGE_PREFIX); for (Iterator iterator = ranges.iterator(); iterator.hasNext(); ) { HttpRange range = iterator.next(); builder.append(range); if (iterator.hasNext()) { builder.append("", ""); } } return builder.toString(); } ",FALSE,HttpRange.java " public ByteRange(long firstPos, @Nullable Long lastPos) { assertPositions(firstPos, lastPos); this.firstPos = firstPos; this.lastPos = lastPos; } "," public ByteRange(long firstPos, @Nullable Long lastPos) { assertPositions(firstPos, lastPos); this.firstPos = firstPos; this.lastPos = lastPos; } ",FALSE,HttpRange.java " private void assertPositions(long firstBytePos, @Nullable Long lastBytePos) { if (firstBytePos < 0) { throw new IllegalArgumentException(""Invalid first byte position: "" + firstBytePos); } if (lastBytePos != null && lastBytePos < firstBytePos) { throw new IllegalArgumentException(""firstBytePosition="" + firstBytePos + "" should be less then or equal to lastBytePosition="" + lastBytePos); } } "," private void assertPositions(long firstBytePos, @Nullable Long lastBytePos) { if (firstBytePos < 0) { throw new IllegalArgumentException(""Invalid first byte position: "" + firstBytePos); } if (lastBytePos != null && lastBytePos < firstBytePos) { throw new IllegalArgumentException(""firstBytePosition="" + firstBytePos + "" should be less then or equal to lastBytePosition="" + lastBytePos); } } ",FALSE,HttpRange.java " public long getRangeStart(long length) { return this.firstPos; } "," public long getRangeStart(long length) { return this.firstPos; } ",FALSE,HttpRange.java " public long getRangeEnd(long length) { if (this.lastPos != null && this.lastPos < length) { return this.lastPos; } else { return length - 1; } } "," public long getRangeEnd(long length) { if (this.lastPos != null && this.lastPos < length) { return this.lastPos; } else { return length - 1; } } ",FALSE,HttpRange.java " public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof ByteRange)) { return false; } ByteRange otherRange = (ByteRange) other; return (this.firstPos == otherRange.firstPos && ObjectUtils.nullSafeEquals(this.lastPos, otherRange.lastPos)); } "," public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof ByteRange)) { return false; } ByteRange otherRange = (ByteRange) other; return (this.firstPos == otherRange.firstPos && ObjectUtils.nullSafeEquals(this.lastPos, otherRange.lastPos)); } ",FALSE,HttpRange.java " public int hashCode() { return (ObjectUtils.nullSafeHashCode(this.firstPos) * 31 + ObjectUtils.nullSafeHashCode(this.lastPos)); } "," public int hashCode() { return (ObjectUtils.nullSafeHashCode(this.firstPos) * 31 + ObjectUtils.nullSafeHashCode(this.lastPos)); } ",FALSE,HttpRange.java " public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.firstPos); builder.append('-'); if (this.lastPos != null) { builder.append(this.lastPos); } return builder.toString(); } "," public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.firstPos); builder.append('-'); if (this.lastPos != null) { builder.append(this.lastPos); } return builder.toString(); } ",FALSE,HttpRange.java " public SuffixByteRange(long suffixLength) { if (suffixLength < 0) { throw new IllegalArgumentException(""Invalid suffix length: "" + suffixLength); } this.suffixLength = suffixLength; } "," public SuffixByteRange(long suffixLength) { if (suffixLength < 0) { throw new IllegalArgumentException(""Invalid suffix length: "" + suffixLength); } this.suffixLength = suffixLength; } ",FALSE,HttpRange.java " public long getRangeStart(long length) { if (this.suffixLength < length) { return length - this.suffixLength; } else { return 0; } } "," public long getRangeStart(long length) { if (this.suffixLength < length) { return length - this.suffixLength; } else { return 0; } } ",FALSE,HttpRange.java " public long getRangeEnd(long length) { return length - 1; } "," public long getRangeEnd(long length) { return length - 1; } ",FALSE,HttpRange.java " public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof SuffixByteRange)) { return false; } SuffixByteRange otherRange = (SuffixByteRange) other; return (this.suffixLength == otherRange.suffixLength); } "," public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof SuffixByteRange)) { return false; } SuffixByteRange otherRange = (SuffixByteRange) other; return (this.suffixLength == otherRange.suffixLength); } ",FALSE,HttpRange.java " public int hashCode() { return Long.hashCode(this.suffixLength); } "," public int hashCode() { return Long.hashCode(this.suffixLength); } ",FALSE,HttpRange.java " public String toString() { return ""-"" + this.suffixLength; } "," public String toString() { return ""-"" + this.suffixLength; } ",FALSE,HttpRange.java " public void invalidFirstPosition() { HttpRange.createByteRange(-1); } "," public void invalidFirstPosition() { HttpRange.createByteRange(-1); } ",FALSE,HttpRangeTests.java " public void invalidLastLessThanFirst() { HttpRange.createByteRange(10, 9); } "," public void invalidLastLessThanFirst() { HttpRange.createByteRange(10, 9); } ",FALSE,HttpRangeTests.java " public void invalidSuffixLength() { HttpRange.createSuffixRange(-1); } "," public void invalidSuffixLength() { HttpRange.createSuffixRange(-1); } ",FALSE,HttpRangeTests.java " public void byteRange() { HttpRange range = HttpRange.createByteRange(0, 499); assertEquals(0, range.getRangeStart(1000)); assertEquals(499, range.getRangeEnd(1000)); } "," public void byteRange() { HttpRange range = HttpRange.createByteRange(0, 499); assertEquals(0, range.getRangeStart(1000)); assertEquals(499, range.getRangeEnd(1000)); } ",FALSE,HttpRangeTests.java " public void byteRangeWithoutLastPosition() { HttpRange range = HttpRange.createByteRange(9500); assertEquals(9500, range.getRangeStart(10000)); assertEquals(9999, range.getRangeEnd(10000)); } "," public void byteRangeWithoutLastPosition() { HttpRange range = HttpRange.createByteRange(9500); assertEquals(9500, range.getRangeStart(10000)); assertEquals(9999, range.getRangeEnd(10000)); } ",FALSE,HttpRangeTests.java " public void byteRangeOfZeroLength() { HttpRange range = HttpRange.createByteRange(9500, 9500); assertEquals(9500, range.getRangeStart(10000)); assertEquals(9500, range.getRangeEnd(10000)); } "," public void byteRangeOfZeroLength() { HttpRange range = HttpRange.createByteRange(9500, 9500); assertEquals(9500, range.getRangeStart(10000)); assertEquals(9500, range.getRangeEnd(10000)); } ",FALSE,HttpRangeTests.java " public void suffixRange() { HttpRange range = HttpRange.createSuffixRange(500); assertEquals(500, range.getRangeStart(1000)); assertEquals(999, range.getRangeEnd(1000)); } "," public void suffixRange() { HttpRange range = HttpRange.createSuffixRange(500); assertEquals(500, range.getRangeStart(1000)); assertEquals(999, range.getRangeEnd(1000)); } ",FALSE,HttpRangeTests.java " public void suffixRangeShorterThanRepresentation() { HttpRange range = HttpRange.createSuffixRange(500); assertEquals(0, range.getRangeStart(350)); assertEquals(349, range.getRangeEnd(350)); } "," public void suffixRangeShorterThanRepresentation() { HttpRange range = HttpRange.createSuffixRange(500); assertEquals(0, range.getRangeStart(350)); assertEquals(349, range.getRangeEnd(350)); } ",FALSE,HttpRangeTests.java " public void parseRanges() { List ranges = HttpRange.parseRanges(""bytes=0-0,500-,-1""); assertEquals(3, ranges.size()); assertEquals(0, ranges.get(0).getRangeStart(1000)); assertEquals(0, ranges.get(0).getRangeEnd(1000)); assertEquals(500, ranges.get(1).getRangeStart(1000)); assertEquals(999, ranges.get(1).getRangeEnd(1000)); assertEquals(999, ranges.get(2).getRangeStart(1000)); assertEquals(999, ranges.get(2).getRangeEnd(1000)); } "," public void parseRanges() { List ranges = HttpRange.parseRanges(""bytes=0-0,500-,-1""); assertEquals(3, ranges.size()); assertEquals(0, ranges.get(0).getRangeStart(1000)); assertEquals(0, ranges.get(0).getRangeEnd(1000)); assertEquals(500, ranges.get(1).getRangeStart(1000)); assertEquals(999, ranges.get(1).getRangeEnd(1000)); assertEquals(999, ranges.get(2).getRangeStart(1000)); assertEquals(999, ranges.get(2).getRangeEnd(1000)); } ",FALSE,HttpRangeTests.java " "," public void parseRangesValidations() { // 1. At limit.. StringBuilder sb = new StringBuilder(""bytes=0-0""); for (int i=0; i < 99; i++) { sb.append("","").append(i).append(""-"").append(i + 1); } List ranges = HttpRange.parseRanges(sb.toString()); assertEquals(100, ranges.size()); // 2. Above limit.. sb = new StringBuilder(""bytes=0-0""); for (int i=0; i < 100; i++) { sb.append("","").append(i).append(""-"").append(i + 1); } try { HttpRange.parseRanges(sb.toString()); fail(); } catch (IllegalArgumentException ex) { // Expected } } ",TRUE,HttpRangeTests.java " public void rangeToString() { List ranges = new ArrayList<>(); ranges.add(HttpRange.createByteRange(0, 499)); ranges.add(HttpRange.createByteRange(9500)); ranges.add(HttpRange.createSuffixRange(500)); assertEquals(""Invalid Range header"", ""bytes=0-499, 9500-, -500"", HttpRange.toString(ranges)); } "," public void rangeToString() { List ranges = new ArrayList<>(); ranges.add(HttpRange.createByteRange(0, 499)); ranges.add(HttpRange.createByteRange(9500)); ranges.add(HttpRange.createSuffixRange(500)); assertEquals(""Invalid Range header"", ""bytes=0-499, 9500-, -500"", HttpRange.toString(ranges)); } ",FALSE,HttpRangeTests.java " public void toResourceRegion() { byte[] bytes = ""Spring Framework"".getBytes(StandardCharsets.UTF_8); ByteArrayResource resource = new ByteArrayResource(bytes); HttpRange range = HttpRange.createByteRange(0, 5); ResourceRegion region = range.toResourceRegion(resource); assertEquals(resource, region.getResource()); assertEquals(0L, region.getPosition()); assertEquals(6L, region.getCount()); } "," public void toResourceRegion() { byte[] bytes = ""Spring Framework"".getBytes(StandardCharsets.UTF_8); ByteArrayResource resource = new ByteArrayResource(bytes); HttpRange range = HttpRange.createByteRange(0, 5); ResourceRegion region = range.toResourceRegion(resource); assertEquals(resource, region.getResource()); assertEquals(0L, region.getPosition()); assertEquals(6L, region.getCount()); } ",FALSE,HttpRangeTests.java " public void toResourceRegionInputStreamResource() { InputStreamResource resource = mock(InputStreamResource.class); HttpRange range = HttpRange.createByteRange(0, 9); range.toResourceRegion(resource); } "," public void toResourceRegionInputStreamResource() { InputStreamResource resource = mock(InputStreamResource.class); HttpRange range = HttpRange.createByteRange(0, 9); range.toResourceRegion(resource); } ",FALSE,HttpRangeTests.java " public void toResourceRegionIllegalLength() { ByteArrayResource resource = mock(ByteArrayResource.class); given(resource.contentLength()).willReturn(-1L); HttpRange range = HttpRange.createByteRange(0, 9); range.toResourceRegion(resource); } "," public void toResourceRegionIllegalLength() { ByteArrayResource resource = mock(ByteArrayResource.class); given(resource.contentLength()).willReturn(-1L); HttpRange range = HttpRange.createByteRange(0, 9); range.toResourceRegion(resource); } ",FALSE,HttpRangeTests.java " public void toResourceRegionExceptionLength() throws IOException { InputStreamResource resource = mock(InputStreamResource.class); given(resource.contentLength()).willThrow(IOException.class); HttpRange range = HttpRange.createByteRange(0, 9); range.toResourceRegion(resource); } "," public void toResourceRegionExceptionLength() throws IOException { InputStreamResource resource = mock(InputStreamResource.class); given(resource.contentLength()).willThrow(IOException.class); HttpRange range = HttpRange.createByteRange(0, 9); range.toResourceRegion(resource); } ",FALSE,HttpRangeTests.java " "," public void toResourceRegionsValidations() { byte[] bytes = ""12345"".getBytes(StandardCharsets.UTF_8); ByteArrayResource resource = new ByteArrayResource(bytes); // 1. Below length List ranges = HttpRange.parseRanges(""bytes=0-1,2-3""); List regions = HttpRange.toResourceRegions(ranges, resource); assertEquals(2, regions.size()); // 2. At length ranges = HttpRange.parseRanges(""bytes=0-1,2-4""); try { HttpRange.toResourceRegions(ranges, resource); fail(); } catch (IllegalArgumentException ex) { // Expected.. } } ",TRUE,HttpRangeTests.java " public void testIntercepDefault() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); // by default the interceptor doesn't accept any cookies CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.intercept(invocation); assertTrue(action.getCookiesMap().isEmpty()); assertNull(action.getCookie1(), null); assertNull(action.getCookie2(), null); assertNull(action.getCookie3(), null); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie1"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie2"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie3"")); } "," public void testIntercepDefault() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); // by default the interceptor doesn't accept any cookies CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.intercept(invocation); assertTrue(action.getCookiesMap().isEmpty()); assertNull(action.getCookie1(), null); assertNull(action.getCookie2(), null); assertNull(action.getCookie3(), null); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie1"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie2"")); assertNull(ActionContext.getContext().getValueStack().findValue(""cookie3"")); } ",FALSE,CookieInterceptorTest.java " public void testInterceptAll1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""*""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptAll1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""*""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptAll2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie2, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptAll2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie2, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 3); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), ""cookie2value""); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), ""cookie2value""); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), ""cookie2value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameOnly1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptSelectedCookiesNameOnly1() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value, cookie2value, cookie3value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameOnly2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptSelectedCookiesNameOnly2() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""*""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameOnly3() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } "," public void testInterceptSelectedCookiesNameOnly3() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 2); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), ""cookie3value""); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), ""cookie3value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), ""cookie3value""); } ",FALSE,CookieInterceptorTest.java " public void testInterceptSelectedCookiesNameAndValue() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 1); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), null); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), null); } "," public void testInterceptSelectedCookiesNameAndValue() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie[] { new Cookie(""cookie1"", ""cookie1value""), new Cookie(""cookie2"", ""cookie2value""), new Cookie(""cookie3"", ""cookie3value"") }); ServletActionContext.setRequest(request); MockActionWithCookieAware action = new MockActionWithCookieAware(); ActionContext.getContext().getValueStack().push(action); MockControl actionInvocationControl = MockControl.createControl(ActionInvocation.class); ActionInvocation invocation = (ActionInvocation) actionInvocationControl.getMock(); actionInvocationControl.expectAndDefaultReturn( invocation.getAction(), action); actionInvocationControl.expectAndDefaultReturn( invocation.invoke(), Action.SUCCESS); actionInvocationControl.replay(); CookieInterceptor interceptor = new CookieInterceptor(); interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""cookie1, cookie3""); interceptor.setCookiesValue(""cookie1value""); interceptor.intercept(invocation); assertFalse(action.getCookiesMap().isEmpty()); assertEquals(action.getCookiesMap().size(), 1); assertEquals(action.getCookiesMap().get(""cookie1""), ""cookie1value""); assertEquals(action.getCookiesMap().get(""cookie2""), null); assertEquals(action.getCookiesMap().get(""cookie3""), null); assertEquals(action.getCookie1(), ""cookie1value""); assertEquals(action.getCookie2(), null); assertEquals(action.getCookie3(), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie1""), ""cookie1value""); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie2""), null); assertEquals(ActionContext.getContext().getValueStack().findValue(""cookie3""), null); } ",FALSE,CookieInterceptorTest.java " public void testCookiesWithClassPollution() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String pollution1 = ""model['class']['classLoader']['jarPath']""; String pollution2 = ""model.class.classLoader.jarPath""; String pollution3 = ""class.classLoader.jarPath""; String pollution4 = ""class['classLoader']['jarPath']""; String pollution5 = ""model[\""class\""]['classLoader']['jarPath']""; String pollution6 = ""class[\""classLoader\""]['jarPath']""; request.setCookies( new Cookie(pollution1, ""pollution1""), new Cookie(""pollution1"", pollution1), new Cookie(pollution2, ""pollution2""), new Cookie(""pollution2"", pollution2), new Cookie(pollution3, ""pollution3""), new Cookie(""pollution3"", pollution3), new Cookie(pollution4, ""pollution4""), new Cookie(""pollution4"", pollution4), new Cookie(pollution5, ""pollution5""), new Cookie(""pollution5"", pollution5), new Cookie(pollution6, ""pollution6""), new Cookie(""pollution6"", pollution6) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(pollution1)); assertFalse(excludedName.get(pollution2)); assertFalse(excludedName.get(pollution3)); assertFalse(excludedName.get(pollution4)); assertFalse(excludedName.get(pollution5)); assertFalse(excludedName.get(pollution6)); assertFalse(excludedValue.get(pollution1)); assertFalse(excludedValue.get(pollution2)); assertFalse(excludedValue.get(pollution3)); assertFalse(excludedValue.get(pollution4)); assertFalse(excludedValue.get(pollution5)); assertFalse(excludedValue.get(pollution6)); } "," public void testCookiesWithClassPollution() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String pollution1 = ""model['class']['classLoader']['jarPath']""; String pollution2 = ""model.class.classLoader.jarPath""; String pollution3 = ""class.classLoader.jarPath""; String pollution4 = ""class['classLoader']['jarPath']""; String pollution5 = ""model[\""class\""]['classLoader']['jarPath']""; String pollution6 = ""class[\""classLoader\""]['jarPath']""; request.setCookies( new Cookie(pollution1, ""pollution1""), new Cookie(""pollution1"", pollution1), new Cookie(pollution2, ""pollution2""), new Cookie(""pollution2"", pollution2), new Cookie(pollution3, ""pollution3""), new Cookie(""pollution3"", pollution3), new Cookie(pollution4, ""pollution4""), new Cookie(""pollution4"", pollution4), new Cookie(pollution5, ""pollution5""), new Cookie(""pollution5"", pollution5), new Cookie(pollution6, ""pollution6""), new Cookie(""pollution6"", pollution6) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; DefaultExcludedPatternsChecker excludedPatternsChecker = new DefaultExcludedPatternsChecker(); excludedPatternsChecker.setAdditionalExcludePatterns("".*(^|\\.|\\[|'|\"")class(\\.|\\[|'|\"").*""); interceptor.setExcludedPatternsChecker(excludedPatternsChecker); interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(pollution1)); assertFalse(excludedName.get(pollution2)); assertFalse(excludedName.get(pollution3)); assertFalse(excludedName.get(pollution4)); assertFalse(excludedName.get(pollution5)); assertFalse(excludedName.get(pollution6)); assertFalse(excludedValue.get(pollution1)); assertFalse(excludedValue.get(pollution2)); assertFalse(excludedValue.get(pollution3)); assertFalse(excludedValue.get(pollution4)); assertFalse(excludedValue.get(pollution5)); assertFalse(excludedValue.get(pollution6)); } ",TRUE,CookieInterceptorTest.java " public void testCookiesWithStrutsInternalsAccess() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String sessionCookieName = ""session.userId""; String sessionCookieValue = ""session.userId=1""; String appCookieName = ""application.userId""; String appCookieValue = ""application.userId=1""; String reqCookieName = ""request.userId""; String reqCookieValue = ""request.userId=1""; request.setCookies( new Cookie(sessionCookieName, ""1""), new Cookie(""1"", sessionCookieValue), new Cookie(appCookieName, ""1""), new Cookie(""1"", appCookieValue), new Cookie(reqCookieName, ""1""), new Cookie(""1"", reqCookieValue) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(sessionCookieName)); assertFalse(excludedName.get(appCookieName)); assertFalse(excludedName.get(reqCookieName)); assertFalse(excludedValue.get(sessionCookieValue)); assertFalse(excludedValue.get(appCookieValue)); assertFalse(excludedValue.get(reqCookieValue)); } "," public void testCookiesWithStrutsInternalsAccess() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); String sessionCookieName = ""session.userId""; String sessionCookieValue = ""session.userId=1""; String appCookieName = ""application.userId""; String appCookieValue = ""application.userId=1""; String reqCookieName = ""request.userId""; String reqCookieValue = ""request.userId=1""; request.setCookies( new Cookie(sessionCookieName, ""1""), new Cookie(""1"", sessionCookieValue), new Cookie(appCookieName, ""1""), new Cookie(""1"", appCookieValue), new Cookie(reqCookieName, ""1""), new Cookie(""1"", reqCookieValue) ); ServletActionContext.setRequest(request); final Map excludedName = new HashMap(); final Map excludedValue = new HashMap(); CookieInterceptor interceptor = new CookieInterceptor() { @Override protected boolean isAcceptableName(String name) { boolean accepted = super.isAcceptableName(name); excludedName.put(name, accepted); return accepted; } @Override protected boolean isAcceptableValue(String value) { boolean accepted = super.isAcceptableValue(value); excludedValue.put(value, accepted); return accepted; } }; interceptor.setExcludedPatternsChecker(new DefaultExcludedPatternsChecker()); interceptor.setCookiesName(""*""); MockActionInvocation invocation = new MockActionInvocation(); invocation.setAction(new MockActionWithCookieAware()); interceptor.intercept(invocation); assertFalse(excludedName.get(sessionCookieName)); assertFalse(excludedName.get(appCookieName)); assertFalse(excludedName.get(reqCookieName)); assertFalse(excludedValue.get(sessionCookieValue)); assertFalse(excludedValue.get(appCookieValue)); assertFalse(excludedValue.get(reqCookieValue)); } ",FALSE,CookieInterceptorTest.java " public void setCookiesMap(Map cookies) { this.cookies = cookies; } "," public void setCookiesMap(Map cookies) { this.cookies = cookies; } ",FALSE,CookieInterceptorTest.java " public Map getCookiesMap() { return this.cookies; } "," public Map getCookiesMap() { return this.cookies; } ",FALSE,CookieInterceptorTest.java " public String getCookie1() { return cookie1; } "," public String getCookie1() { return cookie1; } ",FALSE,CookieInterceptorTest.java " public void setCookie1(String cookie1) { this.cookie1 = cookie1; } "," public void setCookie1(String cookie1) { this.cookie1 = cookie1; } ",FALSE,CookieInterceptorTest.java " public String getCookie2() { return cookie2; } "," public String getCookie2() { return cookie2; } ",FALSE,CookieInterceptorTest.java " public void setCookie2(String cookie2) { this.cookie2 = cookie2; } "," public void setCookie2(String cookie2) { this.cookie2 = cookie2; } ",FALSE,CookieInterceptorTest.java " public String getCookie3() { return cookie3; } "," public String getCookie3() { return cookie3; } ",FALSE,CookieInterceptorTest.java " public void setCookie3(String cookie3) { this.cookie3 = cookie3; } "," public void setCookie3(String cookie3) { this.cookie3 = cookie3; } ",FALSE,CookieInterceptorTest.java " public DefaultExcludedPatternsChecker() { setExcludedPatterns(EXCLUDED_PATTERNS); } "," public DefaultExcludedPatternsChecker() { setExcludedPatterns(EXCLUDED_PATTERNS); } ",FALSE,DefaultExcludedPatternsChecker.java " public void setOverrideExcludePatterns(String excludePatterns) { if (LOG.isWarnEnabled()) { LOG.warn(""Overriding excluded patterns [#0] with [#1], be aware that this affects all instances and safety of your application!"", XWorkConstants.OVERRIDE_EXCLUDED_PATTERNS, excludePatterns); } excludedPatterns = new HashSet(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } "," public void setOverrideExcludePatterns(String excludePatterns) { if (LOG.isWarnEnabled()) { LOG.warn(""Overriding excluded patterns [#0] with [#1], be aware that this affects all instances and safety of your application!"", XWorkConstants.OVERRIDE_EXCLUDED_PATTERNS, excludePatterns); } excludedPatterns = new HashSet(); for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } ",FALSE,DefaultExcludedPatternsChecker.java " public void setAdditionalExcludePatterns(String excludePatterns) { if (LOG.isDebugEnabled()) { LOG.debug(""Adding additional global patterns [#0] to excluded patterns!"", excludePatterns); } for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } "," public void setAdditionalExcludePatterns(String excludePatterns) { if (LOG.isDebugEnabled()) { LOG.debug(""Adding additional global patterns [#0] to excluded patterns!"", excludePatterns); } for (String pattern : TextParseUtil.commaDelimitedStringToSet(excludePatterns)) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } ",FALSE,DefaultExcludedPatternsChecker.java " public void setExcludedPatterns(String commaDelimitedPatterns) { setExcludedPatterns(TextParseUtil.commaDelimitedStringToSet(commaDelimitedPatterns)); } "," public void setExcludedPatterns(String commaDelimitedPatterns) { setExcludedPatterns(TextParseUtil.commaDelimitedStringToSet(commaDelimitedPatterns)); } ",FALSE,DefaultExcludedPatternsChecker.java " public void setExcludedPatterns(String[] patterns) { setExcludedPatterns(new HashSet(Arrays.asList(patterns))); } "," public void setExcludedPatterns(String[] patterns) { setExcludedPatterns(new HashSet(Arrays.asList(patterns))); } ",FALSE,DefaultExcludedPatternsChecker.java " public void setExcludedPatterns(Set patterns) { if (LOG.isTraceEnabled()) { LOG.trace(""Sets excluded patterns [#0]"", patterns); } excludedPatterns = new HashSet(patterns.size()); for (String pattern : patterns) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } "," public void setExcludedPatterns(Set patterns) { if (LOG.isTraceEnabled()) { LOG.trace(""Sets excluded patterns [#0]"", patterns); } excludedPatterns = new HashSet(patterns.size()); for (String pattern : patterns) { excludedPatterns.add(Pattern.compile(pattern, Pattern.CASE_INSENSITIVE)); } } ",FALSE,DefaultExcludedPatternsChecker.java " public IsExcluded isExcluded(String value) { for (Pattern excludedPattern : excludedPatterns) { if (excludedPattern.matcher(value).matches()) { if (LOG.isTraceEnabled()) { LOG.trace(""[#0] matches excluded pattern [#1]"", value, excludedPattern); } return IsExcluded.yes(excludedPattern); } } return IsExcluded.no(excludedPatterns); } "," public IsExcluded isExcluded(String value) { for (Pattern excludedPattern : excludedPatterns) { if (excludedPattern.matcher(value).matches()) { if (LOG.isTraceEnabled()) { LOG.trace(""[#0] matches excluded pattern [#1]"", value, excludedPattern); } return IsExcluded.yes(excludedPattern); } } return IsExcluded.no(excludedPatterns); } ",FALSE,DefaultExcludedPatternsChecker.java " public Set getExcludedPatterns() { return excludedPatterns; } "," public Set getExcludedPatterns() { return excludedPatterns; } ",FALSE,DefaultExcludedPatternsChecker.java " public void testHardcodedPatterns() throws Exception { // given List params = new ArrayList() { { add(""%{#application['test']}""); add(""%{#application.test}""); add(""%{#Application['test']}""); add(""%{#Application.test}""); add(""%{#session['test']}""); add(""%{#session.test}""); add(""%{#Session['test']}""); add(""%{#Session.test}""); add(""%{#struts['test']}""); add(""%{#struts.test}""); add(""%{#Struts['test']}""); add(""%{#Struts.test}""); add(""%{#request['test']}""); add(""%{#request.test}""); add(""%{#Request['test']}""); add(""%{#Request.test}""); add(""%{#servletRequest['test']}""); add(""%{#servletRequest.test}""); add(""%{#ServletRequest['test']}""); add(""%{#ServletRequest.test}""); add(""%{#servletResponse['test']}""); add(""%{#servletResponse.test}""); add(""%{#ServletResponse['test']}""); add(""%{#ServletResponse.test}""); add(""%{#parameters['test']}""); add(""%{#parameters.test}""); add(""%{#Parameters['test']}""); add(""%{#Parameters.test}""); add(""#context.get('com.opensymphony.xwork2.dispatcher.HttpServletResponse')""); add(""%{#context.get('com.opensymphony.xwork2.dispatcher.HttpServletResponse')}""); add(""#_memberAccess[\""allowStaticMethodAccess\""]= new java.lang.Boolean(true)""); add(""%{#_memberAccess[\""allowStaticMethodAccess\""]= new java.lang.Boolean(true)}""); add(""form.class.classLoader""); add(""form[\""class\""][\""classLoader\""]""); add(""form['class']['classLoader']""); add(""class['classLoader']""); add(""class[\""classLoader\""]""); add(""class.classLoader.resources.dirContext.docBase=tttt""); add(""Class.classLoader.resources.dirContext.docBase=tttt""); } }; ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker(); for (String param : params) { // when ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(param); // then assertTrue(""Access to "" + param + "" is possible!"", actual.isExcluded()); } } "," public void testHardcodedPatterns() throws Exception { // given List params = new ArrayList() { { add(""%{#application['test']}""); add(""%{#application.test}""); add(""%{#Application['test']}""); add(""%{#Application.test}""); add(""%{#session['test']}""); add(""%{#session.test}""); add(""%{#Session['test']}""); add(""%{#Session.test}""); add(""%{#struts['test']}""); add(""%{#struts.test}""); add(""%{#Struts['test']}""); add(""%{#Struts.test}""); add(""%{#request['test']}""); add(""%{#request.test}""); add(""%{#Request['test']}""); add(""%{#Request.test}""); add(""%{#servletRequest['test']}""); add(""%{#servletRequest.test}""); add(""%{#ServletRequest['test']}""); add(""%{#ServletRequest.test}""); add(""%{#servletResponse['test']}""); add(""%{#servletResponse.test}""); add(""%{#ServletResponse['test']}""); add(""%{#ServletResponse.test}""); add(""%{#parameters['test']}""); add(""%{#parameters.test}""); add(""%{#Parameters['test']}""); add(""%{#Parameters.test}""); add(""#context.get('com.opensymphony.xwork2.dispatcher.HttpServletResponse')""); add(""%{#context.get('com.opensymphony.xwork2.dispatcher.HttpServletResponse')}""); add(""#_memberAccess[\""allowStaticMethodAccess\""]= new java.lang.Boolean(true)""); add(""%{#_memberAccess[\""allowStaticMethodAccess\""]= new java.lang.Boolean(true)}""); add(""form.class.classLoader""); add(""form[\""class\""][\""classLoader\""]""); add(""form['class']['classLoader']""); add(""class['classLoader']""); add(""class[\""classLoader\""]""); add(""class.classLoader.resources.dirContext.docBase=tttt""); add(""Class.classLoader.resources.dirContext.docBase=tttt""); } }; DefaultExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker(); checker.setAdditionalExcludePatterns("".*(^|\\.|\\[|'|\"")class(\\.|\\[|'|\"").*""); for (String param : params) { // when ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(param); // then assertTrue(""Access to "" + param + "" is possible!"", actual.isExcluded()); } } ",TRUE,DefaultExcludedPatternsCheckerTest.java " public void testParamWithClassInName() throws Exception { // given List properParams = new ArrayList(); properParams.add(""eventClass""); properParams.add(""form.eventClass""); properParams.add(""form[\""eventClass\""]""); properParams.add(""form['eventClass']""); ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker(); for (String properParam : properParams) { // when ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(properParam); // then assertFalse(""Param '"" + properParam + ""' is excluded!"", actual.isExcluded()); } } "," public void testParamWithClassInName() throws Exception { // given List properParams = new ArrayList(); properParams.add(""eventClass""); properParams.add(""form.eventClass""); properParams.add(""form[\""eventClass\""]""); properParams.add(""form['eventClass']""); properParams.add(""class.super@demo.com""); properParams.add(""super.class@demo.com""); ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker(); for (String properParam : properParams) { // when ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(properParam); // then assertFalse(""Param '"" + properParam + ""' is excluded!"", actual.isExcluded()); } } ",TRUE,DefaultExcludedPatternsCheckerTest.java " public void testStrutsTokenIsExcluded() throws Exception { // given List tokens = new ArrayList(); tokens.add(""struts.token.name""); tokens.add(""struts.token""); ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker(); for (String token : tokens) { // when ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(token); // then assertTrue(""Param '"" + token + ""' is not excluded!"", actual.isExcluded()); } } "," public void testStrutsTokenIsExcluded() throws Exception { // given List tokens = new ArrayList(); tokens.add(""struts.token.name""); tokens.add(""struts.token""); ExcludedPatternsChecker checker = new DefaultExcludedPatternsChecker(); for (String token : tokens) { // when ExcludedPatternsChecker.IsExcluded actual = checker.isExcluded(token); // then assertTrue(""Param '"" + token + ""' is not excluded!"", actual.isExcluded()); } } ",FALSE,DefaultExcludedPatternsCheckerTest.java