id
stringlengths 8
13
| source
stringlengths 164
33.1k
| target
stringlengths 36
5.98k
|
---|---|---|
2280644_27
|
class MapCommand implements Command<T> {
public boolean contains(String name) {
return values.containsKey(name);
}
public Object getValue(String name);
public void setValue(String name, Object value);
public void resetValue(String name);
public Map<String, Object> getValues();
public boolean checkForRequiredOptions(ParsedLine pl);
void resetAll();
private final Key completeChar;
}
class MapCommandTest {
private final Key completeChar;
@Test
public void testCompletion() throws Exception {
|
TestConnection connection = new TestConnection(false);
// Build dynamic command.
DynCommand1 cmd = new DynCommand1();
DynamicOptionsProvider provider = new DynamicOptionsProvider();
MapProcessedCommandBuilder builder = MapProcessedCommandBuilder.builder();
builder.command(cmd);
// Retrieve dynamic options during completion.
builder.lookupAtCompletionOnly(true);
builder.name("dyn1");
builder.optionProvider(provider);
CommandRegistry registry = AeshCommandRegistryBuilder.builder()
.command(builder.create())
.create();
Settings settings = SettingsBuilder.builder()
.logging(true)
.connection(connection)
.commandRegistry(registry)
.build();
ReadlineConsole console = new ReadlineConsole(settings);
console.setPrompt(new Prompt(""));
console.start();
// First test without any dynamic option provided.
connection.clearOutputBuffer();
connection.read("d");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 ", connection.getOutputBuffer());
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 ", connection.getOutputBuffer());
connection.read("--");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --", connection.getOutputBuffer());
// Then add dynamic options
provider.options = getOptions();
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn", connection.getOutputBuffer());
connection.read("1");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn1-withvalue=", connection.getOutputBuffer());
connection.read("cdcsdc ");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn1-withvalue=cdcsdc --opt-dyn", connection.getOutputBuffer());
connection.read("2");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn1-withvalue=cdcsdc --opt-dyn2-withvalue=", connection.getOutputBuffer());
connection.read("xxx ");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn1-withvalue=cdcsdc --opt-dyn2-withvalue=xxx --opt-dyn3-novalue ", connection.getOutputBuffer());
// No completion if the options already exist in the buffer.
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn1-withvalue=cdcsdc --opt-dyn2-withvalue=xxx --opt-dyn3-novalue ", connection.getOutputBuffer());
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
{
String val = (String) cmd.options.get("opt-dyn1-withvalue");
assertEquals("cdcsdc", val);
}
{
String val = (String) cmd.options.get("opt-dyn2-withvalue");
assertEquals("xxx", val);
}
assertTrue(cmd.contains("opt-dyn3-novalue"));
// Invalid option
connection.read("dyn1 --opt-dyn3-novalue--");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --opt-dyn3-novalue--", connection.getOutputBuffer());
}
}
|
2280644_28
|
class MapCommand implements Command<T> {
public boolean contains(String name) {
return values.containsKey(name);
}
public Object getValue(String name);
public void setValue(String name, Object value);
public void resetValue(String name);
public Map<String, Object> getValues();
public boolean checkForRequiredOptions(ParsedLine pl);
void resetAll();
private final Key completeChar;
}
class MapCommandTest {
private final Key completeChar;
@Test
public void testCompletionWithStaticOptions() throws Exception {
|
TestConnection connection = new TestConnection(false);
// Build dynamic command.
DynCommand1 cmd = new DynCommand1();
DynamicOptionsProvider provider = new DynamicOptionsProvider();
MapProcessedCommandBuilder builder = MapProcessedCommandBuilder.builder();
builder.command(cmd);
// Retrieve dynamic options during completion.
builder.lookupAtCompletionOnly(true);
builder.name("dyn1");
{
ProcessedOptionBuilder optBuilder = ProcessedOptionBuilder.builder();
optBuilder.name("verbose");
optBuilder.hasValue(false);
optBuilder.type(Boolean.class);
builder.addOption(optBuilder.build());
}
{
ProcessedOptionBuilder optBuilder = ProcessedOptionBuilder.builder();
optBuilder.name("dir");
optBuilder.hasValue(true);
optBuilder.type(String.class);
builder.addOption(optBuilder.build());
}
builder.optionProvider(provider);
CommandRegistry registry = AeshCommandRegistryBuilder.builder()
.command(builder.create())
.create();
Settings settings = SettingsBuilder.builder()
.logging(true)
.connection(connection)
.commandRegistry(registry)
.build();
ReadlineConsole console = new ReadlineConsole(settings);
console.setPrompt(new Prompt(""));
console.start();
// First test without any dynamic option provided.
connection.clearOutputBuffer();
connection.read("d");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 ", connection.getOutputBuffer());
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --", connection.getOutputBuffer());
connection.read("v");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose ", connection.getOutputBuffer());
connection.read("--");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --dir=", connection.getOutputBuffer());
connection.read("toto");
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
{
String val = (String) cmd.options.get("dir");
assertEquals("toto", val);
}
assertTrue(cmd.contains("verbose"));
// Enable dynamic commands
provider.options = getOptions();
connection.read("dyn1 --verbose");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose ", connection.getOutputBuffer());
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --", connection.getOutputBuffer());
connection.read("opt-dyn1");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --opt-dyn1-withvalue=", connection.getOutputBuffer());
connection.read("xxx ");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --opt-dyn1-withvalue=xxx --", connection.getOutputBuffer());
connection.read("d");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --opt-dyn1-withvalue=xxx --dir=", connection.getOutputBuffer());
connection.read("tutu ");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --opt-dyn1-withvalue=xxx --dir=tutu --opt-dyn", connection.getOutputBuffer());
connection.read("2-withvalue=yyy --");
connection.read(completeChar.getFirstValue());
assertEquals("dyn1 --verbose --opt-dyn1-withvalue=xxx --dir=tutu --opt-dyn2-withvalue=yyy --opt-dyn3-novalue ", connection.getOutputBuffer());
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
{
String val = (String) cmd.options.get("dir");
assertEquals("tutu", val);
}
{
String val = (String) cmd.options.get("opt-dyn1-withvalue");
assertEquals("xxx", val);
}
{
String val = (String) cmd.options.get("opt-dyn2-withvalue");
assertEquals("yyy", val);
}
assertTrue(cmd.contains("verbose"));
assertTrue(cmd.contains("opt-dyn3-novalue"));
}
}
|
2280644_29
|
class MapCommand implements Command<T> {
public boolean contains(String name) {
return values.containsKey(name);
}
public Object getValue(String name);
public void setValue(String name, Object value);
public void resetValue(String name);
public Map<String, Object> getValues();
public boolean checkForRequiredOptions(ParsedLine pl);
void resetAll();
private final Key completeChar;
}
class MapCommandTest {
private final Key completeChar;
@Test
public void testExecution() throws Exception {
|
TestConnection connection = new TestConnection(false);
// Build dynamic command.
DynCommand1 cmd = new DynCommand1();
DynamicOptionsProvider provider = new DynamicOptionsProvider();
MapProcessedCommandBuilder builder = MapProcessedCommandBuilder.builder();
builder.command(cmd);
// Retrieve dynamic options at execution time too, required to check for required option.
builder.lookupAtCompletionOnly(false);
builder.name("dyn1");
{
ProcessedOptionBuilder optBuilder = ProcessedOptionBuilder.builder();
optBuilder.name("verbose");
optBuilder.hasValue(false);
optBuilder.type(Boolean.class);
builder.addOption(optBuilder.build());
}
{
ProcessedOptionBuilder optBuilder = ProcessedOptionBuilder.builder();
optBuilder.name("dir");
optBuilder.hasValue(true);
optBuilder.type(String.class);
builder.addOption(optBuilder.build());
}
builder.optionProvider(provider);
CommandRegistry registry = AeshCommandRegistryBuilder.builder()
.command(builder.create())
.create();
Settings settings = SettingsBuilder.builder()
.logging(true)
.connection(connection)
.commandRegistry(registry)
.build();
ReadlineConsole console = new ReadlineConsole(settings);
console.setPrompt(new Prompt(""));
console.start();
// First test without any dynamic option provided.
connection.clearOutputBuffer();
connection.read("dyn1");
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
assertFalse(cmd.contains("verbose"));
assertFalse(cmd.contains("dir"));
connection.read("dyn1 --verbose");
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
assertTrue(cmd.contains("verbose"));
assertFalse(cmd.contains("dir"));
connection.read("dyn1 --dir=toto");
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
assertFalse(cmd.contains("verbose"));
assertTrue(cmd.contains("dir"));
assertFalse(cmd.contains("opt-dyn1-withvalue"));
// add dynamic options
provider.options = getOptions();
connection.read("dyn1 --opt-dyn1-withvalue=foo");
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
assertFalse(cmd.contains("verbose"));
assertFalse(cmd.contains("dir"));
assertTrue(cmd.contains("opt-dyn1-withvalue"));
assertFalse(cmd.contains("opt-dyn2-withvalue"));
assertFalse(cmd.contains("opt-dyn3-novalue"));
// Update to a new set if options.
provider.options = getOptionsRequired();
connection.read("dyn1");
// Execute command.
connection.read(Config.getLineSeparator());
Thread.sleep(200);
assertTrue(connection.getOutputBuffer().contains("Option: --opt-dyn1-required is required for this command"));
connection.clearOutputBuffer();
connection.read("dyn1 --opt-dyn1-required=xxx");
// Execute command.
connection.read(Config.getLineSeparator());
Thread.sleep(200);
assertTrue(connection.getOutputBuffer().contains("Option: --opt-dyn2-required is required for this command"));
connection.clearOutputBuffer();
connection.read("dyn1 --opt-dyn1-required=xxx --opt-dyn2-required=yyy");
// Execute command.
connection.read(Config.getLineSeparator());
connection.clearOutputBuffer();
Thread.sleep(200);
assertTrue(connection.getOutputBuffer(), cmd.contains("opt-dyn1-required"));
assertTrue(connection.getOutputBuffer(), cmd.contains("opt-dyn2-required"));
assertFalse(cmd.contains("opt-dyn1-withvalue"));
assertFalse(cmd.contains("opt-dyn2-withvalue"));
assertFalse(cmd.contains("opt-dyn3-novalue"));
}
}
|
2280644_30
|
class ParsedLine {
public ParsedWord firstWord() {
if(words.size() > 0 )
return words.get(0);
else
return new ParsedWord("", 0);
}
public ParsedLine(String originalInput, List<ParsedWord> words,
int cursor, int cursorWord, int wordCursor,
ParserStatus status, String errorMessage, OperatorType operator);
public int cursor();
public int selectedIndex();
public ParsedWord selectedWord();
public ParsedWord selectedWordToCursor();
public int wordCursor();
public String line();
public String errorMessage();
public List<ParsedWord> words();
public ParserStatus status();
public ParsedWord lastWord();
public int size();
public boolean hasWords();
public ParsedLineIterator iterator();
public OperatorType operator();
public boolean cursorAtEnd();
public boolean spaceAtEnd();
public boolean isCursorAtEndOfSelectedWord();
@Override public String toString();
}
class ParsedLineTest {
@Test
public void firstWordFromEmptyLine() throws Exception {
|
List<ParsedWord> words = new ArrayList<>();
ParsedLine pl = new ParsedLine("", words, -1,
0, 0, ParserStatus.OK, "", OperatorType.NONE);
assertEquals(pl.firstWord().word(), "");
}
}
|
2280644_31
|
class ParsedLine {
public ParsedWord firstWord() {
if(words.size() > 0 )
return words.get(0);
else
return new ParsedWord("", 0);
}
public ParsedLine(String originalInput, List<ParsedWord> words,
int cursor, int cursorWord, int wordCursor,
ParserStatus status, String errorMessage, OperatorType operator);
public int cursor();
public int selectedIndex();
public ParsedWord selectedWord();
public ParsedWord selectedWordToCursor();
public int wordCursor();
public String line();
public String errorMessage();
public List<ParsedWord> words();
public ParserStatus status();
public ParsedWord lastWord();
public int size();
public boolean hasWords();
public ParsedLineIterator iterator();
public OperatorType operator();
public boolean cursorAtEnd();
public boolean spaceAtEnd();
public boolean isCursorAtEndOfSelectedWord();
@Override public String toString();
}
class ParsedLineTest {
@Test
public void firstWordFromLineWithWords() throws Exception {
|
List<ParsedWord> words = new ArrayList<>();
words.add(new ParsedWord("command", 0));
words.add(new ParsedWord("line", 1));
words.add(new ParsedWord("text", 2));
ParsedLine pl = new ParsedLine("command line text", words, -1,
0, 0, ParserStatus.OK, "", OperatorType.NONE);
assertEquals(pl.firstWord().word(), "command");
}
}
|
2280644_32
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testfindCurrentWordFromCursor() {
|
LineParser lineParser = new LineParser();
assertEquals("", lineParser.parseLine(" ", 1).selectedWord().word());
assertEquals("foo", lineParser.parseLine("foo bar", 3).selectedWord().word());
assertEquals("bar", lineParser.parseLine("foo bar", 6).selectedWord().word());
assertEquals("foobar", lineParser.parseLine("foobar", 6).selectedWord().word());
assertEquals("fo", lineParser.parseLine("foobar", 2).selectedWordToCursor().word());
assertEquals("", lineParser.parseLine("ls ", 3).selectedWord().word());
assertEquals("foo", lineParser.parseLine("ls foo", 6).selectedWord().word());
assertEquals("foo", lineParser.parseLine("ls foo bar", 6).selectedWord().word());
assertEquals("bar", lineParser.parseLine("ls foo bar", 11).selectedWordToCursor().word());
assertEquals("ba", lineParser.parseLine("ls foo bar", 10).selectedWordToCursor().word());
assertEquals("b", lineParser.parseLine("ls foo bar", 9).selectedWordToCursor().word());
assertEquals("foo", lineParser.parseLine("ls foo ", 6).selectedWordToCursor().word());
assertEquals("o", lineParser.parseLine("ls o org/jboss/aeshell/Shell.class", 4).selectedWord().word());
assertEquals("", lineParser.parseLine("ls org/jboss/aeshell/Shell.class", 3).selectedWord().word());
}
}
|
2280644_33
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testFindCurrentWordWithEscapedSpaceToCursor() {
|
LineParser lineParser = new LineParser();
assertEquals("foo bar", lineParser.parseLine("foo\\ bar", 8).selectedWordToCursor().word());
assertEquals("foo ba", lineParser.parseLine("foo\\ bar", 7).selectedWordToCursor().word());
assertEquals("foo bar", lineParser.parseLine("ls foo\\ bar", 12).selectedWordToCursor().word());
}
}
|
2280644_34
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testFindClosestWholeWordToCursor() {
|
LineParser lineParser = new LineParser();
ParsedLine line = lineParser.parseLine("ls foo bar", 6);
assertEquals("foo", line.selectedWord().word());
assertFalse(line.isCursorAtEndOfSelectedWord());
assertEquals("", lineParser.parseLine(" ", 1).selectedWord().word());
line = lineParser.parseLine("foo bar", 1);
assertEquals("foo", line.selectedWord().word());
assertFalse(line.isCursorAtEndOfSelectedWord());
line = lineParser.parseLine("foo bar", 3);
assertEquals("foo", line.selectedWord().word());
assertTrue(line.isCursorAtEndOfSelectedWord());
assertEquals("foobar", lineParser.parseLine("foobar", 6).selectedWord().word());
assertEquals("foobar", lineParser.parseLine("foobar", 2).selectedWord().word());
assertEquals("", lineParser.parseLine("ls ", 3).selectedWord().word());
assertEquals("o", lineParser.parseLine("ls o org/jboss/aeshell/Shell.class", 4).selectedWord().word());
assertEquals("", lineParser.parseLine("ls org/jboss/aeshell/Shell.class", 3).selectedWord().word());
line = lineParser.parseLine("foo bar foo", 3);
assertEquals("foo", line.selectedWord().word());
assertTrue(line.isCursorAtEndOfSelectedWord());
}
}
|
2280644_35
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testFindClosestWholeWordToCursorEscapedSpace() {
|
LineParser lineParser = new LineParser();
assertEquals("foo bar", lineParser.parseLine("foo\\ bar", 7).selectedWord().word());
assertEquals("foo bar", lineParser.parseLine("ls foo\\ bar", 11).selectedWord().word());
}
}
|
2280644_36
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testOriginalInput() {
|
LineParser lineParser = new LineParser();
String input = "echo foo -i bar";
ParsedLine line = lineParser.parseLine(input);
assertEquals(input, line.line());
}
}
|
2280644_37
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testFindAllQuotedWords() {
|
LineParser lineParser = new LineParser();
ParsedLine line = lineParser.parseLine("foo bar \"baz 12345\" ", 19);
assertEquals("foo", line.words().get(0).word());
assertEquals(0, line.words().get(0).lineIndex());
assertEquals("bar", line.words().get(1).word());
assertEquals(4, line.words().get(1).lineIndex());
assertEquals("baz 12345", line.words().get(2).word());
assertEquals(9, line.words().get(2).lineIndex());
assertEquals("", line.selectedWord().word());
assertEquals(0, line.wordCursor());
assertFalse(line.cursorAtEnd());
line = lineParser.parseLine("java -cp \"foo/bar\" \"Example\"", 32);
assertEquals("foo/bar", line.words().get(2).word());
assertEquals("Example", line.words().get(3).word());
assertTrue(line.cursorAtEnd());
line = lineParser.parseLine("'foo/bar/' Example\\ 1");
assertEquals("foo/bar/", line.words().get(0).word());
assertEquals("Example 1", line.words().get(1).word());
line = lineParser.parseLine("man -f='foo bar/' Example\\ 1 foo");
assertEquals("man", line.words().get(0).word());
assertEquals("-f=foo bar/", line.words().get(1).word());
assertEquals("Example 1", line.words().get(2).word());
assertEquals("foo", line.words().get(3).word());
line = lineParser.parseLine("man -f='foo/bar/ Example\\ 1");
assertEquals(ParserStatus.UNCLOSED_QUOTE, line.status());
line = lineParser.parseLine("man -f='foo/bar/' Example\\ 1\"");
assertEquals(ParserStatus.UNCLOSED_QUOTE, line.status());
line = lineParser.parseLine("-s \'redirectUris=[\"http://localhost:8080/blah/*\"]\'");
assertEquals("-s", line.words().get(0).word());
assertEquals("redirectUris=[\"http://localhost:8080/blah/*\"]", line.words().get(1).word());
line = lineParser.parseLine("\"baz\\ 12345\"");
assertEquals(line.words().toString(), "baz\\ 12345", line.words().get(0).word());
line = lineParser.parseLine("\"\\\"String with double quotes\\\"\"");
assertEquals(line.words().toString(), 1, line.words().size());
assertEquals(line.words().toString(), "\\\"String with double quotes\\\"", line.words().get(0).word());
// A word and a word containing only a double quote.
line = lineParser.parseLine("\"\\\"String with double quotes\"\\\"");
assertEquals(line.words().toString(), 2, line.words().size());
assertEquals(line.words().toString(), "\\\"String with double quotes", line.words().get(0).word());
assertEquals(line.words().toString(), "\"", line.words().get(1).word());
line = lineParser.parseLine("'\\'String with single quotes\\''");
assertEquals(line.words().toString(), 1, line.words().size());
assertEquals(line.words().toString(), "\\'String with single quotes\\'", line.words().get(0).word());
// A word and a word containing only a single quote.
line = lineParser.parseLine("'\\'String with single quotes'\\'");
assertEquals(line.words().toString(), 2, line.words().size());
assertEquals(line.words().toString(), "\\'String with single quotes", line.words().get(0).word());
assertEquals(line.words().toString(), "'", line.words().get(1).word());
}
}
|
2280644_38
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testFindAllTernaryQuotedWords() {
|
LineParser lineParser = new LineParser();
ParsedLine line = lineParser.parseLine("\"\" \"\"");
assertEquals(" ", line.words().get(0).word());
line = lineParser.parseLine("\"\" foo bar \"\"");
assertEquals(" foo bar ", line.words().get(0).word());
line = lineParser.parseLine("\"\" \"foo bar\" \"\"");
assertEquals(" \"foo bar\" ", line.words().get(0).word());
line = lineParser.parseLine("gah bah-bah \"\" \"foo bar\" \"\" boo");
assertEquals("gah", line.words().get(0).word());
assertEquals("bah-bah", line.words().get(1).word());
assertEquals(" \"foo bar\" ", line.words().get(2).word());
assertEquals("boo", line.words().get(3).word());
line = lineParser.parseLine(" \"\"/s-ramp/wsdl/Operation[xp2:matches(@name, 'submit.*')]\"\"");
assertEquals("/s-ramp/wsdl/Operation[xp2:matches(@name, 'submit.*')]", line.words().get(0).word());
line = lineParser.parseLine(" \"\"/s-ramp/ext/${type} \\ \"\"");
assertEquals("/s-ramp/ext/${type} \\ ", line.words().get(0).word());
line = lineParser.parseLine(" 'test=\"some thing\"' ");
assertEquals("test=\"some thing\"", line.words().get(0).word());
}
}
|
2280644_39
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testParsedLineIterator() {
|
LineParser lineParser = new LineParser();
ParsedLine line = lineParser.parseLine("foo bar");
ParsedLineIterator iterator = line.iterator();
int counter = 0;
while(iterator.hasNextWord()) {
if(counter == 0)
assertEquals("foo", iterator.pollWord());
else if(counter == 1)
assertEquals("bar", iterator.pollWord());
counter++;
}
line = lineParser.parseLine("");
iterator = line.iterator();
assertFalse(iterator.hasNextWord());
assertNull(iterator.pollWord());
line = lineParser.parseLine("\\ foo ba bar");
iterator = line.iterator();
assertEquals(" foo", iterator.peekWord());
assertEquals(" foo", iterator.pollWord());
assertFalse(iterator.finished());
assertEquals('b', iterator.pollChar());
assertEquals('a', iterator.pollChar());
assertEquals(' ', iterator.pollChar());
assertFalse(iterator.finished());
assertEquals("bar", iterator.peekWord());
assertEquals("bar", iterator.pollWord());
assertTrue(iterator.finished());
line = lineParser.parseLine("\\ foo ba bar");
iterator = line.iterator();
assertEquals('\\', iterator.pollChar());
assertEquals(' ', iterator.pollChar());
assertEquals('f', iterator.pollChar());
assertEquals(" foo", iterator.pollWord());
assertEquals("ba", iterator.pollWord());
assertEquals('b', iterator.pollChar());
assertEquals('a', iterator.pollChar());
assertEquals('r', iterator.pollChar());
assertTrue(iterator.finished());
line = lineParser.parseLine("\\ foo ba bar");
iterator = line.iterator();
assertEquals(" foo", iterator.pollWord());
}
}
|
2280644_40
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testParsedLineIterator2() {
|
LineParser lineParser = new LineParser();
ParsedLine line = lineParser.parseLine("foo bar");
ParsedLineIterator iterator = line.iterator();
assertEquals("foo bar", iterator.stringFromCurrentPosition());
iterator.updateIteratorPosition(3);
assertEquals(' ', iterator.pollChar());
assertEquals("bar", iterator.stringFromCurrentPosition());
assertEquals("bar", iterator.pollWord());
line = lineParser.parseLine("command --opt1={ myProp1=99, myProp2=100} --opt2");
iterator = line.iterator();
assertEquals("command", iterator.pollWord());
assertEquals('-', iterator.peekChar());
assertEquals("--opt1={", iterator.peekWord());
iterator.updateIteratorPosition(33);
assertEquals("--opt2", iterator.peekWord());
assertEquals(' ', iterator.peekChar());
line = lineParser.parseLine("--headers={t=x; t=y}");
iterator = line.iterator();
assertEquals("--headers={t=x;", iterator.pollWord());
assertEquals('t', iterator.peekChar());
iterator.updateIteratorPosition(3);
assertEquals('}', iterator.peekChar());
assertEquals("t=y}", iterator.pollWord());
assertFalse(iterator.hasNextWord());
assertNull("", iterator.pollWord());
line = lineParser.parseLine("--headers={t=x; t=y}");
iterator = line.iterator();
iterator.pollParsedWord();
iterator.updateIteratorPosition(4);
assertFalse(iterator.hasNextChar());
assertEquals('\u0000', iterator.pollChar());
assertNull("", iterator.pollWord());
line = lineParser.parseLine("--headers={t=x; t=y}");
iterator = line.iterator();
iterator.pollParsedWord();
iterator.updateIteratorPosition(40);
assertFalse(iterator.hasNextChar());
assertEquals('\u0000', iterator.pollChar());
assertNull("", iterator.pollWord());
line = lineParser.parseLine("--headers={t=x; t=y}");
iterator = line.iterator();
iterator.updateIteratorPosition(20);
assertNull(iterator.peekWord());
}
}
|
2280644_41
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testCurlyBrackets() {
|
LineParser lineParser = new LineParser();
ParsedLine line = lineParser.parseLine("foo bar {baz 12345} ", 19, true);
assertEquals("foo", line.words().get(0).word());
assertEquals(0, line.words().get(0).lineIndex());
assertEquals("bar", line.words().get(1).word());
assertEquals(4, line.words().get(1).lineIndex());
assertEquals("{baz 12345}", line.words().get(2).word());
assertEquals(8, line.words().get(2).lineIndex());
assertEquals("{baz 12345}", line.selectedWord().word());
assertEquals(11, line.wordCursor());
line = lineParser.parseLine("cmd1 --option1=bar{x1; x2}", 19, true);
assertEquals("cmd1", line.words().get(0).word());
assertEquals("--option1=bar{x1; x2}", line.words().get(1).word());
line = lineParser.parseLine("cmd1 --option1=bar{x1; x2}", 19, false);
assertEquals("--option1=bar{x1;", line.words().get(1).word());
line = lineParser.parseLine("cmd1 --option1=bar{x1; x2 ", 19, true);
assertEquals("cmd1", line.words().get(0).word());
assertEquals("--option1=bar{x1; x2 ", line.words().get(1).word());
assertEquals(ParsedWord.Status.OPEN_BRACKET, line.words().get(1).status());
}
}
|
2280644_42
|
class LineParser {
public ParsedLine parseLine(String text) {
return parseLine(text, -1);
}
public LineParser input(String text);
public LineParser cursor(int cursor);
public LineParser parseBrackets(boolean doParse);
public LineParser operators(EnumSet<OperatorType> operators);
public ParsedLine parse();
public List<ParsedLine> parseWithOperators();
public ParsedLine parseLine(String text, int cursor);
public ParsedLine parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
private ParsedLine doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets);
public List<ParsedLine> parseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private List<ParsedLine> doParseLine(String text, int cursor, boolean parseCurlyAndSquareBrackets, Set<OperatorType> operators);
private char nextChar(String text, int index);
private boolean isQuoted();
private OperatorType matchesOperators(Set<OperatorType> operators, String text, int index);
private ParsedLine endOfLineProcessing(String text, int cursor,
int startIndex, int totalTextLength);
private void handleCurlyEnd(char c);
private void handleCurlyStart(char c);
private void handleDoubleQuote(char c);
private void handleHaveDoubleQuote();
private void handleSingleQuote(char c);
private char handleSpace(char c);
private void handleFoundOperator(List<ParsedLine> lines, String text, int cursor);
private void handleEscape(char c);
private void reset();
}
class LineParserTest {
@Test
public void testParseEscapedCharacters() {
|
assertEquals("mkdir", parseLine("mkdir He\\|lo").get(0).word());
assertEquals("Try to escape |", "He|lo", parseLine("mkdir He\\|lo").get(1).word());
assertEquals("Try to escape ;", "He;lo", parseLine("mkdir He\\;lo").get(1).word());
assertEquals("Try to escape \\","He\\lo", parseLine("mkdir He\\\\lo").get(1).word());
assertEquals("Try to escape normal char","He\\lo", parseLine("mkdir He\\lo").get(1).word());
assertEquals("Try to escape normal char","He\\-o", parseLine("mkdir He\\-o").get(1).word());
}
}
|
23330642_0
|
class Main extends MainSupport {
@Override
protected Map<String, CamelContext> getCamelContextMap() {
BeanManager manager = container.getBeanManager();
return manager.getBeans(CamelContext.class, Any.Literal.INSTANCE).stream()
.map(bean -> getReference(manager, CamelContext.class, bean))
.collect(toMap(CamelContext::getName, identity()));
}
public static void main(String... args);
public static Main getInstance();
@Override protected ProducerTemplate findOrCreateCamelTemplate();
@Override protected void doStart();
private void warnIfNoCamelFound();
@Override protected void doStop();
}
class MainTest {
@Test
public void testMainSupport() throws Exception {
|
Main main = new Main();
main.start();
assertThat("Camel contexts are not deployed!", main.getCamelContextMap(), allOf(hasKey("default"), hasKey("foo")));
CamelContext context = main.getCamelContextMap().get("default");
assertThat("Default Camel context is not started", context.getStatus(), is(equalTo(ServiceStatus.Started)));
assertThat("Foo Camel context is not started", main.getCamelContextMap().get("foo").getStatus(), is(equalTo(ServiceStatus.Started)));
MockEndpoint outbound = context.getEndpoint("mock:outbound", MockEndpoint.class);
outbound.expectedMessageCount(1);
outbound.expectedBodiesReceived("message");
ProducerTemplate producer = main.getCamelTemplate();
producer.sendBody("direct:inbound", "message");
MockEndpoint.assertIsSatisfied(2L, TimeUnit.SECONDS, outbound);
main.stop();
}
}
|
24503275_0
|
class ECKey implements Serializable {
@Override
public int hashCode() {
// Public keys are random already so we can just use a part of them as the hashcode. Read from the start to
// avoid picking up the type code (compressed vs uncompressed) which is tacked on the end.
byte[] bits = getPubKey();
return (bits[0] & 0xFF) | ((bits[1] & 0xFF) << 8) | ((bits[2] & 0xFF) << 16) | ((bits[3] & 0xFF) << 24);
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public boolean isPubKeyCanonical();
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testHashCode() {
|
assertEquals(1866897155, ECKey.fromPrivate(privateKey).hashCode());
}
}
|
24503275_2
|
class ECKey implements Serializable {
public boolean isPubKeyOnly() {
return priv == null;
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public boolean isPubKeyCanonical();
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testIsPubKeyOnly() {
|
ECKey key = ECKey.fromPublicOnly(pubKey);
assertTrue(key.isPubKeyCanonical());
assertTrue(key.isPubKeyOnly());
assertArrayEquals(key.getPubKey(), pubKey);
}
}
|
24503275_3
|
class ECKey implements Serializable {
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) {
ECPoint point = CURVE.getG().multiply(privKey);
return point.getEncoded(compressed);
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public boolean isPubKeyCanonical();
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testPublicKeyFromPrivate() {
|
byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, false);
assertArrayEquals(pubKey, pubFromPriv);
}
}
|
24503275_4
|
class ECKey implements Serializable {
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) {
ECPoint point = CURVE.getG().multiply(privKey);
return point.getEncoded(compressed);
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public boolean isPubKeyCanonical();
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testPublicKeyFromPrivateCompressed() {
|
byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, true);
assertArrayEquals(compressedPubKey, pubFromPriv);
}
}
|
24503275_5
|
class ECKey implements Serializable {
public byte[] getAddress() {
if (pubKeyHash == null) {
byte[] pubBytes = this.pub.getEncoded(false);
pubKeyHash = HashUtil.sha3omit12(Arrays.copyOfRange(pubBytes, 1, pubBytes.length));
}
return pubKeyHash;
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public boolean isPubKeyCanonical();
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testGetAddress() {
|
ECKey key = ECKey.fromPublicOnly(pubKey);
assertArrayEquals(Hex.decode(address), key.getAddress());
}
}
|
24503275_6
|
class ECKey implements Serializable {
public String toString() {
StringBuilder b = new StringBuilder();
b.append("pub:").append(Hex.toHexString(pub.getEncoded(false)));
return b.toString();
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public boolean isPubKeyCanonical();
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testToString() {
|
ECKey key = ECKey.fromPrivate(BigInteger.TEN); // An example private key.
assertEquals("pub:04a0434d9e47f3c86235477c7b1ae6ae5d3442d49b1943c2b752a68e2a47e247c7893aba425419bc27a3b6c7e693a24c696f794c2ed877a1593cbee53b037368d7", key.toString());
}
}
|
24503275_7
|
class ECKey implements Serializable {
public boolean isPubKeyCanonical() {
return isPubKeyCanonical(pub.getEncoded());
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testIsPubKeyCanonicalCorect() {
|
// Test correct prefix 4, right length 65
byte[] canonicalPubkey1 = new byte[65]; canonicalPubkey1[0] = 0x04;
assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey1));
// Test correct prefix 2, right length 33
byte[] canonicalPubkey2 = new byte[33]; canonicalPubkey2[0] = 0x02;
assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey2));
// Test correct prefix 3, right length 33
byte[] canonicalPubkey3 = new byte[33]; canonicalPubkey3[0] = 0x03;
assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey3));
}
}
|
24503275_8
|
class ECKey implements Serializable {
public boolean isPubKeyCanonical() {
return isPubKeyCanonical(pub.getEncoded());
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testIsPubKeyCanonicalWrongLength() {
|
// Test correct prefix 4, but wrong length !65
byte[] nonCanonicalPubkey1 = new byte[64]; nonCanonicalPubkey1[0] = 0x04;
assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey1));
// Test correct prefix 2, but wrong length !33
byte[] nonCanonicalPubkey2 = new byte[32]; nonCanonicalPubkey2[0] = 0x02;
assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey2));
// Test correct prefix 3, but wrong length !33
byte[] nonCanonicalPubkey3 = new byte[32]; nonCanonicalPubkey3[0] = 0x03;
assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey3));
}
}
|
24503275_9
|
class ECKey implements Serializable {
public boolean isPubKeyCanonical() {
return isPubKeyCanonical(pub.getEncoded());
}
public ECKey();
public ECKey(SecureRandom secureRandom);
protected ECKey(@Nullable BigInteger priv, ECPoint pub);
public static ECPoint compressPoint(ECPoint uncompressed);
public static ECPoint decompressPoint(ECPoint compressed);
public static ECKey fromPrivate(BigInteger privKey);
public static ECKey fromPrivate(byte[] privKeyBytes);
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub);
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub);
public static ECKey fromPublicOnly(ECPoint pub);
public static ECKey fromPublicOnly(byte[] pub);
public ECKey decompress();
public boolean isPubKeyOnly();
public boolean hasPrivKey();
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed);
public byte[] getAddress();
public byte[] getPubKey();
public ECPoint getPubKeyPoint();
public BigInteger getPrivKey();
public boolean isCompressed();
public String toString();
public String toStringWithPrivate();
public ECDSASignature doSign(byte[] input);
public ECDSASignature sign(byte[] messageHash);
public static ECKey signatureToKey(byte[] messageHash, String signatureBase64);
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub);
public static boolean verify(byte[] data, byte[] signature, byte[] pub);
public boolean verify(byte[] data, byte[] signature);
public boolean verify(byte[] sigHash, ECDSASignature signature);
public static boolean isPubKeyCanonical(byte[] pubkey);
@Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash, boolean compressed);
private static ECPoint decompressKey(BigInteger xBN, boolean yBit);
@Nullable public byte[] getPrivKeyBytes();
@Override public boolean equals(Object o);
@Override public int hashCode();
private static void check(boolean test, String message);
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
}
class ECKeyTest {
private static final Logger log;
private String privString;
private BigInteger privateKey;
private String pubString;
private String compressedPubString;
private byte[] pubKey;
private byte[] compressedPubKey;
private String address;
private String exampleMessage;
private String sigBase64;
@Test
public void testIsPubKeyCanonicalWrongPrefix() {
|
// Test wrong prefix 4, right length 65
byte[] nonCanonicalPubkey4 = new byte[65];
assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey4));
// Test wrong prefix 2, right length 33
byte[] nonCanonicalPubkey5 = new byte[33];
assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey5));
// Test wrong prefix 3, right length 33
byte[] nonCanonicalPubkey6 = new byte[33];
assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey6));
}
}
|
25259107_0
|
class SignResponse extends JsonSerializable implements Persistable {
public static SignResponse fromJson(String json) throws U2fBadInputException {
checkArgument(json.length() < MAX_SIZE, "Client response bigger than allowed");
return fromJson(json, SignResponse.class);
}
@JsonCreator public SignResponse(@JsonProperty("clientData") String clientData, @JsonProperty("signatureData") String signatureData, @JsonProperty("keyHandle") String keyHandle);
@JsonIgnore public ClientData getClientData();
public String getSignatureData();
public String getKeyHandle();
public String getRequestId();
private void writeObject(ObjectOutputStream out);
private void readObject(ObjectInputStream in);
public static final String JSON;
}
class SignResponseTest {
public static final String JSON;
@Test(expected = IllegalArgumentException.class)
public void fromJsonDetectsTooLongJsonContent() throws U2fBadInputException {
|
SignResponse.fromJson(makeLongJson(20000));
fail("fromJson did not detect too long JSON content.");
}
}
|
25259107_1
|
class SignResponse extends JsonSerializable implements Persistable {
public static SignResponse fromJson(String json) throws U2fBadInputException {
checkArgument(json.length() < MAX_SIZE, "Client response bigger than allowed");
return fromJson(json, SignResponse.class);
}
@JsonCreator public SignResponse(@JsonProperty("clientData") String clientData, @JsonProperty("signatureData") String signatureData, @JsonProperty("keyHandle") String keyHandle);
@JsonIgnore public ClientData getClientData();
public String getSignatureData();
public String getKeyHandle();
public String getRequestId();
private void writeObject(ObjectOutputStream out);
private void readObject(ObjectInputStream in);
public static final String JSON;
}
class SignResponseTest {
public static final String JSON;
@Test
public void fromJsonAllowsShortJsonContent() throws U2fBadInputException {
|
assertNotNull(SignResponse.fromJson(makeLongJson(19999)));
}
}
|
25259107_2
|
class SignRequest extends JsonSerializable implements Persistable {
public String getRequestId() {
return challenge;
}
public static SignRequest fromJson(String json);
public static final String JSON;
}
class SignRequestTest {
public static final String JSON;
@Test
public void testGetters() throws Exception {
|
SignRequest signRequest = SignRequest.builder().challenge(SERVER_CHALLENGE_SIGN_BASE64).appId(APP_ID_SIGN).keyHandle(KEY_HANDLE_BASE64).build();
assertEquals(SERVER_CHALLENGE_SIGN_BASE64, signRequest.getChallenge());
assertEquals(SERVER_CHALLENGE_SIGN_BASE64, signRequest.getRequestId());
assertEquals(APP_ID_SIGN, signRequest.getAppId());
assertEquals(KEY_HANDLE_BASE64, signRequest.getKeyHandle());
}
}
|
25259107_3
|
class JsonSerializable {
@Override
public String toString() {
return toJson();
}
@JsonIgnore public String toJson();
public static T fromJson(String json, Class<T> cls);
}
class JsonSerializableTest {
@Test
public void toStringReturnsJson() {
|
assertEquals("{\"foo\":\"bar\"}", new Thing("bar").toString());
}
}
|
25259107_4
|
class ClientData {
public static String canonicalizeOrigin(String url) {
try {
URI uri = new URI(url);
if (uri.getAuthority() == null) {
return url;
}
return uri.getScheme() + "://" + uri.getAuthority();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("specified bad origin", e);
}
}
public ClientData(String clientData);
public String asJson();
@Override public String toString();
public String getChallenge();
private static String getString(JsonNode data, String key);
public void checkContent(String type, String challenge, Optional<Set<String>> facets);
private static void verifyOrigin(String origin, Set<String> allowedOrigins);
public static Set<String> canonicalizeOrigins(Set<String> origins);
}
class ClientDataTest {
@Test
public void shouldCanonicalizeOrigin() throws U2fBadInputException {
|
assertEquals("http://example.com", canonicalizeOrigin("http://example.com"));
assertEquals("http://example.com", canonicalizeOrigin("http://example.com/"));
assertEquals("http://example.com", canonicalizeOrigin("http://example.com/foo"));
assertEquals("http://example.com", canonicalizeOrigin("http://example.com/foo?bar=b"));
assertEquals("http://example.com", canonicalizeOrigin("http://example.com/foo#fragment"));
assertEquals("https://example.com", canonicalizeOrigin("https://example.com"));
assertEquals("https://example.com", canonicalizeOrigin("https://example.com/foo"));
assertEquals("android:apk-key-hash:2jmj7l5rSw0yVb/vlWAYkK/YBwk",
canonicalizeOrigin("android:apk-key-hash:2jmj7l5rSw0yVb/vlWAYkK/YBwk"));
}
}
|
25259107_6
|
class RegisterRequest extends JsonSerializable implements Persistable {
@Override
public String getRequestId() {
return getChallenge();
}
public RegisterRequest(String challenge, String appId);
public static RegisterRequest fromJson(String json);
public static final String JSON;
}
class RegisterRequestTest {
public static final String JSON;
@Test
public void testGetters() throws Exception {
|
RegisterRequest registerRequest = new RegisterRequest(SERVER_CHALLENGE_REGISTER_BASE64, APP_ID_ENROLL);
assertEquals(SERVER_CHALLENGE_REGISTER_BASE64, registerRequest.getChallenge());
assertEquals(APP_ID_ENROLL, registerRequest.getAppId());
assertNotNull(SERVER_CHALLENGE_REGISTER_BASE64, registerRequest.getRequestId());
}
}
|
25259107_7
|
class RegisterRequest extends JsonSerializable implements Persistable {
public static RegisterRequest fromJson(String json) throws U2fBadInputException {
return fromJson(json, RegisterRequest.class);
}
public RegisterRequest(String challenge, String appId);
@Override public String getRequestId();
public static final String JSON;
}
class RegisterRequestTest {
public static final String JSON;
@Test
public void testJavaSerializer() throws Exception {
|
RegisterRequest registerRequest = RegisterRequest.fromJson(JSON);
RegisterRequest registerRequest2 = TestUtils.clone(registerRequest);
assertEquals(registerRequest, registerRequest2);
}
}
|
25259107_8
|
class RegisterResponse extends JsonSerializable implements Persistable {
public static RegisterResponse fromJson(String json) throws U2fBadInputException {
checkArgument(json.length() < MAX_SIZE, "Client response bigger than allowed");
return JsonSerializable.fromJson(json, RegisterResponse.class);
}
@JsonCreator public RegisterResponse(@JsonProperty("registrationData") String registrationData, @JsonProperty("clientData") String clientData);
public String getRegistrationData();
@JsonIgnore public ClientData getClientData();
public String getRequestId();
private void writeObject(ObjectOutputStream out);
private void readObject(ObjectInputStream in);
public static final String JSON;
}
class RegisterResponseTest {
public static final String JSON;
@Test(expected = IllegalArgumentException.class)
public void fromJsonDetectsTooLongJsonContent() throws U2fBadInputException {
|
RegisterResponse.fromJson(makeLongJson(20000));
fail("fromJson did not detect too long JSON content.");
}
}
|
25259107_9
|
class RegisterResponse extends JsonSerializable implements Persistable {
public static RegisterResponse fromJson(String json) throws U2fBadInputException {
checkArgument(json.length() < MAX_SIZE, "Client response bigger than allowed");
return JsonSerializable.fromJson(json, RegisterResponse.class);
}
@JsonCreator public RegisterResponse(@JsonProperty("registrationData") String registrationData, @JsonProperty("clientData") String clientData);
public String getRegistrationData();
@JsonIgnore public ClientData getClientData();
public String getRequestId();
private void writeObject(ObjectOutputStream out);
private void readObject(ObjectInputStream in);
public static final String JSON;
}
class RegisterResponseTest {
public static final String JSON;
@Test
public void fromJsonAllowsShortJsonContent() throws U2fBadInputException {
|
assertNotNull(RegisterResponse.fromJson(makeLongJson(19999)));
}
}
|
25434304_0
|
class Naming {
static String normalize(CharSequence name) {
return capitalize(name.toString().replaceFirst("^_", ""))
.replaceFirst("^Class$", "Class_");
}
private Naming();
static String withGeneratedSuffix(CharSequence what);
private static String capitalize(String name);
}
class NamingTest {
@Test
public void shouldAvoidGetClassMethodCollisions() throws Exception {
|
assertThat(Naming.normalize("_class"), equalTo("Class_"));
}
}
|
25434304_1
|
class Naming {
static String normalize(CharSequence name) {
return capitalize(name.toString().replaceFirst("^_", ""))
.replaceFirst("^Class$", "Class_");
}
private Naming();
static String withGeneratedSuffix(CharSequence what);
private static String capitalize(String name);
}
class NamingTest {
@Test
public void shouldIgnoreUnderscoresInBeginning() throws Exception {
|
assertThat(Naming.normalize("_public"), equalTo("Public"));
}
}
|
25434304_2
|
class MatcherFactoryGenerator extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
try {
if (roundEnv.processingOver()) {
return false;
}
if (annotations.isEmpty()) {
LOGGER.info("No any annotation found...");
return false;
}
List<Element> fields = new LinkedList<>();
for (TypeElement annotation : annotations) {
LOGGER.info(format("Work with %s...", annotation.getQualifiedName()));
roundEnv.getElementsAnnotatedWith(annotation)
.stream()
.flatMap(MatcherFactoryGenerator::asFields)
.filter(ProcessingPredicates.shouldGenerateMatcher())
.forEach(fields::add);
}
Map<Element, ClassSpecDescription> classes = groupedClasses(fields);
LOGGER.info(format("Got %s classes to generate matchers. Writing them...", classes.size()));
classes.values()
.stream()
.filter(isEntryWithParentPackageElement())
.map(ClassSpecDescription::asJavaFile)
.forEach(write(processingEnv));
LOGGER.info("All classes were successfully processed!");
} catch (Exception e) {
LOGGER.log(Level.SEVERE, format("Can't generate matchers, because of: %s", e.getMessage()), e);
}
return false;
}
@Override public Set<String> getSupportedAnnotationTypes();
@Override public synchronized void init(ProcessingEnvironment processingEnv);
static Map<Element, ClassSpecDescription> groupedClasses(List<Element> fields);
private static Consumer<JavaFile> write(ProcessingEnvironment processingEnv);
private static Stream<Element> asFields(Element element);
@Mock
private RoundEnvironment env;
@Mock
private ProcessingEnvironment prenv;
@Mock
private Elements elements;
private Set<TypeElement> annotations;
private MatcherFactoryGenerator matcherFactoryGenerator;
@Rule
public ExternalResource prepare;
}
class MatcherFactoryGeneratorTest {
@Mock
private RoundEnvironment env;
@Mock
private ProcessingEnvironment prenv;
@Mock
private Elements elements;
private Set<TypeElement> annotations;
private MatcherFactoryGenerator matcherFactoryGenerator;
@Rule
public ExternalResource prepare;
@Test
public void shouldDoNothingWithNoneAnnotationsOrEmptyAnnotationClass() throws Exception {
|
matcherFactoryGenerator.process(annotations, env);
verify(env).processingOver();
verifyNoMoreInteractions(env);
}
}
|
25434304_3
|
class ElementParentsIterable implements Iterable<Element> {
public static Stream<Element> stream(Element element) {
return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
}
public ElementParentsIterable(Element start);
@Override public Iterator<Element> iterator();
@Rule
public CompilationRule compilation;
}
class ElementParentsIterableTest {
@Rule
public CompilationRule compilation;
@Test
public void shouldGetParents() throws Exception {
|
TypeElement twiceNested = compilation.getElements()
.getTypeElement(Outer.Nested.TwiceNested.class.getCanonicalName());
List<? extends Element> members = compilation.getElements().getAllMembers(twiceNested);
Element field = members.stream().filter(ofKind(ElementKind.FIELD)).findFirst()
.orElseThrow(IllegalStateException::new);
List<String> parents = stream(field)
.map(element -> element.getSimpleName().toString())
.collect(Collectors.toList());
assertThat(parents, hasItems("field", "TwiceNested", "Nested", "Outer"));
}
}
|
25434304_4
|
class ElementParentsIterable implements Iterable<Element> {
public static Stream<Element> stream(Element element) {
return StreamSupport.stream(new ElementParentsIterable(element).spliterator(), false);
}
public ElementParentsIterable(Element start);
@Override public Iterator<Element> iterator();
@Rule
public CompilationRule compilation;
}
class ElementParentsIterableTest {
@Rule
public CompilationRule compilation;
@Test
public void shouldReturnNothingForPackage() throws Exception {
|
PackageElement pkg = compilation.getElements()
.getPackageElement(Outer.class.getPackage().getName());
assertThat(stream(pkg).count(), is(0L));
}
}
|
27062690_0
|
class XModifier {
private void create(Node parent, XModifyNode node) throws XPathExpressionException {
Node newNode;
if (node.isAttributeModifier()) {
//attribute
createAttributeByXPath(parent, node.getCurNode().substring(1), node.getValue());
} else {
//element
if (node.isRootNode()) {
//root node
newNode = parent;
boolean canMoveToNext = node.moveNext();
if (!canMoveToNext) {
//last node
newNode.setTextContent(node.getValue());
} else {
//next node
create(newNode, node);
}
} else if (node.getCurNode().equals("text()")) {
parent.setTextContent(node.getValue());
} else {
//element
findOrCreateElement(parent, node);
}
}
}
public XModifier(Document document);
public void setNamespace(String prefix, String url);
public void addModify(String xPath, String value);
public void addModify(String xPath);
public void modify();
private void initXPath();
private void createAttributeByXPath(Node node, String current, String value);
private void findOrCreateElement(Node parent, XModifyNode node);
private Element createNewElement(String namespaceURI, String local, String[] conditions);
}
class XModifierTest {
@Test
public void create() throws ParserConfigurationException, IOException, SAXException {
|
Document document = createDocument();
Document documentExpected = readDocument("createExpected.xml");
XModifier modifier = new XModifier(document);
modifier.setNamespace("ns", "http://localhost");
// create an empty element
modifier.addModify("/ns:root/ns:element1");
// create an element with attribute
modifier.addModify("/ns:root/ns:element2[@attr=1]");
// append an new element to existing element1
modifier.addModify("/ns:root/ns:element1/ns:element11");
// create an element with text
modifier.addModify("/ns:root/ns:element3", "TEXT");
modifier.modify();
assertXmlEquals(documentExpected, document);
}
}
|
27187107_2
|
class ZkUtils {
public static Stream<String> getAllChildren(CuratorFramework curator, String parentPath) {
String parentPath0 = removeEnd(parentPath, "/");
return getAllChildren0(curator, parentPath0).map(p -> removeStart(p, parentPath0));
}
private ZkUtils();
public static String getStringFromZk(CuratorFramework client, String path);
public static byte[] getBytesFromZk(CuratorFramework client, String path);
public static T getFromZk(CuratorFramework client, String path,
ThrowableFunction<byte[], T, X> decoder);
public static void setToZk(CuratorFramework client, String path, byte[] value);
@Deprecated public static void setToZk(CuratorFramework client, String path, byte[] value,
CreateMode createMode);
public static EphemeralNode createEphemeralNode(CuratorFramework client, String path,
byte[] value);
public static void removeFromZk(CuratorFramework client, String path);
public static void removeFromZk(CuratorFramework client, String path,
boolean recruitDeletedChildren);
public static void changeZkValue(CuratorFramework client, String path,
Function<T, T> changeFunction, Function<byte[], T> decoder,
Function<T, byte[]> encoder);
public static boolean changeZkValue(CuratorFramework client, String path,
Function<byte[], byte[]> changeFunction, int retryTimes, long retryWait);
public static Stream<ChildData> getAllChildrenWithData(CuratorFramework curator, String parentPath);
private static Stream<ChildData> getAllChildrenWithData0(CuratorFramework curator, String parentPath);
@Nullable private static ChildData toChildData(CuratorFramework curator, String path);
private static Stream<String> getAllChildren0(CuratorFramework curator, String parentPath);
private static final int LOOP;
private static final String TEST_PATH;
private static final String TEST_PATH2;
private static ObjectMapper mapper;
private static TestingServer testingServer;
private static CuratorFramework curatorFramework;
private static String otherConnectionStr;
}
class ZkUtilsTest {
private static final int LOOP;
private static final String TEST_PATH;
private static final String TEST_PATH2;
private static ObjectMapper mapper;
private static TestingServer testingServer;
private static CuratorFramework curatorFramework;
private static String otherConnectionStr;
@Test
void testGetAllChildren() {
|
ZkUtils.setToZk(curatorFramework, "/all/test1/a", "a".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test1/b", "b".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test1/b/c", "c".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test1/b/c/c1", "c1".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test1/b/c/c2", "c2".getBytes());
getAllChildren(curatorFramework, "/all/test1").forEach(System.out::println);
assertEquals(5, getAllChildren(curatorFramework, "/all/test1").count());
System.out.println("no end /");
getAllChildren(curatorFramework, "/all/test1/").forEach(System.out::println);
assertEquals(5, getAllChildren(curatorFramework, "/all/test1").count());
System.out.println("no path");
getAllChildren(curatorFramework, "/all/xyz/").forEach(System.out::println);
assertEquals(0, getAllChildren(curatorFramework, "/all/xyz/").count());
}
}
|
27187107_3
|
class ZkUtils {
public static Stream<ChildData> getAllChildrenWithData(CuratorFramework curator, String parentPath){
String parentPath0 = removeEnd(parentPath, "/");
return getAllChildrenWithData0(curator, parentPath0);
}
private ZkUtils();
public static String getStringFromZk(CuratorFramework client, String path);
public static byte[] getBytesFromZk(CuratorFramework client, String path);
public static T getFromZk(CuratorFramework client, String path,
ThrowableFunction<byte[], T, X> decoder);
public static void setToZk(CuratorFramework client, String path, byte[] value);
@Deprecated public static void setToZk(CuratorFramework client, String path, byte[] value,
CreateMode createMode);
public static EphemeralNode createEphemeralNode(CuratorFramework client, String path,
byte[] value);
public static void removeFromZk(CuratorFramework client, String path);
public static void removeFromZk(CuratorFramework client, String path,
boolean recruitDeletedChildren);
public static void changeZkValue(CuratorFramework client, String path,
Function<T, T> changeFunction, Function<byte[], T> decoder,
Function<T, byte[]> encoder);
public static boolean changeZkValue(CuratorFramework client, String path,
Function<byte[], byte[]> changeFunction, int retryTimes, long retryWait);
private static Stream<ChildData> getAllChildrenWithData0(CuratorFramework curator, String parentPath);
@Nullable private static ChildData toChildData(CuratorFramework curator, String path);
public static Stream<String> getAllChildren(CuratorFramework curator, String parentPath);
private static Stream<String> getAllChildren0(CuratorFramework curator, String parentPath);
private static final int LOOP;
private static final String TEST_PATH;
private static final String TEST_PATH2;
private static ObjectMapper mapper;
private static TestingServer testingServer;
private static CuratorFramework curatorFramework;
private static String otherConnectionStr;
}
class ZkUtilsTest {
private static final int LOOP;
private static final String TEST_PATH;
private static final String TEST_PATH2;
private static ObjectMapper mapper;
private static TestingServer testingServer;
private static CuratorFramework curatorFramework;
private static String otherConnectionStr;
@Test
void testGetAllChildrenWithData() {
|
ZkUtils.setToZk(curatorFramework, "/all/test3/a", "a".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test3/b", "b".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test3/b/c", "c".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test3/b/c/c1", "c1".getBytes());
ZkUtils.setToZk(curatorFramework, "/all/test3/b/c/c2", "c2".getBytes());
getAllChildrenWithData(curatorFramework, "/all/test3").forEach(System.out::println);
assertEquals(5, getAllChildrenWithData(curatorFramework, "/all/test3").count());
System.out.println("no end /");
getAllChildrenWithData(curatorFramework, "/all/test3/").forEach(System.out::println);
assertEquals(5, getAllChildrenWithData(curatorFramework, "/all/test3").count());
System.out.println("no path");
getAllChildrenWithData(curatorFramework, "/all/xyz/").forEach(System.out::println);
assertEquals(0, getAllChildrenWithData(curatorFramework, "/all/xyz/").count());
}
}
|
27187107_4
|
class ZkBasedTreeNodeResource implements Closeable {
@Override
public void close() {
synchronized (lock) {
if (resource != null && cleanup != null) {
cleanup.test(resource);
}
if (treeCache != null) {
treeCache.close();
}
closed = true;
}
}
private ZkBasedTreeNodeResource(Builder<T> builder);
public static Builder<T> newBuilder();
private void ensureTreeCacheReady();
public T get();
private void checkClosed();
private void cleanup(T currentResource, T oldResource);
public boolean isClosed();
private T doFactory();
private void generateFullTree(Map<String, ChildData> map, TreeCache cache, String rootPath);
private static final Logger logger;
}
class ZkBasedTreeNodeResourceTest {
private static final Logger logger;
@Test
void testClose() {
|
ZkBasedTreeNodeResource<Map<String, String>> tree = ZkBasedTreeNodeResource
.<Map<String, String>> newBuilder()
.curator(curatorFramework)
.path("/test")
.factory(p -> p.entrySet().stream()
.collect(toMap(Entry::getKey, e -> new String(e.getValue().getData()))))
.build();
System.out.println(tree.get());
tree.close();
assertThrows(IllegalStateException.class, tree::get);
}
}
|
29774200_1
|
class SonarConnectionFactory {
public SonarConnection create(String url, String login, String password) {
Preconditions.checkNotNull(url, "url is mandatory");
SonarConnection sonarConnection = new SonarConnection();
sonarConnection.connect(url, login, password);
return sonarConnection;
}
SonarConnectionFactory sonarConnectionFactory;
}
class SonarConnectionFactoryTest {
SonarConnectionFactory sonarConnectionFactory;
@Test
public void should_create_sonar_connection() {
|
SonarConnection connection = sonarConnectionFactory.create("http://sonar:9000", "", "");
assertFalse(connection.isClosed());
}
}
|
29774200_2
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_incompatible_for_1_0_version() {
|
assertFalse(checker.versionIsCompatible(1.0));
}
}
|
29774200_3
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_incompatible_for_2_0_version() {
|
assertFalse(checker.versionIsCompatible(2.0));
}
}
|
29774200_4
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_incompatible_for_2_3_version() {
|
assertFalse(checker.versionIsCompatible(2.3));
}
}
|
29774200_5
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_compatible_for_3_0_version() {
|
assertTrue(checker.versionIsCompatible(3.0));
}
}
|
29774200_6
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_compatible_for_2_4_version() {
|
assertTrue(checker.versionIsCompatible(2.4));
}
}
|
29774200_7
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_compatible_for_2_5_version() {
|
assertTrue(checker.versionIsCompatible(2.5));
}
}
|
29774200_8
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_compatible_for_2_12_version() {
|
assertTrue(checker.versionIsCompatible(2.12));
}
}
|
29774200_9
|
class SonarCompatibleVersionChecker {
public boolean versionIsCompatible(String version) {
try {
double versionAsFloat = Double.valueOf(version);
return versionIsCompatible(versionAsFloat);
} catch (Exception e) {
return false;
}
}
public SonarCompatibleVersionChecker(Double sonarMinimumCompatibleVersion);
public boolean versionIsCompatible(Double version);
private Integer getDecimalPart(Double value);
SonarCompatibleVersionChecker checker;
}
class SonarCompatibleVersionCheckerTest {
SonarCompatibleVersionChecker checker;
@Test
public void should_get_compatible_for_2_4_version_as_string() {
|
assertTrue(checker.versionIsCompatible("2.4"));
}
}
|
32651977_0
|
class Util {
public static String removeFirstAndLastChar(String text) {
Preconditions.checkNotNull(text, "text can not be null");
int n = text.length();
return text.substring(1, n - 1);
}
private Util();
public static String getFileName(String fullPath);
}
class UtilTest {
@Test
public void testRemoveQuotes_expected() throws Exception {
|
assertEquals("abc", removeFirstAndLastChar("\"abc\""));
}
}
|
32651977_1
|
class CompositeFileReader implements FileReader {
@Nullable
@Override
public CharStream read(String name) {
for (FileReader delegate : delegateList) {
CharStream result = delegate.read(name);
if (result != null) {
return result;
}
}
return null;
}
public CompositeFileReader(List<FileReader> delegateList);
public CompositeFileReader(FileReader... delegates);
}
class CompositeFileReaderTest {
@Test
public void testRead() throws Exception {
|
TestReader r1 = new TestReader("1.proto", "1");
TestReader r2 = new TestReader("2.proto", "2");
CompositeFileReader reader = new CompositeFileReader(r1, r2);
CharStream s1 = reader.read("1.proto");
CharStream s2 = reader.read("2.proto");
CharStream s3 = reader.read("3.proto");
assertNotNull(s1);
assertNotNull(s2);
assertNull(s3);
assertEquals("1", s1.getText(Interval.of(0, 1)));
assertEquals("2", s2.getText(Interval.of(0, 1)));
}
}
|
32651977_2
|
class ClasspathFileReader implements FileReader {
@Nullable
@Override
public CharStream read(String name) {
try {
InputStream resource = readResource(name);
if (resource != null) {
return CharStreams.fromStream(resource);
}
} catch (Exception e) {
LOGGER.error("Could not read {}", name, e);
}
return null;
}
public static InputStream readResource(String name);
}
class ClasspathFileReaderTest {
@Test
public void testRead() throws Exception {
|
ClasspathFileReader reader = new ClasspathFileReader();
CharStream a = reader.read("protostuff_unittest/messages_sample.proto");
CharStream b = reader.read("this_file_does_not_exist.proto");
assertNotNull(a);
assertNull(b);
}
}
|
32651977_3
|
class UserTypeValidationPostProcessor implements ProtoContextPostProcessor {
@VisibleForTesting
boolean isValidTagValue(int tag) {
return tag >= MIN_TAG && tag <= MAX_TAG
&& !(tag >= SYS_RESERVED_START && tag <= SYS_RESERVED_END);
}
@Override public void process(ProtoContext context);
private void processService(Service service);
private void checkDuplicateServiceMethodNames(List<ServiceMethod> methods);
private void processEnum(Enum anEnum);
private void checkReservedEnumNames(Enum anEnum, List<EnumConstant> constants);
private void checkReservedEnumTags(Enum anEnum, List<EnumConstant> constants);
private void checkDuplicateEnumConstantValues(Enum anEnum, List<EnumConstant> constants);
private void checkDuplicateEnumConstantNames(List<EnumConstant> constants);
private void processMessage(Message message);
private void checkFieldModifier(Message message, List<Field> fields);
private void checkReservedFieldTags(Message message, List<Field> fields);
private void checkReservedFieldNames(Message message, List<Field> fields);
private void checkInvalidFieldTags(List<Field> fields);
private void checkDuplicateFieldTags(List<Field> fields);
private void checkDuplicateFieldNames(List<Field> fields);
private UserTypeValidationPostProcessor processor;
}
class UserTypeValidationPostProcessorTest {
private UserTypeValidationPostProcessor processor;
@Test
public void isValidTagValue() throws Exception {
|
assertFalse(processor.isValidTagValue(-1));
assertFalse(processor.isValidTagValue(0));
assertFalse(processor.isValidTagValue(19000));
assertFalse(processor.isValidTagValue(19999));
assertFalse(processor.isValidTagValue(Field.MAX_TAG_VALUE+1));
assertTrue(processor.isValidTagValue(1));
assertTrue(processor.isValidTagValue(100));
assertTrue(processor.isValidTagValue(18999));
assertTrue(processor.isValidTagValue(20000));
assertTrue(processor.isValidTagValue(Field.MAX_TAG_VALUE-1));
assertTrue(processor.isValidTagValue(Field.MAX_TAG_VALUE));
}
}
|
32651977_4
|
class LocalFileReader implements FileReader {
@Nullable
@Override
public CharStream read(String name) {
for (Path prefix : pathList) {
Path path = prefix.resolve(name);
if (Files.isRegularFile(path)) {
try {
byte[] bytes = Files.readAllBytes(path);
String result = new String(bytes, StandardCharsets.UTF_8);
return CharStreams.fromString(result);
} catch (IOException e) {
LOGGER.trace("Could not read {}", path, e);
}
}
}
return null;
}
public LocalFileReader(Path... paths);
public LocalFileReader(List<Path> paths);
private List<Path> checkDirectories(List<Path> pathList);
private Path tempDirectory1;
private Path tempDirectory2;
private Path file1;
private Path file2;
}
class LocalFileReaderTest {
private Path tempDirectory1;
private Path tempDirectory2;
private Path file1;
private Path file2;
@Test
public void testRead() throws Exception {
|
LocalFileReader reader = new LocalFileReader(tempDirectory1, tempDirectory2);
CharStream a = reader.read("1.proto");
CharStream b = reader.read("2.proto");
CharStream c = reader.read("3.proto");
assertNotNull(a);
assertNotNull(b);
assertNull(c);
assertEquals("1", a.getText(Interval.of(0, 1)));
assertEquals("2", b.getText(Interval.of(0, 1)));
}
}
|
32651977_5
|
class ScalarFieldTypeUtil {
@Nonnull
public static String getWrapperType(ScalarFieldType type) {
return getNonNull(WRAPPER_TYPE, type);
}
private ScalarFieldTypeUtil();
@Nonnull public static String getPrimitiveType(ScalarFieldType type);
@Nonnull public static String getDefaultValue(ScalarFieldType type);
@Nonnull private static String getNonNull(Map<ScalarFieldType, String> map, ScalarFieldType type);
}
class ScalarFieldTypeUtilTest {
@Test
void getWrapperType() {
|
assertEquals("Integer", ScalarFieldTypeUtil.getWrapperType(INT32));
}
}
|
32651977_6
|
class ScalarFieldTypeUtil {
@Nonnull
public static String getWrapperType(ScalarFieldType type) {
return getNonNull(WRAPPER_TYPE, type);
}
private ScalarFieldTypeUtil();
@Nonnull public static String getPrimitiveType(ScalarFieldType type);
@Nonnull public static String getDefaultValue(ScalarFieldType type);
@Nonnull private static String getNonNull(Map<ScalarFieldType, String> map, ScalarFieldType type);
}
class ScalarFieldTypeUtilTest {
@Test
void getWrapperType_null_input() {
|
Assertions.assertThrows(IllegalArgumentException.class,
() -> ScalarFieldTypeUtil.getWrapperType(null));
}
}
|
32651977_7
|
class ScalarFieldTypeUtil {
@Nonnull
public static String getPrimitiveType(ScalarFieldType type) {
return getNonNull(PRIMITIVE_TYPE, type);
}
private ScalarFieldTypeUtil();
@Nonnull public static String getWrapperType(ScalarFieldType type);
@Nonnull public static String getDefaultValue(ScalarFieldType type);
@Nonnull private static String getNonNull(Map<ScalarFieldType, String> map, ScalarFieldType type);
}
class ScalarFieldTypeUtilTest {
@Test
void getPrimitiveType() {
|
assertEquals("int", ScalarFieldTypeUtil.getPrimitiveType(INT32));
}
}
|
32651977_8
|
class ScalarFieldTypeUtil {
@Nonnull
public static String getDefaultValue(ScalarFieldType type) {
return getNonNull(DEFAULT_VALUE, type);
}
private ScalarFieldTypeUtil();
@Nonnull public static String getWrapperType(ScalarFieldType type);
@Nonnull public static String getPrimitiveType(ScalarFieldType type);
@Nonnull private static String getNonNull(Map<ScalarFieldType, String> map, ScalarFieldType type);
}
class ScalarFieldTypeUtilTest {
@Test
void getDefaultValue() {
|
assertEquals("0", ScalarFieldTypeUtil.getDefaultValue(INT32));
}
}
|
32651977_9
|
class MessageFieldUtil {
public static String bitFieldName(Field field) {
return "__bitField" + (field.getIndex() - 1) / 32;
}
private MessageFieldUtil();
public static String getFieldType(Field field);
public static String getFieldName(Field field);
public static String getJsonFieldName(Field field);
private static boolean isReservedKeyword(String formattedName);
public static String getFieldGetterName(Field field);
public static String getFieldSetterName(Field field);
public static String getFieldWitherName(Field field);
public static String getEnumFieldValueGetterName(Field field);
public static String getEnumFieldValueSetterName(Field field);
public static String getFieldCleanerName(Field field);
public static boolean isMessage(Field field);
public static String getHasMethodName(Field field);
public static String getBuilderSetterName(Field field);
public static String getDefaultValue(Field field);
public static boolean isScalarNullableType(Field field);
public static String getRepeatedFieldType(Field field);
public static String getIterableFieldType(Field field);
public static String getWrapperFieldType(Field field);
public static String getRepeatedFieldGetterName(Field field);
public static String getRepeatedEnumFieldValueGetterName(Field field);
public static String javaRepeatedEnumValueGetterByIndexName(Field field);
public static String getRepeatedEnumConverterName(Field field);
public static String getRepeatedFieldSetterName(Field field);
public static String getRepeatedEnumValueSetterName(Field field);
public static String repeatedGetCountMethodName(Field field);
public static String repeatedGetByIndexMethodName(Field field);
public static String getRepeatedBuilderSetterName(Field field);
public static String getBuilderGetterName(Field field);
public static String getRepeatedFieldAdderName(Field field);
public static String getRepeatedFieldAddAllName(Field field);
public static String getRepeatedEnumValueAdderName(Field field);
public static String getRepeatedEnumValueAddAllName(Field field);
public static String toStringPart(Field field);
public static String protostuffReadMethod(Field field);
public static String protostuffWriteMethod(Field field);
private static String protostuffIoMethodName(Field field, String operation);
public static int bitFieldIndex(Field field);
public static int bitFieldMask(Field field);
public static String getMapFieldType(Field field);
public static String getMapFieldKeyType(Field field);
public static String getMapFieldValueType(Field field);
public static String getMapGetterName(Field field);
public static String getMapSetterName(Field field);
public static String mapGetByKeyMethodName(Field field);
public static String getMapFieldAdderName(Field field);
public static String getMapFieldAddAllName(Field field);
public static String javaOneofConstantName(Field field);
public static boolean isNumericType(Field field);
public static boolean isBooleanType(Field field);
private Field f1;
private Field f32;
private Field f33;
}
class MessageFieldUtilTest {
private Field f1;
private Field f32;
private Field f33;
@Test
public void testBitFieldName() throws Exception {
|
assertEquals("__bitField0", MessageFieldUtil.bitFieldName(f1));
assertEquals("__bitField0", MessageFieldUtil.bitFieldName(f32));
assertEquals("__bitField1", MessageFieldUtil.bitFieldName(f33));
}
}
|
33329835_1
|
class EbtsUtils {
public static int byteArrayToInt(final byte[] bytes) {
if (bytes.length == 4) {
return Ints.fromByteArray(bytes);
} else if (bytes.length == 2) {
return Shorts.fromByteArray(bytes);
} else if (bytes.length == 1) {
return bytes[0] & 0xff;
} else {
throw new InputMismatchException("invalid data length of "+bytes.length);
}
}
private EbtsUtils();
public static Set<Integer> getBinaryHeaderTypes();
public static Set<Integer> getGenericRecordTypes();
private static void ensureExistence(final Map<Integer, HashBiMap<Integer, String>> map, final int recordType);
private static Map<Integer,HashBiMap<Integer,String>> loadPropertiesFile();
public static int tagToFieldNumber(final String tag);
public static int tagToRecordNumber(final String tag);
public static int[] splitTag(final String tag);
public static String fieldNumberToMnemonic(final int recordType, final int fieldNumber);
public static String fieldTagToMnemonic(final String tag);
public static int fieldMnemonicToNumber(final int recordType, final String fieldIdentifier);
public static List<String> convertOccurrenceList(final List<Occurrence> occurrences);
public static List<Occurrence> convertStringList(final List<String> strings);
public static List<Occurrence> convertStringList(final List<String> strings, final int limit);
public static List<SubField> convertStringListToSubFields(final List<String> strings);
public static String getMimeExtension(final byte[] data);
private static final Logger log;
}
class EbtsUtilsTest {
private static final Logger log;
@Test
public void testByteArrayToInt() throws Exception {
|
byte[] data = new byte[4];
data[0] = 0x00;
data[1] = 0x00;
data[2] = (byte) 0x98;
data[3] = (byte) 0xF2;
int val = EbtsUtils.byteArrayToInt(data);
assertEquals(39154,val);
log.debug("{}",val);
data = new byte[1];
data[0] = (byte) 0xFF;
val = EbtsUtils.byteArrayToInt(data);
log.debug("{}",val);
data = new byte[2];
data[0] = (byte) 0xFF;
data[1] = (byte) 0xFF;
val = EbtsUtils.byteArrayToInt(data);
log.debug("{}",val);
}
}
|
33329835_2
|
class EbtsParser {
public static Ebts parse(final byte[] bytes, final ParseType parseType) throws EbtsParsingException {
return EbtsParser.parse(bytes,parseType,Type7Handling.TREAT_AS_TYPE4);
}
public EbtsParser();
public static Ebts parse(final byte[] bytes, Type7Handling type7Handling);
public static Ebts parse(final byte[] bytes, final ParseType parseType, Type7Handling type7Handling);
public static Ebts parse(final byte[] bytes);
public static Ebts parse(final File file, final ParseType parseType, final Type7Handling type7Handling);
public static Ebts parse(final File file, final ParseType parseType);
public static Ebts parse(final File file);
@Deprecated public static Ebts parse(final String filePath, final ParseType parseType);
private static LogicalRecord parseGenericRecord(final int type, final ByteBuffer bb);
private static LogicalRecord parseType7(final int recordType, final ByteBuffer bb, final Type7Handling type7Handling);
private static BinaryHeaderImageRecord parseType7AsNist( int recordType, ByteBuffer bb );
private static BinaryHeaderImageRecord parseType7AsType4(final int recordType, final ByteBuffer bb);
private static LogicalRecord parseType3456(final int recordType, final ByteBuffer bb);
private static LogicalRecord parseBinaryHeaderRecord(final int recordType, final int[] headerFormat, final ByteBuffer bb);
private static LogicalRecord parseType8(final int recordType, final ByteBuffer bb);
private static byte[] convertBinaryFieldData(final byte[] data);
private static final Logger log;
Ebts ebts;
}
class EbtsParserTest {
private static final Logger log;
Ebts ebts;
@Test
public void testDescriptiveOnly() throws Exception {
|
File file = new File(ClassLoader.getSystemResource("EFT/S001-01-t10_01.eft").toURI());
EbtsParser ebtsParser = new EbtsParser();
Ebts ebtsDescriptiveOnly = ebtsParser.parse(file,ParseType.DESCRIPTIVE_ONLY);
Ebts ebts = ebtsParser.parse(file,ParseType.FULL);
//Type 1 and 2 only parsed
assertEquals(2,ebtsDescriptiveOnly.getAllRecords().size());
//Same number of fields
assertEquals(ebts.getRecordsByType(1).get(0).getLength(),ebtsDescriptiveOnly.getRecordsByType(1).get(0).getLength());
assertEquals(ebts.getRecordsByType(2).get(0).getLength(),ebtsDescriptiveOnly.getRecordsByType(2).get(0).getLength());
}
}
|
33329835_3
|
class EbtsParser {
public static Ebts parse(final byte[] bytes, final ParseType parseType) throws EbtsParsingException {
return EbtsParser.parse(bytes,parseType,Type7Handling.TREAT_AS_TYPE4);
}
public EbtsParser();
public static Ebts parse(final byte[] bytes, Type7Handling type7Handling);
public static Ebts parse(final byte[] bytes, final ParseType parseType, Type7Handling type7Handling);
public static Ebts parse(final byte[] bytes);
public static Ebts parse(final File file, final ParseType parseType, final Type7Handling type7Handling);
public static Ebts parse(final File file, final ParseType parseType);
public static Ebts parse(final File file);
@Deprecated public static Ebts parse(final String filePath, final ParseType parseType);
private static LogicalRecord parseGenericRecord(final int type, final ByteBuffer bb);
private static LogicalRecord parseType7(final int recordType, final ByteBuffer bb, final Type7Handling type7Handling);
private static BinaryHeaderImageRecord parseType7AsNist( int recordType, ByteBuffer bb );
private static BinaryHeaderImageRecord parseType7AsType4(final int recordType, final ByteBuffer bb);
private static LogicalRecord parseType3456(final int recordType, final ByteBuffer bb);
private static LogicalRecord parseBinaryHeaderRecord(final int recordType, final int[] headerFormat, final ByteBuffer bb);
private static LogicalRecord parseType8(final int recordType, final ByteBuffer bb);
private static byte[] convertBinaryFieldData(final byte[] data);
private static final Logger log;
Ebts ebts;
}
class EbtsParserTest {
private static final Logger log;
Ebts ebts;
@Test
public void type10EmptyImageTest() throws Exception {
|
File file = new File(ClassLoader.getSystemResource("EFT/empty_image.eft").toURI());
EbtsParser ebtsParser = new EbtsParser();
//previously threw exception
Ebts ebts = ebtsParser.parse(file,ParseType.FULL);
assertNotNull(ebts);
GenericRecord type10 = (GenericRecord) ebts.getRecordsByType(10).get(0);
assertFalse(type10.getFields().isEmpty());
assertEquals("JPEGB",type10.getField(11).toString());
assertFalse(type10.hasImageData());
}
}
|
33329835_5
|
class EbtsBuilder {
public byte[] build(final Ebts ebts) throws EbtsBuildingException {
this.ebts = ebts;
//Create the auto-expanding output stream
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Get list of all records
//Overwrite CNT field(1.03)
final List<LogicalRecord> records = ebts.getAllRecords();
for (final LogicalRecord record : records) {
if (genericTypes.contains(record.getRecordType())) {
genericBuilder((GenericRecord)record,baos);
} else if (binaryHeaderTypes.contains(record.getRecordType())) {
binaryHeaderBuilder((BinaryHeaderImageRecord)record,baos);
}
}
return baos.toByteArray();
}
public EbtsBuilder();
public EbtsBuilder(final int precedingZeros);
private void fixCountField(final GenericRecord record);
private int getNextAvailableIDC();
private void genericBuilder(final GenericRecord record, final ByteArrayOutputStream baos);
private static void binaryHeaderBuilder(final BinaryHeaderImageRecord record, final ByteArrayOutputStream baos);
public void setPrecedingZeros(final int precedingZeros);
private static final Logger log;
}
class EbtsBuilderTest {
private static final Logger log;
@Test
public void basicBuilderTest() throws Exception {
|
Ebts ebts = new Ebts();
GenericRecord type1 = new GenericRecord(1);
type1.setField(3, new Field("0400"));
type1.setField(8, new Field("WVMEDS001"));
GenericRecord type2 = new GenericRecord(2);
type2.setField(2, new Field("04"));
type2.setField(19, new Field("Smith,John"));
type2.getField(19).getOccurrences().add(new Occurrence("Smith,Johnny"));
type2.setField(18, new Field("Smith,Jo"));
type2.setField(41, new Field("B"));
type2.setField(40, new Field("A"));
List<String> strings = new ArrayList<String>();
strings.add("Test1");
strings.add("Test2");
strings.add("Test3");
List<Occurrence> occs = EbtsUtils.convertStringList(strings);
occs.add(new Occurrence("HI"));
occs.remove(new Occurrence("HI"));
type2.setField(50,new Field(occs));
GenericRecord type10 = new GenericRecord(10);
type10.setField(6, new Field("600"));
Random rand = new Random();
byte[] imageData = new byte[10];
rand.nextBytes(imageData);
type10.setImageData(imageData);
ebts.addRecord(type1);
ebts.addRecord(type10);
ebts.addRecord(type2);
EbtsBuilder builder = new EbtsBuilder(2);
byte[] data = builder.build(ebts);
log.info("EBTS Length: {}",data.length);
ByteBuffer bb = ByteBuffer.wrap(data);
assertTrue(ByteBufferUtils.find(bb, "A".getBytes()[0]) < ByteBufferUtils.find(bb, "B".getBytes()[0]));
assertEquals(200,data.length);
new EbtsParser().parse(data);
}
}
|
33403291_0
|
class MinecraftlyUtil {
public static long convertMillisToTicks( long milliseconds ) {
double nearestTickTime = round( milliseconds, 50 );
return (long) ((nearestTickTime / 1000) * 20);
}
public static UUID convertFromNoDashes( String uuidString );
public static String convertToNoDashes( UUID uuid );
public static String convertToNoDashes( String uuidString );
public static String downloadText( String url );
public static String downloadText( URL url );
public static String readText( String filePath );
public static String readText( File file );
public static double round( double value, double factor );
public static InetSocketAddress parseAddress( String address );
public static String getTimeString( long millis );
}
class MinecraftlyUtilTest {
@Test
public void tickConversionTest() {
|
Assert.assertEquals( 1, MinecraftlyUtil.convertMillisToTicks( 40 ) );
Assert.assertEquals( 1, MinecraftlyUtil.convertMillisToTicks( 50 ) );
Assert.assertEquals( 1, MinecraftlyUtil.convertMillisToTicks( 60 ) );
Assert.assertEquals( 3, MinecraftlyUtil.convertMillisToTicks( 140 ) );
Assert.assertEquals( 3, MinecraftlyUtil.convertMillisToTicks( 150 ) );
Assert.assertEquals( 3, MinecraftlyUtil.convertMillisToTicks( 160 ) );
}
}
|
34599551_1
|
class HelloWorldEndpointImpl implements HelloWorldPortType {
@Override
public Greeting sayHello(Person person) {
String firstName = person.getFirstName();
LOGGER.debug("firstName={}", firstName);
String lasttName = person.getLastName();
LOGGER.debug("lastName={}", lasttName);
ObjectFactory factory = new ObjectFactory();
Greeting response = factory.createGreeting();
String greeting = "Hello " + firstName + " " + lasttName + "!";
LOGGER.info("greeting={}", greeting);
response.setText(greeting);
return response;
}
private static String ENDPOINT_ADDRESS;
}
class HelloWorldEndpointImplTest {
private static String ENDPOINT_ADDRESS;
@Test
public void testSayHelloProxy() {
|
Person person = new Person();
person.setFirstName("John");
person.setLastName("Watson");
assertEquals("Hello John Watson!", new HelloWorldClientImplMock(
ENDPOINT_ADDRESS).sayHello(person, "john.watson", "w4750n"));
}
}
|
34599551_2
|
class HelloWorldEndpointImpl implements HelloWorldPortType {
@Override
public Greeting sayHello(Person person) {
String firstName = person.getFirstName();
LOGGER.debug("firstName={}", firstName);
String lasttName = person.getLastName();
LOGGER.debug("lastName={}", lasttName);
ObjectFactory factory = new ObjectFactory();
Greeting response = factory.createGreeting();
String greeting = "Hello " + firstName + " " + lasttName + "!";
LOGGER.info("greeting={}", greeting);
response.setText(greeting);
return response;
}
private static String ENDPOINT_ADDRESS;
}
class HelloWorldEndpointImplTest {
private static String ENDPOINT_ADDRESS;
@Test
public void testSayHelloNoCredentials() {
|
Person person = new Person();
person.setFirstName("Marie");
person.setLastName("Hudson");
try {
new HelloWorldClientImplMock(ENDPOINT_ADDRESS).sayHello(person);
fail("no credentials should fail");
} catch (SOAPFaultException soapFaultException) {
assertEquals(
"Authentication required but no user or password was supplied",
soapFaultException.getFault().getFaultString());
}
}
}
|
34599551_3
|
class HelloWorldEndpointImpl implements HelloWorldPortType {
@Override
public Greeting sayHello(Person person) {
String firstName = person.getFirstName();
LOGGER.debug("firstName={}", firstName);
String lasttName = person.getLastName();
LOGGER.debug("lastName={}", lasttName);
ObjectFactory factory = new ObjectFactory();
Greeting response = factory.createGreeting();
String greeting = "Hello " + firstName + " " + lasttName + "!";
LOGGER.info("greeting={}", greeting);
response.setText(greeting);
return response;
}
private static String ENDPOINT_ADDRESS;
}
class HelloWorldEndpointImplTest {
private static String ENDPOINT_ADDRESS;
@Test
public void testSayHelloUnknownUser() {
|
Person person = new Person();
person.setFirstName("Mycroft");
person.setLastName("Holmes");
try {
new HelloWorldClientImplMock(ENDPOINT_ADDRESS).sayHello(person,
"mycroft.holmes", "h0lm35");
fail("unknown user should fail");
} catch (SOAPFaultException soapFaultException) {
assertEquals(
"Authentication failed (details can be found in server log)",
soapFaultException.getFault().getFaultString());
}
}
}
|
34599551_4
|
class HelloWorldEndpointImpl implements HelloWorldPortType {
@Override
public Greeting sayHello(Person person) {
String firstName = person.getFirstName();
LOGGER.debug("firstName={}", firstName);
String lasttName = person.getLastName();
LOGGER.debug("lastName={}", lasttName);
ObjectFactory factory = new ObjectFactory();
Greeting response = factory.createGreeting();
String greeting = "Hello " + firstName + " " + lasttName + "!";
LOGGER.info("greeting={}", greeting);
response.setText(greeting);
return response;
}
private static String ENDPOINT_ADDRESS;
}
class HelloWorldEndpointImplTest {
private static String ENDPOINT_ADDRESS;
@Test
public void testSayHelloIncorrectPassword() {
|
Person person = new Person();
person.setFirstName("Jim");
person.setLastName("Moriarty");
try {
new HelloWorldClientImplMock(ENDPOINT_ADDRESS).sayHello(person,
"jim.moriarty", "moriarty");
fail("incorrect password should fail");
} catch (SOAPFaultException soapFaultException) {
assertEquals(
"Authentication failed (details can be found in server log)",
soapFaultException.getFault().getFaultString());
}
}
}
|
34599551_5
|
class HelloWorldClientImpl {
public String sayHello(Person person, String userName, String password) {
setBasicAuthentication(userName, password);
return sayHello(person);
}
public HelloWorldClientImpl(Bus bus);
private String sayHello(Person person);
private void setBasicAuthentication(String userName, String password);
private Properties loadProperties(String file);
private static String ENDPOINT_ADDRESS;
private static HelloWorldClientImpl helloWorldClientImpl;
}
class HelloWorldClientImplTest {
private static String ENDPOINT_ADDRESS;
private static HelloWorldClientImpl helloWorldClientImpl;
@Test
public void testSayHello() {
|
Person person = new Person();
person.setFirstName("Sherlock");
person.setLastName("Holmes");
assertEquals("Hello Sherlock Holmes!", helloWorldClientImpl.sayHello(
person, "sherlock.holmes", "h0lm35"));
}
}
|
34599551_6
|
class HelloWorldClientImpl {
public String sayHello(Person person) {
Greeting greeting = helloWorldJaxWsProxyBean.sayHello(person);
String result = greeting.getText();
LOGGER.info("result={}", result);
return result;
}
private static String ENDPOINT_ADDRESS;
@Autowired
private HelloWorldClientImpl helloWorldClientImplBean;
}
class HelloWorldClientImplTest {
private static String ENDPOINT_ADDRESS;
@Autowired
private HelloWorldClientImpl helloWorldClientImplBean;
@Test
public void testSayHello() {
|
Person person = new Person();
person.setFirstName("Sherlock");
person.setLastName("Holmes");
assertEquals("Hello Sherlock Holmes!",
helloWorldClientImplBean.sayHello(person));
}
}
|
34599551_7
|
class HelloWorldEndpointImpl implements HelloWorldPortType {
@Override
public Greeting sayHello(Person person) {
String firstName = person.getFirstName();
LOGGER.debug("firstName={}", firstName);
String lasttName = person.getLastName();
LOGGER.debug("lastName={}", lasttName);
ObjectFactory factory = new ObjectFactory();
Greeting response = factory.createGreeting();
String greeting = "Hello " + firstName + " " + lasttName + "!";
LOGGER.info("greeting={}", greeting);
response.setText(greeting);
return response;
}
private static String ENDPOINT_ADDRESS;
}
class HelloWorldEndpointImplTest {
private static String ENDPOINT_ADDRESS;
@Test
public void testSayHelloProxy() {
|
Person person = new Person();
person.setFirstName("John");
person.setLastName("Watson");
assertEquals("Hello John Watson!", new HelloWorldClientImplMock(
ENDPOINT_ADDRESS).sayHello(person));
}
}
|
34599551_8
|
class HelloWorldClientImpl {
public String sayHello(Person person) {
Greeting greeting = helloWorldClientBean.sayHello(person);
String result = greeting.getText();
LOGGER.info("result={}", result);
return result;
}
private static String ENDPOINT_ADDRESS;
@Autowired
private HelloWorldClientImpl helloWorldClientImplBean;
}
class HelloWorldClientImplTest {
private static String ENDPOINT_ADDRESS;
@Autowired
private HelloWorldClientImpl helloWorldClientImplBean;
@Test
public void testSayHello() {
|
Person person = new Person();
person.setFirstName("Sherlock");
person.setLastName("Holmes");
assertEquals("Hello Sherlock Holmes!",
helloWorldClientImplBean.sayHello(person));
}
}
|
35957836_1
|
class LanguageStats {
public static List<LanguageStats> buildStats(List<Project> projectList) {
List<Project> projects = filterUniqueSnapshots(projectList);
// For each date, we have a map of all the counts. Later we piece the
// results together from these pieces of information.
Map<Date, Map<String,Integer>> counts = new HashMap<>();
TreeSet<Date> dates = new TreeSet<>();
Set<String> languages = new HashSet<>();
for (Project p: projects) {
String language = p.getPrimaryLanguage();
Date date = p.getSnapshotDate();
if (language == null)
language = "unknown";
dates.add(date);
languages.add(language);
Map<String,Integer> hist = counts.get(date);
if (hist == null) {
hist = new HashMap<>();
counts.put(date, hist);
}
if (hist.containsKey(language)) {
hist.put(language, hist.get(language) + 1);
} else {
hist.put(language, 1);
}
}
List<LanguageStats> result = new ArrayList<>();
for (String l: languages) {
List<Integer> projectCounts = new ArrayList<>();
List<Date> snapshotDates = new ArrayList<>(dates);
for(Date d: snapshotDates) {
Integer i = counts.get(d).get(l);
if (i == null) {
projectCounts.add(0);
} else {
projectCounts.add(i);
}
}
result.add(new LanguageStats(l, projectCounts, snapshotDates));
}
return result;
}
public LanguageStats(String languageName, List<Integer> projectCounts, List<Date> snapshotDates);
public static List<Project> filterUniqueSnapshots(List<Project> projects);
@JsonProperty(value="name") public String getLanguageName();
@JsonProperty(value="project_counts") public List<Integer> getProjectCounts();
@JsonProperty(value="snapshot_dates") @JsonSerialize(using = JsonDateListSerializer.class) public List<Date> getSnapshotDates();
private static final String JAVA;
private static final String PYTHON;
}
class LanguageStatsTest {
private static final String JAVA;
private static final String PYTHON;
@Test
public void thatStatsAreBuiltForEmptyProjects() {
|
assertThat(LanguageStats.buildStats(Lists.newArrayList()), empty());
}
}
|
35957836_2
|
class LanguageStats {
public static List<LanguageStats> buildStats(List<Project> projectList) {
List<Project> projects = filterUniqueSnapshots(projectList);
// For each date, we have a map of all the counts. Later we piece the
// results together from these pieces of information.
Map<Date, Map<String,Integer>> counts = new HashMap<>();
TreeSet<Date> dates = new TreeSet<>();
Set<String> languages = new HashSet<>();
for (Project p: projects) {
String language = p.getPrimaryLanguage();
Date date = p.getSnapshotDate();
if (language == null)
language = "unknown";
dates.add(date);
languages.add(language);
Map<String,Integer> hist = counts.get(date);
if (hist == null) {
hist = new HashMap<>();
counts.put(date, hist);
}
if (hist.containsKey(language)) {
hist.put(language, hist.get(language) + 1);
} else {
hist.put(language, 1);
}
}
List<LanguageStats> result = new ArrayList<>();
for (String l: languages) {
List<Integer> projectCounts = new ArrayList<>();
List<Date> snapshotDates = new ArrayList<>(dates);
for(Date d: snapshotDates) {
Integer i = counts.get(d).get(l);
if (i == null) {
projectCounts.add(0);
} else {
projectCounts.add(i);
}
}
result.add(new LanguageStats(l, projectCounts, snapshotDates));
}
return result;
}
public LanguageStats(String languageName, List<Integer> projectCounts, List<Date> snapshotDates);
public static List<Project> filterUniqueSnapshots(List<Project> projects);
@JsonProperty(value="name") public String getLanguageName();
@JsonProperty(value="project_counts") public List<Integer> getProjectCounts();
@JsonProperty(value="snapshot_dates") @JsonSerialize(using = JsonDateListSerializer.class) public List<Date> getSnapshotDates();
private static final String JAVA;
private static final String PYTHON;
}
class LanguageStatsTest {
private static final String JAVA;
private static final String PYTHON;
@Test
public void thatStatsAreBuildForTwoProjectsOfDifferentLanguageAndSameSnapshotDate() {
|
Date snapshotDate = new Date();
Project javaProject = new Project();
javaProject.setName("Project 1");
javaProject.setPrimaryLanguage(JAVA);
javaProject.setSnapshotDate(snapshotDate);
Project pythonProject = new Project();
pythonProject.setName("Project 2");
pythonProject.setPrimaryLanguage(PYTHON);
pythonProject.setSnapshotDate(snapshotDate);
List<LanguageStats> listOfLanguageStats = LanguageStats.buildStats(Lists.newArrayList(javaProject, pythonProject));
assertThat(listOfLanguageStats.size(), is(2));
assertThat(listOfLanguageStats,
hasItem(new LanguageStatsMatcher(JAVA, Lists.newArrayList(1), Lists.newArrayList(snapshotDate))));
assertThat(listOfLanguageStats,
hasItem(new LanguageStatsMatcher(PYTHON, Lists.newArrayList(1), Lists.newArrayList(snapshotDate))));
}
}
|
35957836_3
|
class LanguageStats {
public static List<LanguageStats> buildStats(List<Project> projectList) {
List<Project> projects = filterUniqueSnapshots(projectList);
// For each date, we have a map of all the counts. Later we piece the
// results together from these pieces of information.
Map<Date, Map<String,Integer>> counts = new HashMap<>();
TreeSet<Date> dates = new TreeSet<>();
Set<String> languages = new HashSet<>();
for (Project p: projects) {
String language = p.getPrimaryLanguage();
Date date = p.getSnapshotDate();
if (language == null)
language = "unknown";
dates.add(date);
languages.add(language);
Map<String,Integer> hist = counts.get(date);
if (hist == null) {
hist = new HashMap<>();
counts.put(date, hist);
}
if (hist.containsKey(language)) {
hist.put(language, hist.get(language) + 1);
} else {
hist.put(language, 1);
}
}
List<LanguageStats> result = new ArrayList<>();
for (String l: languages) {
List<Integer> projectCounts = new ArrayList<>();
List<Date> snapshotDates = new ArrayList<>(dates);
for(Date d: snapshotDates) {
Integer i = counts.get(d).get(l);
if (i == null) {
projectCounts.add(0);
} else {
projectCounts.add(i);
}
}
result.add(new LanguageStats(l, projectCounts, snapshotDates));
}
return result;
}
public LanguageStats(String languageName, List<Integer> projectCounts, List<Date> snapshotDates);
public static List<Project> filterUniqueSnapshots(List<Project> projects);
@JsonProperty(value="name") public String getLanguageName();
@JsonProperty(value="project_counts") public List<Integer> getProjectCounts();
@JsonProperty(value="snapshot_dates") @JsonSerialize(using = JsonDateListSerializer.class) public List<Date> getSnapshotDates();
private static final String JAVA;
private static final String PYTHON;
}
class LanguageStatsTest {
private static final String JAVA;
private static final String PYTHON;
@Test
public void thatDuplicateProjectsAreFiltered() {
|
Date snapshotDate = new Date();
Project javaProject = new Project();
javaProject.setName("Project 1");
javaProject.setPrimaryLanguage(JAVA);
javaProject.setSnapshotDate(snapshotDate);
Project duplicateProject = new Project();
duplicateProject.setName("Project 1");
duplicateProject.setPrimaryLanguage(JAVA);
duplicateProject.setSnapshotDate(snapshotDate);
List<LanguageStats> listOfLanguageStats = LanguageStats.buildStats(Lists.newArrayList(javaProject, duplicateProject));
assertThat(listOfLanguageStats.size(), is(1));
}
}
|
35957836_4
|
class Scorer {
public int score(Project project) {
String jsCode = "";
jsCode += "var scoring = " + scoringProject + ";\n";
jsCode += "result.value = scoring(project);";
return ((Number) newExecutor(jsCode).bind("project", project).execute()).intValue();
}
public void setScoringProject(String scoringProject);
}
class ScorerTest {
@Test
public void testScore() throws Exception {
|
// given
Scorer scorer = new Scorer();
scorer.setScoringProject("function(project) { return project.forksCount > 0 ? ( "
+ "project.starsCount + project.forksCount + project.contributorsCount + "
+ "project.commitsCount / 100 ) : 0 }");
// when
Project project = new ProjectBuilder().starsCount(20).forksCount(10).contributorsCount(5).commitsCount(230)
.create();
// then
assertEquals(20 + 10 + 5 + 2, scorer.score(project));
// when
project.setForksCount(0);
// then
assertEquals(0, scorer.score(project));
}
}
|
35957836_5
|
class Contributor {
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Contributor {\n");
sb.append(" id: ").append(getId()).append("\n");
sb.append(" organizationId: ").append(getOrganizationId()).append("\n");
sb.append(" name: ").append(name).append("\n");
sb.append(" url: ").append(url).append("\n");
sb.append(" organizationalCommitsCount: ").append(organizationalCommitsCount).append("\n");
sb.append(" personalCommitsCount: ").append(personalCommitsCount).append("\n");
sb.append(" personalProjectsCount: ").append(personalProjectsCount).append("\n");
sb.append(" organizationalProjectsCount: ").append(organizationalProjectsCount).append("\n");
sb.append(" organizationName: ").append(organizationName).append("\n");
sb.append(" snapshotDate: ").append(getSnapshotDate()).append("\n");
sb.append("}\n");
return sb.toString();
}
public Contributor();
public Contributor(long id, long organizationId, Date snapshotDate);
public ContributorKey getKey();
@ApiModelProperty(value = "the GitHub User ID of the Contributor. Part of the primary key. See official GitHub REST API guide.") @JsonProperty("id") public long getId();
@ApiModelProperty(value = "the GitHub ID of the organization. Part of the primary key. See official GitHub REST API guide.") @JsonProperty("organizationId") public long getOrganizationId();
@ApiModelProperty(value = "Name of contributor") @JsonProperty("name") public String getName();
public void setName(String name);
@ApiModelProperty(value = "URL of contributor") @JsonProperty("url") public String getUrl();
public void setUrl(String url);
@ApiModelProperty(value = "Count of organizational commits.") @JsonProperty("organizationalCommitsCount") public Integer getOrganizationalCommitsCount();
public void setOrganizationalCommitsCount(Integer organizationalCommitsCount);
@ApiModelProperty(value = "Count of personal commits.") @JsonProperty("personalCommitsCount") public Integer getPersonalCommitsCount();
public void setPersonalCommitsCount(Integer personalCommitsCount);
@ApiModelProperty(value = "Count of personal projects of contributor.") @JsonProperty("personalProjectsCount") public Integer getPersonalProjectsCount();
public void setPersonalProjectsCount(Integer personalProjectsCount);
@ApiModelProperty(value = "Count of organization projects of contributor.") @JsonProperty("organizationalProjectsCount") public Integer getOrganizationalProjectsCount();
public void setOrganizationalProjectsCount(Integer organizationalProjectsCount);
@ApiModelProperty(value = "Organization of the Contributor.") @JsonProperty("organizationName") public String getOrganizationName();
public void setOrganizationName(String organizationName);
@ApiModelProperty(value = "Contributor snapshot date. Part of the primary key.") @JsonProperty("snapshotDate") public Date getSnapshotDate();
public String getLoginId();
}
class ContributorTest {
@Test
public void testToString_containsKey() throws Exception {
|
// given
Date date = new Date();
Contributor contributor = new Contributor(123456789, 987654321, date);
// when
String str = contributor.toString();
// then
assertThat(str, stringContainsInOrder(asList("id", ":", "123456789")));
assertThat(str, stringContainsInOrder(asList("organizationId", ":", "987654321")));
assertThat(str, stringContainsInOrder(asList("snapshotDate", ":", "" + date)));
}
}
|
35957836_6
|
class LanguageService {
public List<Language> getMainLanguages(final String organizations, final Comparator<Language> c, Optional<String> filterLanguage) {
Collection<String> organizationList = StringParser.parseStringList(organizations, ",");
List<Project> projectList = new ArrayList<>();
// get the projects
for (String org : organizationList) {
Iterable<Project> projects = repository.findProjects(org, Optional.empty(), filterLanguage);
for (Project project : projects) {
projectList.add(project);
}
}
// count the languages
List<String> languageList = new ArrayList<>();
for (Project p : projectList) {
if (StringUtils.isEmpty(p.getPrimaryLanguage())) {
logger.info(String.format("No primary programming language set for project [%s].", p.getName()));
continue;
}
languageList.add(p.getPrimaryLanguage());
}
List<Language> languages = new ArrayList<>();
Set<String> languageSet = new HashSet<>(languageList);
int frequency;
for (String language : languageSet) {
Language l = new Language(language);
frequency = Collections.frequency(languageList, language);
l.setPercentage((int) Math.round(((double) frequency) / languageList.size() * 100));
l.setProjectsCount(frequency);
languages.add(l);
}
// sort
if (languages.size() > 1) {
Collections.sort(languages, c);
}
return languages;
}
@Autowired public LanguageService(ProjectRepository repository);
public List<Language> filterLanguages(List<Language> languages, int limit, int offset);
public static final Logger logger;
@Mock ProjectRepository projectRepository;
@InjectMocks LanguageService languageService;
}
class LanguageServiceTest {
public static final Logger logger;
@Mock ProjectRepository projectRepository;
@InjectMocks LanguageService languageService;
@Test
public void checkProgrammingLanguage() {
|
logger.info("Setting up the projects...");
Project p1 = new ProjectBuilder().commitsCount(10)
.contributorsCount(5)
.forksCount(1)
.gitHubProjectId(12345)
.description("bogus project 1")
.name("bogus project 1")
.primaryLanguage("Java")
.organizationName("zalando-stups")
.getProject();
Project p2 = new ProjectBuilder().commitsCount(10)
.contributorsCount(5)
.forksCount(1)
.gitHubProjectId(12345)
.description("bogus project 2")
.name("bogus project 2")
.primaryLanguage("Scala")
.organizationName("zalando-stups")
.getProject();
Project p3 = new ProjectBuilder().commitsCount(10)
.contributorsCount(5)
.forksCount(1)
.gitHubProjectId(12345)
.description("bogus project 3")
.name("bogus project 3")
.primaryLanguage("C++")
.organizationName("zalando")
.getProject();
Project p4 = new ProjectBuilder().commitsCount(10)
.contributorsCount(5)
.forksCount(1)
.gitHubProjectId(12345)
.description("bogus project 4")
.name("bogus project 4")
.primaryLanguage(null)
.organizationName("zalando")
.getProject();
projectRepository.save(p1);
projectRepository.save(p2);
projectRepository.save(p3);
projectRepository.save(p4);
String organizations = "zalando,zalando-stups";
logger.info("Calling language service...");
List<Project> projectsZalando = new ArrayList<>();
List<Project> projectsZalandoStups = new ArrayList<>();
projectsZalandoStups.add(p1);
projectsZalandoStups.add(p2);
projectsZalando.add(p3);
projectsZalando.add(p4);
// given
when(projectRepository.findProjects("zalando", empty(), empty())).thenReturn(projectsZalando);
when(projectRepository.findProjects("zalando-stups", empty(), empty())).thenReturn(projectsZalandoStups);
// when
List<Language> result = languageService.getMainLanguages(organizations, new LanguagePercentComparator(), empty());
Assert.assertEquals(3, result.size());
}
}
|
39215543_0
|
class InstrumentedOkHttpClient extends OkHttpClient {
String metricId(String metric) {
return name(OkHttpClient.class, name, metric);
}
InstrumentedOkHttpClient(MetricRegistry registry, OkHttpClient rawClient, String name);
private void instrumentHttpCache();
private void instrumentConnectionPool();
private void instrumentNetworkRequests();
@Override public Authenticator authenticator();
@Override public Cache cache();
@Override public CertificatePinner certificatePinner();
@Override public ConnectionPool connectionPool();
@Override public List<ConnectionSpec> connectionSpecs();
@Override public int connectTimeoutMillis();
@Override public CookieJar cookieJar();
@Override public Dispatcher dispatcher();
@Override public Dns dns();
@Override public boolean followRedirects();
@Override public boolean followSslRedirects();
@Override public HostnameVerifier hostnameVerifier();
@Override public List<Interceptor> interceptors();
@Override public List<Interceptor> networkInterceptors();
@Override public OkHttpClient.Builder newBuilder();
@Override public Call newCall(Request request);
@Override public WebSocket newWebSocket(Request request, WebSocketListener listener);
@Override public int pingIntervalMillis();
@Override public List<Protocol> protocols();
@Override public Proxy proxy();
@Override public Authenticator proxyAuthenticator();
@Override public ProxySelector proxySelector();
@Override public int readTimeoutMillis();
@Override public boolean retryOnConnectionFailure();
@Override public SocketFactory socketFactory();
@Override public SSLSocketFactory sslSocketFactory();
@Override public int writeTimeoutMillis();
@Override public boolean equals(Object obj);
@Override public String toString();
private MetricRegistry registry;
private OkHttpClient rawClient;
@Rule public MockWebServer server;
@Rule public TemporaryFolder cacheRule;
}
class InstrumentedOkHttpClientTest {
private MetricRegistry registry;
private OkHttpClient rawClient;
@Rule public MockWebServer server;
@Rule public TemporaryFolder cacheRule;
@Test public void providedNameUsedInMetricId() {
|
String prefix = "custom";
String baseId = "network-requests-submitted";
assertThat(registry.getMeters()).isEmpty();
InstrumentedOkHttpClient client = new InstrumentedOkHttpClient(registry, rawClient, prefix);
String generatedId = client.metricId(baseId);
assertThat(registry.getMeters().get(generatedId)).isNotNull();
}
}
|
39215543_1
|
class InstrumentedOkHttpClients {
public static OkHttpClient create(MetricRegistry registry) {
return new InstrumentedOkHttpClient(registry, new OkHttpClient(), null);
}
private InstrumentedOkHttpClients();
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client);
public static OkHttpClient create(MetricRegistry registry, String name);
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client, String name);
private MetricRegistry registry;
}
class InstrumentedOkHttpClientsTest {
private MetricRegistry registry;
@Test public void instrumentDefaultClient() {
|
OkHttpClient client = InstrumentedOkHttpClients.create(registry);
// The connection, read, and write timeouts are the only configurations applied by default.
assertThat(client.connectTimeoutMillis()).isEqualTo(10_000);
assertThat(client.readTimeoutMillis()).isEqualTo(10_000);
assertThat(client.writeTimeoutMillis()).isEqualTo(10_000);
}
}
|
39215543_2
|
class InstrumentedOkHttpClients {
public static OkHttpClient create(MetricRegistry registry) {
return new InstrumentedOkHttpClient(registry, new OkHttpClient(), null);
}
private InstrumentedOkHttpClients();
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client);
public static OkHttpClient create(MetricRegistry registry, String name);
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client, String name);
private MetricRegistry registry;
}
class InstrumentedOkHttpClientsTest {
private MetricRegistry registry;
@Test public void instrumentAndNameDefaultClient() {
|
OkHttpClient client = InstrumentedOkHttpClients.create(registry, "custom");
// The connection, read, and write timeouts are the only configurations applied by default.
assertThat(client.connectTimeoutMillis()).isEqualTo(10_000);
assertThat(client.readTimeoutMillis()).isEqualTo(10_000);
assertThat(client.writeTimeoutMillis()).isEqualTo(10_000);
}
}
|
39215543_3
|
class InstrumentedOkHttpClients {
public static OkHttpClient create(MetricRegistry registry) {
return new InstrumentedOkHttpClient(registry, new OkHttpClient(), null);
}
private InstrumentedOkHttpClients();
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client);
public static OkHttpClient create(MetricRegistry registry, String name);
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client, String name);
private MetricRegistry registry;
}
class InstrumentedOkHttpClientsTest {
private MetricRegistry registry;
@Test public void instrumentProvidedClient() {
|
OkHttpClient rawClient = new OkHttpClient();
OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient);
assertThatClientsAreEqual(client, rawClient);
}
}
|
39215543_4
|
class InstrumentedOkHttpClients {
public static OkHttpClient create(MetricRegistry registry) {
return new InstrumentedOkHttpClient(registry, new OkHttpClient(), null);
}
private InstrumentedOkHttpClients();
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client);
public static OkHttpClient create(MetricRegistry registry, String name);
public static OkHttpClient create(MetricRegistry registry, OkHttpClient client, String name);
private MetricRegistry registry;
}
class InstrumentedOkHttpClientsTest {
private MetricRegistry registry;
@Test public void instrumentAndNameProvidedClient() {
|
OkHttpClient rawClient = new OkHttpClient();
OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient, "custom");
assertThatClientsAreEqual(client, rawClient);
}
}
|
39905754_0
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_withASingleWord() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "justification." }, 16);
assertEquals(Arrays.asList("justification. "), result);
}
}
|
39905754_1
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_withAFullLineSingleWord() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "0123456789ABCDE." }, 16);
assertEquals(Arrays.asList("0123456789ABCDE."), result);
}
}
|
39905754_2
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_MoreWords() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "This", "is", "an", "example", "of", "text", "justification." }, 16);
assertEquals(Arrays.asList("This is an", "example of text", "justification. "), result);
}
}
|
39905754_3
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_SingleLetter() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "a", "b", "c" }, 1);
assertEquals(Arrays.asList("a", "b", "c"), result);
}
}
|
39905754_4
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_LastLineHaveMoreWords() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "What", "must", "be", "shall", "be." }, 12);
assertEquals(Arrays.asList("What must be", "shall be. "), result);
}
}
|
39905754_5
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_WithEmptyWord() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "" }, 2);
assertEquals(Arrays.asList(" "), result);
}
}
|
39905754_6
|
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> output = new ArrayList<>();
int exclusiveStop = 0;
int start = 0;
while (exclusiveStop < words.length) {
exclusiveStop = exclusiveStop(words, start, maxWidth);
output.add(justifyLine(words, maxWidth, start, exclusiveStop));
start = exclusiveStop;
}
return output;
}
private String justifyLine(String[] words, int maxWidth, int start, int exclusiveStop);
private String justifyNoneLastLine(String[] words, int start, int exclusiveStop, int maxWidth);
private String justifyLastLine(String[] words, int start, int maxWidth);
private String repeatSpaces(int n);
private int wordsLength(String[] words, int start, int exclusiveStop);
private int exclusiveStop(String[] words, int start, int width);
}
class SolutionTest {
@Test
public void testFullJustify_WithMiddleLineContainingOnlyOneLetter() {
|
Solution solution = new Solution();
List<String> result = solution.fullJustify(new String[] { "hello", ",", "world" }, 5);
assertEquals(Arrays.asList("hello", ", ", "world"), result);
}
}
|
39905754_7
|
class EightQueens {
static boolean isSolution(List<Position> board) {
int size = board.size();
for (int i = 0; i < size; i++) {
Position firstPosition = board.get(i);
if (firstPosition.intersectPositions(board, i)) {
return false;
}
}
return true;
}
public static List<Position> findSolution(int boardSize);
private static List<Position> generate(int size);
}
class EightQueensTest {
@Test
public void
acceptance_test() {
|
List<Position> board = Arrays.asList(pos(0, 3),pos(1, 5), pos(2, 7), pos(3, 1),
pos(4, 6), pos(5, 0), pos(6, 2), pos(7, 4));
assertTrue(EightQueens.isSolution(board));
}
}
|
39905754_8
|
class EightQueens {
static boolean isSolution(List<Position> board) {
int size = board.size();
for (int i = 0; i < size; i++) {
Position firstPosition = board.get(i);
if (firstPosition.intersectPositions(board, i)) {
return false;
}
}
return true;
}
public static List<Position> findSolution(int boardSize);
private static List<Position> generate(int size);
}
class EightQueensTest {
@Test
public void
eight_queens_fails() {
|
List<Position> board = Arrays.asList(pos(0, 3),pos(1, 5), pos(2, 7), pos(3, 1),
pos(4, 6), pos(5, 0), pos(7, 2), pos(7, 4));
assertFalse(EightQueens.isSolution(board));
}
}
|
39905754_9
|
class EightQueens {
static boolean isSolution(List<Position> board) {
int size = board.size();
for (int i = 0; i < size; i++) {
Position firstPosition = board.get(i);
if (firstPosition.intersectPositions(board, i)) {
return false;
}
}
return true;
}
public static List<Position> findSolution(int boardSize);
private static List<Position> generate(int size);
}
class EightQueensTest {
@Test
public void
it_should_accept_when_there_is_one_queen() {
|
List<Position> board = asList(pos(0, 3));
assertTrue(EightQueens.isSolution(board));
}
}
|
42112681_0
|
class Symbol {
public static String java2Elisp(String javaName) {
StringBuffer lispName = new StringBuffer();
boolean lastCharWasDash = false;
char prev = ' ';
for (int i = 0; i < javaName.length(); i++) {
char c = javaName.charAt(i);
if (!Character.isLetterOrDigit(c)) {
lispName.append('-');
lastCharWasDash = true;
} else {
// add in a dash only if the last character was not a dash and we
// didn't undergo a case change from lower to upper case
if (i > 0 && !lastCharWasDash
&& Character.isLetter(prev)
&& Character.isLetter(c)
&& Character.isLowerCase(prev)
&& Character.isUpperCase(c)) {
lispName.append('-');
}
lispName.append(Character.toLowerCase(c));
lastCharWasDash = false;
}
prev = c;
}
return lispName.toString();
}
public Symbol(String name);
public String getName();
public String toString();
}
class SymbolTest {
@Test
public void testJava2Elisp1() {
|
assertEquals("jdee-foo-call-left-right", Symbol.java2Elisp("jdeeFooCallLeftRight"));
}
}
|
42112681_1
|
class Symbol {
public static String java2Elisp(String javaName) {
StringBuffer lispName = new StringBuffer();
boolean lastCharWasDash = false;
char prev = ' ';
for (int i = 0; i < javaName.length(); i++) {
char c = javaName.charAt(i);
if (!Character.isLetterOrDigit(c)) {
lispName.append('-');
lastCharWasDash = true;
} else {
// add in a dash only if the last character was not a dash and we
// didn't undergo a case change from lower to upper case
if (i > 0 && !lastCharWasDash
&& Character.isLetter(prev)
&& Character.isLetter(c)
&& Character.isLowerCase(prev)
&& Character.isUpperCase(c)) {
lispName.append('-');
}
lispName.append(Character.toLowerCase(c));
lastCharWasDash = false;
}
prev = c;
}
return lispName.toString();
}
public Symbol(String name);
public String getName();
public String toString();
}
class SymbolTest {
@Test
public void testJava2Elisp2() {
|
assertEquals("jdee-foo-call-left-right", Symbol.java2Elisp("jdee.foo.Call.leftRight"));
}
}
|
42112681_2
|
class Symbol {
public static String java2Elisp(String javaName) {
StringBuffer lispName = new StringBuffer();
boolean lastCharWasDash = false;
char prev = ' ';
for (int i = 0; i < javaName.length(); i++) {
char c = javaName.charAt(i);
if (!Character.isLetterOrDigit(c)) {
lispName.append('-');
lastCharWasDash = true;
} else {
// add in a dash only if the last character was not a dash and we
// didn't undergo a case change from lower to upper case
if (i > 0 && !lastCharWasDash
&& Character.isLetter(prev)
&& Character.isLetter(c)
&& Character.isLowerCase(prev)
&& Character.isUpperCase(c)) {
lispName.append('-');
}
lispName.append(Character.toLowerCase(c));
lastCharWasDash = false;
}
prev = c;
}
return lispName.toString();
}
public Symbol(String name);
public String getName();
public String toString();
}
class SymbolTest {
@Test
public void testJava2Elisp3() {
|
assertEquals("jdee-foo-call-left-right", Symbol.java2Elisp("jdee.foo.CALL_LEFT_RIGHT"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.