src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
RotationsToDistanceDecoder implements Decoder<T> { @Override public void update(T newPage) { decoder.update(newPage); } RotationsToDistanceDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub, BigDecimal wheelCircumference); void reset(); @Override void update(T newPage); @Override void invalidate(); }
@Test public void matchesKnownGood() { FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); class FreqListener implements BroadcastListener<TaggedTelemetryEvent> { private long rotations; public void receiveMessage(TaggedTelemetryEvent telemetryEvent) { if (telemetryEvent instanceof WheelRotationsUpdate) { WheelRotationsUpdate up = (WheelRotationsUpdate) telemetryEvent; rotations = up.getWheelRotations(); } } }; FreqListener freqListener = new FreqListener(); bus.addListener(TaggedTelemetryEvent.class, freqListener); BigDecimal speed = new BigDecimal(10.0); BigDecimal period = WHEEL_CIRCUM.divide(speed, 20, BigDecimal.ROUND_HALF_UP); int power = 200; int rotationsDelta = 10; int eventsDelta = 1; final byte[] data1 = new byte[8]; final byte[] data2 = new byte[8]; new TorqueData.TorqueDataPayload() .encode(data1); new TorqueData.TorqueDataPayload() .setEvents(eventsDelta) .updateTorqueSumFromPower(power, period) .setRotations(rotationsDelta) .encode(data2); TorqueData p1 = new TorqueData(data1); TorqueData p2 = new TorqueData(data2); RotationsToDistanceDecoder<RotationsToDistanceDecodable> dec = new RotationsToDistanceDecoder<>(bus, WHEEL_CIRCUM); dec.update(p1); dec.update(p2); assertEquals( rotationsDelta, freqListener.rotations ); }
CoastEventTrigger implements Decoder<T> { @Override @SuppressWarnings("unchecked") public void update(T newPage) { helper.update(newPage); } CoastEventTrigger(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub); @Override @SuppressWarnings("unchecked") void update(T newPage); @Override void invalidate(); @Override void reset(); }
@Test public void testCoastTimeout() { class CoastHelper implements BroadcastListener<TaggedTelemetryEvent> { boolean coastDetected = false; public void receiveMessage(TaggedTelemetryEvent event) { if (!(event instanceof CoastDetectedEvent)) { return; } coastDetected = true; } } FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); CoastEventTrigger<PowerOnlyDecodable> decoder = new CoastEventTrigger<>(bus); CoastHelper listener = new CoastHelper(); bus.addListener(TaggedTelemetryEvent.class, listener); decoder.update(new PowerOnlyDecodable() { public long getSumPowerDelta(PowerOnlyDecodable old) { return 0; } public long getEventCountDelta(CounterBasedDecodable old) { return 0; } public int getSumPower() { return 0; } public int getEventCount() { return 0; } public boolean isValidDelta(CounterBasedDecodable old) { return true; } public int getInstantPower() { return 0; } public long getTimestamp() { return 0; } }); decoder.update(new PowerOnlyDecodable() { public long getSumPowerDelta(PowerOnlyDecodable old) { return 0; } public long getEventCountDelta(CounterBasedDecodable old) { return 0; } public int getSumPower() { return 0; } public int getEventCount() { return 0; } public boolean isValidDelta(CounterBasedDecodable old) { return true; } public int getInstantPower() { return 0; } public long getTimestamp() { return CoastDetector.COAST_WINDOW; } }); assertTrue(listener.coastDetected); }
LapFlagDecoder implements Decoder<T> { @Override public void update(T newPage) { if (prev == null) {prev = newPage; return;} final boolean prevState = prev.isLapToggled(); final boolean state = newPage.isLapToggled(); prev = newPage; if (state == prevState) return; laps += 1; bus.send(new LapUpdate(newPage,laps)); } LapFlagDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> bus); @Override void update(T newPage); @Override void invalidate(); @Override void reset(); }
@Test public void shouldIncrement() { final FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<>(); final LapFlagDecoder<LapFlagDecodable> decoder = new LapFlagDecoder<>(bus); final int[] res = new int[1]; bus.addListener(LapUpdate.class, new BroadcastListener<LapUpdate>() { @Override public void receiveMessage(LapUpdate lapUpdate) { res[0] = lapUpdate.getLaps(); } }); assertEquals(0, res[0]); decoder.update(toggled); assertEquals(0, res[0]); decoder.update(untoggled); assertEquals(1, res[0]); decoder.update(untoggled); assertEquals(1, res[0]); decoder.update(toggled); assertEquals(2, res[0]); }
PowerOnlyDecoder implements Decoder<T> { public void update(T next) { counterBasedDecoder.update(next); } PowerOnlyDecoder(FilteredBroadcastMessenger<TaggedTelemetryEvent> updateHub); void reset(); void update(T next); void invalidate(); }
@Test public void testSumPower() { final double SIM_POWER = 123.0; final long EVENTS = 100; class PowerSumListener implements BroadcastListener<TaggedTelemetryEvent> { BigDecimal powersum = null; long events = 0; long sum = 0; public void receiveMessage(TaggedTelemetryEvent event) { if (!(event instanceof AveragePowerUpdate)) { return; } AveragePowerUpdate casted = (AveragePowerUpdate) event; powersum = casted.getAveragePower(); events = casted.getEvents(); sum = casted.getSumPower(); } } FilteredBroadcastMessenger<TaggedTelemetryEvent> bus = new FilteredBroadcastMessenger<TaggedTelemetryEvent>(); PowerOnlyDecoder<PowerOnlyDecodable> decoder = new PowerOnlyDecoder<>(bus); PowerSumListener listener = new PowerSumListener(); bus.addListener(TaggedTelemetryEvent.class, listener); decoder.update(new PowerOnlyDecodable() { public long getSumPowerDelta(PowerOnlyDecodable old) { return 0; } public long getEventCountDelta(CounterBasedDecodable old) { return 0; } public int getSumPower() { return 0; } public int getEventCount() { return 0; } public boolean isValidDelta(CounterBasedDecodable old) { return true; } public int getInstantPower() { return 0; } public long getTimestamp() { return 0; } }); decoder.update(new PowerOnlyDecodable() { public long getSumPowerDelta(PowerOnlyDecodable old) { return (long) (EVENTS * SIM_POWER); } public long getEventCountDelta(CounterBasedDecodable old) { return EVENTS; } public int getSumPower() { return 0; } public int getEventCount() { return 0; } public boolean isValidDelta(CounterBasedDecodable old) { return true; } public int getInstantPower() { return 0; } public long getTimestamp() { return 1; } }); assertEquals(listener.powersum.doubleValue(), SIM_POWER, 0.1); assertEquals(listener.events, EVENTS); assertEquals(listener.sum, (long) (EVENTS * SIM_POWER)); }
LookupManagerImpl extends UniversalManagerImpl implements LookupManager { public List<LabelValue> getAllRoles() { List<Role> roles = dao.getRoles(); List<LabelValue> list = new ArrayList<LabelValue>(); for (Role role1 : roles) { list.add(new LabelValue(role1.getName(), role1.getName())); } return list; } void setLookupDao(LookupDao dao); List<LabelValue> getAllRoles(); }
@Test public void testGetAllRoles() { log.debug("entered 'testGetAllRoles' method"); Role role = new Role(Constants.ADMIN_ROLE); final List<Role> testData = new ArrayList<Role>(); testData.add(role); context.checking(new Expectations() {{ one(lookupDao).getRoles(); will(returnValue(testData)); }}); List<LabelValue> roles = mgr.getAllRoles(); assertTrue(roles.size() > 0); }
UserManagerImpl extends UniversalManagerImpl implements UserManager, UserService { public User getUser(String userId) { return dao.get(new Integer(userId)); } @Required void setPasswordEncoder(PasswordEncoder passwordEncoder); User getUser(String userId); List<User> getUsers(User user); String createSession(User user); User authenticate(String username, String password); User authenticate(String sessionKey); void logout(UserSession userSession); User saveUser(User user); void removeUser(String userId); User getUserByUsername(String username); UserSessionDao getUserSessionDao(); void setUserSessionDao(UserSessionDao userSessionDao); @Required void setUserDao(UserDao dao); }
@Test public void testGetUser() throws Exception { final User testData = new User("1"); testData.getRoles().add(new Role("user")); context.checking(new Expectations() {{ one(userDao).get(with(equal(1))); will(returnValue(testData)); }}); User user = userManager.getUser("1"); assertTrue(user != null); assert user != null; assertTrue(user.getRoles().size() == 1); }
UserManagerImpl extends UniversalManagerImpl implements UserManager, UserService { public User saveUser(User user) throws UserExistsException { if (user.getVersion() == null) { user.setUsername(user.getUsername().toLowerCase()); } boolean passwordChanged = false; if (passwordEncoder != null) { if (user.getVersion() == null) { passwordChanged = true; } else { String currentPassword = dao.getUserPassword(user.getUsername()); if (currentPassword == null) { passwordChanged = true; } else { if (!currentPassword.equals(user.getPassword())) { passwordChanged = true; } } } if (passwordChanged) { user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null)); } } else { log.warn("PasswordEncoder not set, skipping password encryption..."); } try { return dao.saveUser(user); } catch (DataIntegrityViolationException e) { e.printStackTrace(); log.warn(e.getMessage()); throw new UserExistsException("User '" + user.getUsername() + "' already exists!"); } catch (EntityExistsException e) { e.printStackTrace(); log.warn(e.getMessage()); throw new UserExistsException("User '" + user.getUsername() + "' already exists!"); } } @Required void setPasswordEncoder(PasswordEncoder passwordEncoder); User getUser(String userId); List<User> getUsers(User user); String createSession(User user); User authenticate(String username, String password); User authenticate(String sessionKey); void logout(UserSession userSession); User saveUser(User user); void removeUser(String userId); User getUserByUsername(String username); UserSessionDao getUserSessionDao(); void setUserSessionDao(UserSessionDao userSessionDao); @Required void setUserDao(UserDao dao); }
@Test public void testSaveUser() throws Exception { final User testData = new User("1"); testData.getRoles().add(new Role("user")); context.checking(new Expectations() {{ one(userDao).get(with(equal(1))); will(returnValue(testData)); }}); final User user = userManager.getUser("1"); user.setPhoneNumber("303-555-1212"); context.checking(new Expectations() {{ one(userDao).saveUser(with(same(user))); will(returnValue(user)); }}); User returned = userManager.saveUser(user); assertTrue(returned.getPhoneNumber().equals("303-555-1212")); assertTrue(returned.getRoles().size() == 1); } @Test public void testUserExistsException() { final User user = new User(Constants.DEFAULT_ADMIN_USERNAME); user.setEmail("[email protected]"); final Exception ex = new DataIntegrityViolationException(""); context.checking(new Expectations() {{ one(userDao).saveUser(with(same(user))); will(throwException(ex)); }}); try { userManager.saveUser(user); fail("Expected UserExistsException not thrown"); } catch (UserExistsException e) { log.debug("expected exception: " + e.getMessage()); assertNotNull(e); } }
LuaProfile extends ProfileDefinition { @Override public RulesProfile createProfile(ValidationMessages validation) { AnnotationBasedProfileBuilder annotationBasedProfileBuilder = new AnnotationBasedProfileBuilder(ruleFinder); return annotationBasedProfileBuilder.build( CheckList.REPOSITORY_KEY, CheckList.SONAR_WAY_PROFILE, Lua.KEY, CheckList.getChecks(), validation); } LuaProfile(RuleFinder ruleFinder); @Override RulesProfile createProfile(ValidationMessages validation); }
@Test public void should_create_sonar_way_profile() { ValidationMessages validation = ValidationMessages.create(); RuleFinder ruleFinder = ruleFinder(); LuaProfile definition = new LuaProfile(ruleFinder); RulesProfile profile = definition.createProfile(validation); assertThat(profile.getLanguage()).isEqualTo(Lua.KEY); assertThat(profile.getName()).isEqualTo(CheckList.SONAR_WAY_PROFILE); assertThat(profile.getActiveRulesByRepository(CheckList.REPOSITORY_KEY)).hasSize(15); assertThat(validation.hasErrors()).isFalse(); }
CoberturaSensor implements Sensor { @Override public void execute(SensorContext context) { String reportPath = context.settings().getString(LuaPlugin.COBERTURA_REPORT_PATH); if (reportPath != null) { File xmlFile = getIOFile(context.fileSystem(), reportPath); if (xmlFile.exists()) { LOGGER.info("Analyzing Cobertura report: " + reportPath); CoberturaReportParser.parseReport(xmlFile, context); } else { LOGGER.info("Cobertura xml report not found: " + reportPath); } } else { LOGGER.info("No Cobertura report provided (see '" + LuaPlugin.COBERTURA_REPORT_PATH + "' property)"); } } @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }
@Test public void noReport() { sensor.execute(tester); } @Test public void shouldParseReport() throws Exception { DefaultInputFile inputFile = new DefaultInputFile("key", "src/example/file.lua") .setLanguage(Lua.KEY) .setType(InputFile.Type.MAIN) .initMetadata(new FileMetadata().readMetadata(new FileReader(TEST_DIR + "src/example/file.lua"))); tester.fileSystem().add(inputFile); tester.settings().setProperty(LuaPlugin.COBERTURA_REPORT_PATH, "coverage.xml"); sensor.execute(tester); String componentKey = "key:src/example/file.lua"; Integer[] expectedConditions = {2, null, null, null, null, null, null, null, null, null}; Integer[] expectedCoveredConditions = {1, null, null, null, null, null, null, null, null, null}; Integer[] expectedHits = {0, null, null, null, null, null, 0, null, null, null}; for (int line = 1; line <= expectedConditions.length; line++) { assertThat(tester.coveredConditions(componentKey, CoverageType.UNIT, line)).as("line " + line).isEqualTo(expectedCoveredConditions[line - 1]); assertThat(tester.conditions(componentKey, CoverageType.UNIT, line)).as("line " + line).isEqualTo(expectedConditions[line - 1]); assertThat(tester.lineHits(componentKey, CoverageType.UNIT, line)).as("line " + line).isEqualTo(expectedHits[line - 1]); assertThat(tester.coveredConditions(componentKey, CoverageType.IT, line)).isNull(); assertThat(tester.lineHits(componentKey, CoverageType.IT, line)).isNull(); assertThat(tester.coveredConditions(componentKey, CoverageType.OVERALL, line)).isNull(); assertThat(tester.lineHits(componentKey, CoverageType.OVERALL, line)).isNull(); } } @Test public void reportNotFound() { tester.settings().setProperty(LuaPlugin.COBERTURA_REPORT_PATH, "/fake/path"); sensor.execute(tester); }
CoberturaSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Lua Cobertura") .onlyOnFileType(InputFile.Type.MAIN) .onlyOnLanguage(Lua.KEY); } @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }
@Test public void testDescriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor.describe(descriptor); assertThat(descriptor.name()).isEqualTo("Lua Cobertura"); assertThat(descriptor.languages()).containsOnly("lua"); }
LuaToolkit { @VisibleForTesting static List<Tokenizer> getTokenizers() { return ImmutableList.of( new StringTokenizer("<span class=\"s\">", "</span>"), new CDocTokenizer("<span class=\"cd\">", "</span>"), new JavadocTokenizer("<span class=\"cppd\">", "</span>"), new CppDocTokenizer("<span class=\"cppd\">", "</span>"), new KeywordsTokenizer("<span class=\"k\">", "</span>", LuaKeyword.keywordValues())); } private LuaToolkit(); static void main(String[] args); }
@Test public void test() { assertThat(LuaToolkit.getTokenizers().size()).isEqualTo(5); }
LuaCommentAnalyser extends CommentAnalyser { @Override public String getContents(String comment) { if (comment.startsWith("--[[")) { if (comment.endsWith("--]]")) { return comment.substring(4, comment.length() - 4); } return comment.substring(4); } else if (comment.startsWith("--")) { return comment.substring(2, comment.length()); } else{ throw new IllegalArgumentException(); } } @Override boolean isBlank(String line); @Override String getContents(String comment); }
@Test public void content() { assertThat(analyser.getContents("--[[comment1 \n comment2--]]")).isEqualTo("comment1 \n comment2"); assertThat(analyser.getContents("--comment")).isEqualTo("comment"); } @Test public void unknown_type_of_comment() { thrown.expect(IllegalArgumentException.class); analyser.getContents(""); }
LuaCommentAnalyser extends CommentAnalyser { @Override public boolean isBlank(String line) { for (int i = 0; i < line.length(); i++) { if (Character.isLetterOrDigit(line.charAt(i))) { return false; } } return true; } @Override boolean isBlank(String line); @Override String getContents(String comment); }
@Test public void blank() { assertThat(analyser.isBlank(" ")).isTrue(); assertThat(analyser.isBlank("comment")).isFalse(); }
LuaAstScanner { public static AstScanner<LexerlessGrammar> create(LuaConfiguration conf, List<SquidAstVisitor<LexerlessGrammar>> visitors) { final SquidAstVisitorContextImpl<LexerlessGrammar> context = new SquidAstVisitorContextImpl<>(new SourceProject("Lua Project")); final Parser<LexerlessGrammar> parser = LuaParser.create(conf); AstScanner.Builder<LexerlessGrammar> builder = new ProgressAstScanner.Builder(context).setBaseParser(parser); builder.withMetrics(LuaMetric.values()); builder.setFilesMetric(LuaMetric.FILES); builder.setCommentAnalyser(new LuaCommentAnalyser()); / builder.withSquidAstVisitor(new SourceCodeBuilderVisitor<LexerlessGrammar>(new SourceCodeBuilderCallback() { private int seq = 0; @Override public SourceCode createSourceCode(SourceCode parentSourceCode, AstNode astNode) { seq++; SourceClass cls = new SourceClass("table:" + seq); cls.setStartAtLine(astNode.getTokenLine()); return cls; } },LuaGrammar.TABLECONSTRUCTOR)); builder.withSquidAstVisitor(CounterVisitor.<LexerlessGrammar>builder() .setMetricDef(LuaMetric.TABLECONSTRUCTORS) .subscribeTo(LuaGrammar.TABLECONSTRUCTOR) .build()); builder.withSquidAstVisitor(new SourceCodeBuilderVisitor<LexerlessGrammar>(new SourceCodeBuilderCallback() { private int seq = 0; @Override public SourceCode createSourceCode(SourceCode parentSourceCode, AstNode astNode) { seq++; SourceFunction function = new SourceFunction("function" + seq); function.setStartAtLine(astNode.getTokenLine()); return function; } }, LuaGrammar.FUNCTION,LuaGrammar.FUNCSTAT,LuaGrammar.LOCALFUNCSTAT)); builder.withSquidAstVisitor(CounterVisitor.<LexerlessGrammar>builder() .setMetricDef(LuaMetric.FUNCTIONS) .subscribeTo(LuaGrammar.FUNCTION,LuaGrammar.FUNCSTAT,LuaGrammar.LOCALFUNCSTAT) .build()); builder.withSquidAstVisitor(new SourceCodeBuilderVisitor<LexerlessGrammar>(new SourceCodeBuilderCallback() { private int seq = 0; @Override public SourceCode createSourceCode(SourceCode parentSourceCode, AstNode astNode) { seq++; SourceFuncCall functionCall = new SourceFuncCall("functionCall" + seq); functionCall.setStartAtLine(astNode.getTokenLine()); return functionCall; } },LuaGrammar.FUNCTIONCALL)); builder.withSquidAstVisitor(CounterVisitor.<LexerlessGrammar>builder() .setMetricDef(LuaMetric.FUNCTIONCALL) .subscribeTo(LuaGrammar.FUNCTIONCALL) .build()); builder.withSquidAstVisitor(new LinesVisitor<LexerlessGrammar>(LuaMetric.LINES)); builder.withSquidAstVisitor(new LinesOfCodeVisitor<LexerlessGrammar>(LuaMetric.LINES_OF_CODE)); builder.withSquidAstVisitor(CommentsVisitor.<LexerlessGrammar>builder().withCommentMetric(LuaMetric.COMMENT_LINES) .withNoSonar(true) .withIgnoreHeaderComment(conf.getIgnoreHeaderComments()) .build()); builder.withSquidAstVisitor(CounterVisitor.<LexerlessGrammar>builder() .setMetricDef(LuaMetric.STATEMENTS) .subscribeTo( LuaGrammar.IF_STATEMENT, LuaGrammar.WHILE_STATEMENT, LuaGrammar.FOR_STATEMENT, LuaGrammar.DO_STATEMENT, LuaGrammar.WHILE_STATEMENT, LuaGrammar.REPEAT_STATEMENT, LuaGrammar.Keyword.AND, LuaGrammar.Keyword.OR ).build()); builder.withSquidAstVisitor(new ComplexityVisitor()); for (SquidAstVisitor<LexerlessGrammar> visitor : visitors) { if (visitor instanceof CharsetAwareVisitor) { ((CharsetAwareVisitor) visitor).setCharset(conf.getCharset()); } builder.withSquidAstVisitor(visitor); } return builder.build(); } private LuaAstScanner(); static SourceFile scanSingleFile(File file, SquidAstVisitor<LexerlessGrammar>... visitors); static AstScanner<LexerlessGrammar> create(LuaConfiguration conf, List<SquidAstVisitor<LexerlessGrammar>> visitors); }
@Test public void files() { AstScanner<LexerlessGrammar> scanner = LuaAstScanner.create(new LuaConfiguration(Charsets.UTF_8), Collections.emptyList()); scanner.scanFiles(ImmutableList.of(new File("src/test/resources/metrics/comments.lua"), new File("src/test/resources/metrics/lines.lua"))); SourceProject project = (SourceProject) scanner.getIndex().search(new QueryByType(SourceProject.class)).iterator().next(); assertThat(project.getInt(LuaMetric.FILES)).isEqualTo(2); }
LuaAstScanner { public static SourceFile scanSingleFile(File file, SquidAstVisitor<LexerlessGrammar>... visitors) { if (!file.isFile()) { throw new IllegalArgumentException("File '" + file + "' not found."); } AstScanner<LexerlessGrammar> scanner = create(new LuaConfiguration(Charsets.UTF_8), Arrays.asList(visitors)); scanner.scanFile(file); Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class)); if (sources.size() != 1) { throw new IllegalStateException("Only one SourceFile was expected whereas " + sources.size() + " has been returned."); } return (SourceFile) sources.iterator().next(); } private LuaAstScanner(); static SourceFile scanSingleFile(File file, SquidAstVisitor<LexerlessGrammar>... visitors); static AstScanner<LexerlessGrammar> create(LuaConfiguration conf, List<SquidAstVisitor<LexerlessGrammar>> visitors); }
@Test public void lines() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/lines.lua")); assertThat(file.getInt(LuaMetric.LINES)).isEqualTo(4); } @Test public void functionCall() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/functionCall.lua")); assertThat(file.getInt(LuaMetric.FUNCTIONCALL)).isEqualTo(3); } @Test public void lines_of_code() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/line_of_code.lua")); assertThat(file.getInt(LuaMetric.LINES_OF_CODE)).isEqualTo(15); } @Test public void TableConstructors() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/tableConstructor.lua")); assertThat(file.getInt(LuaMetric.TABLECONSTRUCTORS)).isEqualTo(4); } @Test public void functions() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/function.lua")); assertThat(file.getInt(LuaMetric.FUNCTIONS)).isEqualTo(6); } @Test public void statments() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/statement.lua")); assertThat(file.getInt(LuaMetric.STATEMENTS)).isEqualTo(3); } @Test public void complexity() { SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/metrics/complexity.lua")); assertThat(file.getInt(LuaMetric.COMPLEXITY)).isEqualTo(4); }
LuaSquidSensor implements Sensor { @Override public void execute(SensorContext context) { FileSystem fileSystem = context.fileSystem(); FilePredicates predicates = fileSystem.predicates(); List<SquidAstVisitor<LexerlessGrammar>> visitors = new ArrayList<>(checks.all()); visitors.add(new FileLinesVisitor(fileLinesContextFactory, fileSystem)); LuaConfiguration configuration = new LuaConfiguration(fileSystem.encoding()); scanner = LuaAstScanner.create(configuration, visitors); Iterable<java.io.File> files = fileSystem.files( predicates.and( predicates.hasType(InputFile.Type.MAIN), predicates.hasLanguage(Lua.KEY), inputFile -> !inputFile.absolutePath().endsWith("mxml") )); scanner.scanFiles(ImmutableList.copyOf(files)); Collection<SourceCode> squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class)); save(context, squidSourceFiles); } LuaSquidSensor(CheckFactory checkFactory, FileLinesContextFactory fileLinesContextFactory); @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }
@Test public void analyse() throws FileNotFoundException { DefaultFileSystem fs = new DefaultFileSystem(TEST_DIR); tester.setFileSystem(fs); DefaultInputFile inputFile = new DefaultInputFile("key", "smallFile.lua") .setType(InputFile.Type.MAIN) .setLanguage(Lua.KEY) .initMetadata(new FileMetadata().readMetadata(new FileReader(new File(TEST_DIR, "smallFile.lua")))); fs.add(inputFile); inputFile = new DefaultInputFile("key", "bom.lua") .setType(InputFile.Type.MAIN) .setLanguage(Lua.KEY) .initMetadata(new FileMetadata().readMetadata(new FileReader(new File(TEST_DIR, "bom.lua")))); fs.add(inputFile); sensor.execute(tester); String componentKey = "key:smallFile.lua"; assertThat(tester.measure(componentKey, CoreMetrics.COMPLEXITY_IN_CLASSES).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.NCLOC).value()).isEqualTo(4); assertThat(tester.measure(componentKey, CoreMetrics.COMMENT_LINES).value()).isEqualTo(1); assertThat(tester.measure(componentKey, CoreMetrics.STATEMENTS).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.FUNCTIONS).value()).isEqualTo(3); assertThat(tester.measure(componentKey, CoreMetrics.COMPLEXITY).value()).isEqualTo(4); assertThat(tester.measure(componentKey, CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION).value()).isEqualTo("0=1;5=0;10=0;20=0;30=0;60=0;90=0"); assertThat(tester.measure(componentKey, CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION).value()).isEqualTo("1=2;2=0;4=1;6=0;8=0;10=0;12=0"); } @Test public void analyse2() throws FileNotFoundException { DefaultFileSystem fs = new DefaultFileSystem(TEST_DIR); tester.setFileSystem(fs); DefaultInputFile inputFile = new DefaultInputFile("key", "timeFormatter.lua") .setType(InputFile.Type.MAIN) .setLanguage(Lua.KEY) .initMetadata(new FileMetadata().readMetadata(new FileReader(new File(TEST_DIR, "timeFormatter.lua")))); fs.add(inputFile); sensor.execute(tester); String componentKey = inputFile.key(); assertThat(tester.measure(componentKey, CoreMetrics.COMPLEXITY_IN_CLASSES).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.NCLOC).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.COMMENT_LINES).value()).isEqualTo(59); assertThat(tester.measure(componentKey, CoreMetrics.STATEMENTS).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.FUNCTIONS).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.COMPLEXITY).value()).isEqualTo(0); assertThat(tester.measure(componentKey, CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION).value()).isEqualTo("0=1;5=0;10=0;20=0;30=0;60=0;90=0"); assertThat(tester.measure(componentKey, CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION).value()).isEqualTo("1=0;2=0;4=0;6=0;8=0;10=0;12=0"); assertThat(tester.allIssues()).hasSize(0); }
FunctionCallComplexityCheck extends LuaCheck { public void setMaximumFunctionCallComplexityThreshold(int threshold) { this.maximumFunctionCallComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionCallComplexityThreshold(int threshold); }
@Test public void test() { FunctionCallComplexityCheck check = new FunctionCallComplexityCheck(); check.setMaximumFunctionCallComplexityThreshold(1); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/functionCallComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("FunctionCall has a complexity of 5 which is greater than 1 authorized.") .noMore(); }
MethodComplexityCheck extends LuaCheck { public void setMaximumFunctionComplexityThreshold(int threshold) { this.maximumMethodComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionComplexityThreshold(int threshold); static final String CHECK_KEY; }
@Test public void test() { MethodComplexityCheck check = new MethodComplexityCheck(); check.setMaximumFunctionComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/methodComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Method has a complexity of 6 which is greater than 0 authorized.") .next().atLine(3).withMessage("Method has a complexity of 2 which is greater than 0 authorized.") .next().atLine(4).withMessage("Method has a complexity of 1 which is greater than 0 authorized.") .next().atLine(11).withMessage("Method has a complexity of 1 which is greater than 0 authorized.") .noMore(); }
FileComplexityCheck extends SquidCheck<LexerlessGrammar> { public void setMaximumFileComplexityThreshold(int threshold) { this.maximumFileComplexityThreshold = threshold; } @Override void leaveFile(AstNode astNode); void setMaximumFileComplexityThreshold(int threshold); static final String CHECK_KEY; }
@Test public void test() { check.setMaximumFileComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/fileComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().withMessage("File has a complexity of 1 which is greater than 0"+ " authorized.") .noMore(); }
LocalFunctionComplexityCheck extends LuaCheck { public void setMaximumFunctionComplexityThreshold(int threshold) { this.maximumLocalFunctionComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionComplexityThreshold(int threshold); static final String CHECK_KEY; }
@Test public void test() { LocalFunctionComplexityCheck check = new LocalFunctionComplexityCheck(); check.setMaximumFunctionComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/localFunctionComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("LocalFunction has a complexity of 6 which is greater than 0 authorized.") .next().atLine(2).withMessage("LocalFunction has a complexity of 3 which is greater than 0 authorized.") .noMore(); }
FunctionComplexityCheck extends LuaCheck { public void setMaximumFunctionComplexityThreshold(int threshold) { this.maximumFunctionComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumFunctionComplexityThreshold(int threshold); static final String CHECK_KEY; }
@Test public void test() { FunctionComplexityCheck check = new FunctionComplexityCheck(); check.setMaximumFunctionComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/functionComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Function has a complexity of 4 which is greater than 0 authorized.") .noMore(); }
TableComplexityCheck extends LuaCheck { public void setMaximumTableComplexityThreshold(int threshold) { this.maximumTableComplexityThreshold = threshold; } @Override void init(); @Override void leaveNode(AstNode node); void setMaximumTableComplexityThreshold(int threshold); }
@Test public void test() { TableComplexityCheck check = new TableComplexityCheck(); check.setMaximumTableComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.") .noMore(); }
LuaSquidSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor .name("Lua") .onlyOnFileType(InputFile.Type.MAIN) .onlyOnLanguage(Lua.KEY); } LuaSquidSensor(CheckFactory checkFactory, FileLinesContextFactory fileLinesContextFactory); @Override void describe(SensorDescriptor descriptor); @Override void execute(SensorContext context); }
@Test public void testDescriptor() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor(); sensor.describe(descriptor); assertThat(descriptor.name()).isEqualTo("Lua"); assertThat(descriptor.languages()).containsOnly("lua"); }
LuaRulesDefinition implements RulesDefinition { @Override public void define(Context context) { NewRepository repository = context .createRepository(CheckList.REPOSITORY_KEY, "lua") .setName(REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, "lua").addRuleClasses(false, CheckList.getChecks()); repository.done(); } @Override void define(Context context); }
@Test public void test() { LuaRulesDefinition rulesDefinition = new LuaRulesDefinition(); RulesDefinition.Context context = new RulesDefinition.Context(); rulesDefinition.define(context); RulesDefinition.Repository repository = context.repository("lua"); assertThat(repository.name()).isEqualTo("SonarQube"); assertThat(repository.language()).isEqualTo("lua"); assertThat(repository.rules()).hasSize(CheckList.getChecks().size()); for (RulesDefinition.Rule rule : repository.rules()) { for (RulesDefinition.Param param : rule.params()) { assertThat(param.description()).as("description for " + param.key() + " of " + rule.key()).isNotEmpty(); } } }
Lua extends AbstractLanguage { @Override public String[] getFileSuffixes() { String[] suffixes = filterEmptyStrings(settings.getStringArray(LuaPlugin.FILE_SUFFIXES_KEY)); if (suffixes.length == 0) { suffixes = StringUtils.split(DEFAULT_FILE_SUFFIXES, ","); } return suffixes; } Lua(Settings settings); @Override String[] getFileSuffixes(); static final String NAME; static final String KEY; static final String DEFAULT_FILE_SUFFIXES; }
@Test public void testGetFileSuffixes() { Settings settings = new Settings(); Lua lua = new Lua(settings); assertThat(lua.getFileSuffixes()).isEqualTo(new String[] {"lua"}); settings.setProperty(LuaPlugin.FILE_SUFFIXES_KEY, ""); assertThat(lua.getFileSuffixes()).isEqualTo(new String[] {"lua"}); settings.setProperty(LuaPlugin.FILE_SUFFIXES_KEY, "lua"); assertThat(lua.getFileSuffixes()).isEqualTo(new String[] {"lua"}); }
LuaPlugin implements Plugin { @Override public void define(Context context) { context.addExtensions( Lua.class, LuaSquidSensor.class, CoberturaSensor.class, LuaRulesDefinition.class, LuaProfile.class, PropertyDefinition.builder(FILE_SUFFIXES_KEY) .defaultValue(Lua.DEFAULT_FILE_SUFFIXES) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.") .onQualifiers(Qualifiers.MODULE, Qualifiers.PROJECT) .build(), PropertyDefinition.builder(COBERTURA_REPORT_PATH) .name("Cobertura xml report path") .description("Path to the Cobertura coverage report file. The path may be either absolute or relative to the project base directory.") .onQualifiers(Qualifiers.MODULE, Qualifiers.PROJECT) .build() ); } @Override void define(Context context); static final String FILE_SUFFIXES_KEY; static final String COBERTURA_REPORT_PATH; }
@Test public void testGetExtensions() throws Exception { Plugin.Context context = new Plugin.Context(Version.create(5, 6)); new LuaPlugin().define(context); assertThat(context.getExtensions()).isNotEmpty(); }
CoberturaReportParser { public static void parseReport(File xmlFile, final SensorContext context) { try { StaxParser parser = new StaxParser(rootCursor -> { rootCursor.advance(); collectPackageMeasures(rootCursor.descendantElementCursor("package"), context); }); parser.parse(xmlFile); } catch (XMLStreamException e) { throw new IllegalStateException(e); } } private CoberturaReportParser(); static void parseReport(File xmlFile, final SensorContext context); }
@Test(expected = IllegalStateException.class) public void invalidXmlFile() throws Exception { CoberturaReportParser.parseReport( TestUtils.getResource("org/sonar/plugins/lua/cobertura/coverage-invalid.xml"), SensorContextTester.create(new File(".")) ); }
SmartcarAuth { public AuthUrlBuilder authUrlBuilder() { return new AuthUrlBuilder(); } SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); SmartcarAuth(String clientId, String redirectUri, String[] scope, boolean testMode, SmartcarCallback callback); AuthUrlBuilder authUrlBuilder(); void addClickHandler(final Context context, final View view); void addClickHandler(final Context context, final View view, final String authUrl); void launchAuthFlow(final Context context); void launchAuthFlow(final Context context, final String authUrl); }
@Test public void smartcarAuth_authUrlBuilder() { String clientId = "client123"; String redirectUri = "scclient123: String redirectUriEncoded = "scclient123%3A%2F%2Ftest"; String[] scope = {"read_odometer", "read_vin"}; String expectedUri = "https: "&client_id=" + clientId + "&redirect_uri=" + redirectUriEncoded + "&mode=live&scope=read_odometer%20read_vin"; SmartcarAuth smartcarAuth = new SmartcarAuth(clientId, redirectUri, scope, null); String requestUri = smartcarAuth.authUrlBuilder().build(); assertEquals(expectedUri, requestUri); } @Test public void smartcarAuth_authUrlBuilder_testMode() { String clientId = "client123"; String redirectUri = "scclient123: String redirectUriEncoded = "scclient123%3A%2F%2Ftest"; String[] scope = {"read_odometer", "read_vin"}; String expectedUri = "https: "&client_id=" + clientId + "&redirect_uri=" + redirectUriEncoded + "&mode=test&scope=read_odometer%20read_vin"; SmartcarAuth smartcarAuth = new SmartcarAuth(clientId, redirectUri, scope, true, null); String requestUri = smartcarAuth.authUrlBuilder().build(); assertEquals(expectedUri, requestUri); } @Test public void smartcarAuth_authUrlBuilderWithSetters() { String clientId = "client123"; String redirectUri = "scclient123: String redirectUriEncoded = "scclient123%3A%2F%2Ftest"; String[] scope = {"read_odometer", "read_vin"}; String vin = "1234567890ABCDEFG"; String[] flags = {"flag:suboption", "feature3"}; String expectedUri = "https: "&client_id=" + clientId + "&redirect_uri=" + redirectUriEncoded + "&mode=live&scope=read_odometer%20read_vin" + "&approval_prompt=force&make=BMW&state=some%20state" + "&single_select=true" + "&single_select_vin=" + vin + "&flags=flag%3Asuboption%20feature3"; SmartcarAuth smartcarAuth = new SmartcarAuth(clientId, redirectUri, scope, null); String requestUri = smartcarAuth.authUrlBuilder() .setForcePrompt(true) .setMakeBypass("BMW") .setState("some state") .setSingleSelect(true) .setSingleSelectVin(vin) .setFlags(flags) .build(); assertEquals(expectedUri, requestUri); }
SmartcarAuth { protected static void receiveResponse(Uri uri) { if (uri != null && uri.toString().startsWith(redirectUri)) { String queryState = uri.getQueryParameter("state"); String queryErrorDescription = uri.getQueryParameter("error_description"); String queryCode = uri.getQueryParameter("code"); String queryError = uri.getQueryParameter("error"); String queryVin = uri.getQueryParameter("vin"); boolean receivedCode = queryCode != null; boolean receivedError = queryError != null && queryVin == null; boolean receivedErrorWithVehicle = queryError != null && queryVin != null; SmartcarResponse.Builder responseBuilder = new SmartcarResponse.Builder(); if (receivedCode) { SmartcarResponse smartcarResponse = responseBuilder .code(queryCode) .errorDescription(queryErrorDescription) .state(queryState) .build(); callback.handleResponse(smartcarResponse); } else if (receivedError) { SmartcarResponse smartcarResponse = responseBuilder .error(queryError) .errorDescription(queryErrorDescription) .state(queryState) .build(); callback.handleResponse(smartcarResponse); } else if (receivedErrorWithVehicle) { String make = uri.getQueryParameter("make"); String model = uri.getQueryParameter("model"); int year = Integer.parseInt(uri.getQueryParameter("year")); VehicleInfo responseVehicle = new VehicleInfo.Builder() .vin(queryVin) .make(make) .model(model) .year(year) .build(); SmartcarResponse smartcarResponse = responseBuilder .error(queryError) .errorDescription(queryErrorDescription) .state(queryState) .vehicleInfo(responseVehicle) .build(); callback.handleResponse(smartcarResponse); } else { SmartcarResponse smartcarResponse = responseBuilder .errorDescription("Unable to fetch code. Please try again") .state(queryState) .build(); callback.handleResponse(smartcarResponse); } } } SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); SmartcarAuth(String clientId, String redirectUri, String[] scope, boolean testMode, SmartcarCallback callback); AuthUrlBuilder authUrlBuilder(); void addClickHandler(final Context context, final View view); void addClickHandler(final Context context, final View view, final String authUrl); void launchAuthFlow(final Context context); void launchAuthFlow(final Context context, final String authUrl); }
@Test public void smartcarAuth_receiveResponse_vehicleIncompatible() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { assertEquals(smartcarResponse.getError(), "vehicle_incompatible"); assertEquals(smartcarResponse.getErrorDescription(), "The user's vehicle is not compatible."); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri + "?error=vehicle_incompatible&error_description=The%20user%27s%20vehicle%20is%20not%20compatible.")); } @Test public void smartcarAuth_receiveResponse_vehicleIncompatibleWithVehicle() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { VehicleInfo responseVehicle = smartcarResponse.getVehicleInfo(); assertEquals(smartcarResponse.getError(), "vehicle_incompatible"); assertEquals(smartcarResponse.getErrorDescription(), "The user's vehicle is not compatible."); assertEquals(responseVehicle.getVin(), "1FDKE30G4JHA04964"); assertEquals(responseVehicle.getMake(), "FORD"); assertEquals(responseVehicle.getModel(), "E-350"); assertEquals(responseVehicle.getYear(), new Integer(1988)); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri + "?error=vehicle_incompatible" + "&error_description=The%20user%27s%20vehicle%20is%20not%20compatible." + "&vin=1FDKE30G4JHA04964&make=FORD&model=E-350&year=1988")); } @Test public void smartcarAuth_receiveResponse_nullCodeWithMessage() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { assertEquals(smartcarResponse.getErrorDescription(), "Unable to fetch code. Please try again"); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri + "?error_description=error")); } @Test public void smartcarAuth_receiveResponse_codeWithState() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { assertEquals(smartcarResponse.getCode(), "testCode"); assertEquals(smartcarResponse.getState(), "testState"); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri + "?code=testCode&state=testState")); } @Test public void smartcarAuth_receiveResponse() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { assertEquals(smartcarResponse.getCode(), "testcode123"); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri + "?code=testcode123")); } @Test public void smartcarAuth_receiveResponse_mismatchRedirectUri() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; String wrongRedirectUri = "wrongscheme: new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { throw new AssertionError("Response should not be received."); } }); SmartcarAuth.receiveResponse(Uri.parse(wrongRedirectUri)); } @Test public void smartcarAuth_receiveResponse_nullUri() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { throw new AssertionError("Response should not be received."); } }); SmartcarAuth.receiveResponse(null); } @Test public void smartcarAuth_receiveResponse_nullCode() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { assertEquals(smartcarResponse.getErrorDescription(), "Unable to fetch code. Please try again"); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri)); } @Test public void smartcarAuth_receiveResponse_accessDenied() { String clientId = "client123"; String redirectUri = "scclient123: String[] scope = {"read_odometer", "read_vin"}; new SmartcarAuth(clientId, redirectUri, scope, new SmartcarCallback() { @Override public void handleResponse(SmartcarResponse smartcarResponse) { assertEquals(smartcarResponse.getError(), "access_denied"); assertEquals(smartcarResponse.getErrorDescription(), "User denied access to the requested scope of permissions."); } }); SmartcarAuth.receiveResponse(Uri.parse(redirectUri + "?error=access_denied&error_description=User%20denied%20access%20to%20the%20requested%20scope%20of%20permissions.")); }
SmartcarAuth { public void addClickHandler(final Context context, final View view) { addClickHandler(context, view, (new AuthUrlBuilder()).build()); } SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); SmartcarAuth(String clientId, String redirectUri, String[] scope, boolean testMode, SmartcarCallback callback); AuthUrlBuilder authUrlBuilder(); void addClickHandler(final Context context, final View view); void addClickHandler(final Context context, final View view, final String authUrl); void launchAuthFlow(final Context context); void launchAuthFlow(final Context context, final String authUrl); }
@Test public void smartcarAuth_addClickHandler() { Context context = mock(Context.class); View view = mock(View.class); SmartcarAuth smartcarAuth = new SmartcarAuth( "client123", "scclient123: new String[] {"read_odometer", "read_vin"}, null ); smartcarAuth.addClickHandler(context, view); verify(view, times(1)) .setOnClickListener(Mockito.any(View.OnClickListener.class)); }
SmartcarAuth { public void launchAuthFlow(final Context context) { launchAuthFlow(context, (new AuthUrlBuilder()).build()); } SmartcarAuth(String clientId, String redirectUri, String[] scope, SmartcarCallback callback); SmartcarAuth(String clientId, String redirectUri, String[] scope, boolean testMode, SmartcarCallback callback); AuthUrlBuilder authUrlBuilder(); void addClickHandler(final Context context, final View view); void addClickHandler(final Context context, final View view, final String authUrl); void launchAuthFlow(final Context context); void launchAuthFlow(final Context context, final String authUrl); }
@Test public void smartcarAuth_launchAuthFlow() { Context context = mock(Context.class); SmartcarAuth smartcarAuth = new SmartcarAuth( "client123", "scclient123: new String[] {"read_odometer", "read_vin"}, null ); smartcarAuth.launchAuthFlow(context); }
ApduSessionParameter implements Serializable { public byte[] getValueAsBytes() { return Hex.decode(value); } ApduSessionParameter(); ApduSessionParameter(String name, String value); ApduSessionParameter(String name, byte[] value); String getName(); @Override boolean equals(Object o); @Override int hashCode(); void setName(String name); String getValue(); void setValue(String value); byte[] getValueAsBytes(); void setValue(byte[] value); void setValue(byte[] value, int index, int length); @Override String toString(); }
@Test public void getValueAsBytes() { ApduSessionParameter parameter = new ApduSessionParameter(); parameter.setName("Test Parameter"); parameter.setValue("0102030405"); byte[] value = parameter.getValueAsBytes(); Assert.assertArrayEquals( new byte[]{1, 2, 3, 4, 5}, value); }
ApduEngineCli { public void go() { StatusResponse status = null; ApduSession session = new ApduSession(new GetVersion()); status = session.transmit(transmitter); byte[] piccDivData = session.getRequiredParameter(DesfireGetCardUID.CARD_UID_KEY).getValueAsBytes(); byte[] appDivData = Bytes.concat(piccDivData, new byte[] {(byte)0xFF, 0x54, 0x53}); session.nextCommands( new SelectPicc(), new GetKeySettings(), new DesfireAuth(DesfireUtils.cmacKeyDivAes128( piccDivData, new JceAesCryptor(Hex.decode("0F1E2D3C4B5A69788796A5B4C3D2E1F0"))), DesfireKeyType.AES_128), new ResetTo2K3DesKey() ); status = session.transmit(transmitter); session.nextCommands( new GetVersion(), new SelectPicc(), new DesfireAuth(new byte[24], DesfireKeyType.TWO_KEY_3DES), new ChangeKey(DesfireUtils.cmacKeyDivAes128( session.getRequiredParameter(DesfireGetCardUID.CARD_UID_KEY).getValueAsBytes(), new JceAesCryptor(Hex.decode("0F1E2D3C4B5A69788796A5B4C3D2E1F0")))), new DesfireAuth( DesfireUtils.cmacKeyDivAes128( piccDivData, new JceAesCryptor(Hex.decode("0F1E2D3C4B5A69788796A5B4C3D2E1F0"))), DesfireKeyType.AES_128), new ChangeKeySettings((byte) 0x0B), new FormatCard(), new CreateTsApplication(), new SelectTsApplication(), new DesfireAuth(new byte[16], DesfireKeyType.AES_128), new ChangeReadKey(DesfireUtils.cmacKeyDivAes128( appDivData, new JceAesCryptor(Hex.decode("00112233445566778899AABBCCDDEEFF")))), new ChangeWriteKey(DesfireUtils.cmacKeyDivAes128( appDivData, new JceAesCryptor(Hex.decode("FFEEDDCCBBAA99887766554433221100")))), new DesfireAuth( DesfireUtils.cmacKeyDivAes128( appDivData, new JceAesCryptor(Hex.decode("FFEEDDCCBBAA99887766554433221100"))), DesfireKeyType.AES_128), new CreateStdFile("0A08220625C0513DDF98".length()/2), new WriteData(Hex.decode("0A08220625C0513DDF98")), new ReadData() ); session.transmit(transmitter); } ApduEngineCli(ApduTransmitter transmitter); static void main(String[] ignored); void go(); StatusResponse andThen(ApduCommand... commands); void listApplications(ApduSession session, ApduTransmitter transmitter); StatusResponse authenticate(byte[] key); StatusResponse authenticate(); ApduSession getSession(); }
@Test @Ignore public void runApduEngineCliApp() { new ApduEngineCli( new MockTransmitter(DesfireKeyType.AES_128, new byte[16])).go(); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @PostConstruct public void init() { appFormerJsBridge.init("org.kie.bc.KIEWebapp"); homeConfiguration.setMonitoring(true); workbench.addStartupBlocker(KieWorkbenchEntryPoint.class); navigationExplorerScreen.getNavTreeEditor().setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH, 2); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }
@Test public void initTest() { kieWorkbenchEntryPoint.init(); verify(workbench).addStartupBlocker(KieWorkbenchEntryPoint.class); verify(navTreeEditor).setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH, 2); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override protected void initializeWorkbench() { permissionTreeSetup.configureTree(); super.initializeWorkbench(); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }
@Test public void testInitializeWorkbench() { kieWorkbenchEntryPoint.initializeWorkbench(); verify(permissionTreeSetup).configureTree(); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override public void setupMenu() { navigationManager.init(() -> { navTreeDefinitions.initialize(()->{ NavTree navTree = navTreeDefinitions.buildDefaultNavTree(); navigationManager.setDefaultNavTree(navTree); initMenuBar(); workbench.removeStartupBlocker(KieWorkbenchEntryPoint.class); }); }); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }
@Test public void setupMenuTest() { kieWorkbenchEntryPoint.setupMenu(); verify(menuBar).addMenus(any()); verify(menusHelper).addUtilitiesMenuItems(); verify(workbench).removeStartupBlocker(KieWorkbenchEntryPoint.class); } @Test public void defaultNavTreeTest() { kieWorkbenchEntryPoint.setupMenu(); NavTree navTree = navigationManager.getNavTree(); NavGroup workbench = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_WORKBENCH); NavGroup deploy = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_DEPLOY); NavItem execServers = navTree.getItemById(NavTreeDefinitions.ENTRY_EXECUTION_SERVERS); NavGroup manage = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_MANAGE); NavItem processDef = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_DEFINITIONS); NavItem processInst = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_INSTANCES); NavItem taskAdmin = navTree.getItemById(NavTreeDefinitions.ENTRY_ADMINISTRATION_TASKS); NavItem jobs = navTree.getItemById(NavTreeDefinitions.ENTRY_JOBS); NavItem executionErrors = navTree.getItemById(NavTreeDefinitions.ENTRY_EXECUTION_ERRORS); NavGroup track = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_TRACK); NavItem tasks = navTree.getItemById(NavTreeDefinitions.ENTRY_TASKS_LIST); NavItem processDashboard = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_DASHBOARD); NavItem taskDashboard = navTree.getItemById(NavTreeDefinitions.ENTRY_TASK_DASHBOARD); assertNotNull(workbench); assertNotNull(deploy); assertNotNull(manage); assertNotNull(track); assertEquals(deploy.getParent(), workbench); assertEquals(manage.getParent(), workbench); assertEquals(track.getParent(), workbench); assertNotNull(execServers); assertEquals(execServers.getParent(), deploy); assertNotNull(processDef); assertNotNull(processInst); assertNotNull(taskAdmin); assertNotNull(jobs); assertNotNull(executionErrors); assertEquals(processDef.getParent(), manage); assertEquals(processInst.getParent(), manage); assertEquals(taskAdmin.getParent(), manage); assertEquals(jobs.getParent(), manage); assertEquals(executionErrors.getParent(), manage); assertNotNull(tasks); assertNotNull(processDashboard); assertNotNull(taskDashboard); assertEquals(tasks.getParent(), track); assertEquals(processDashboard.getParent(), track); assertEquals(taskDashboard.getParent(), track); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override protected void setupAdminPage() { adminPageHelper.setup(false, true, false); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final AppFormerJsBridge appFormerJsBridge, final HomeConfiguration homeConfiguration); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); }
@Test public void testSetupAdminPage() { kieWorkbenchEntryPoint.setupAdminPage(); verify(adminPageHelper).setup(false, true, false); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @PostConstruct public void init() { appFormerJsBridge.init("org.kie.bc.KIEWebapp"); workbench.addStartupBlocker(KieWorkbenchEntryPoint.class); initNavTreeEditor(); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final ProfilePreferences profilePreferences, final Event<WorkbenchProfileCssClass> workbenchProfileCssClassEvent, final AppFormerJsBridge appFormerJsBridge); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); void refreshMenuOnProfilesChange(@Observes PreferenceUpdatedEvent event); }
@Test public void initTest() { kieWorkbenchEntryPoint.init(); verify(workbench).addStartupBlocker(KieWorkbenchEntryPoint.class); verify(navTreeEditor).setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH, 2); verify(navTreeEditor).setNewDividerEnabled(NavTreeDefinitions.GROUP_WORKBENCH, false); verify(navTreeEditor).setNewPerspectiveEnabled(NavTreeDefinitions.GROUP_WORKBENCH, false); verify(navTreeEditor).setOnlyRuntimePerspectives(NavTreeDefinitions.GROUP_WORKBENCH, false); verify(navTreeEditor).setPerspectiveContextEnabled(NavTreeDefinitions.GROUP_WORKBENCH, false); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override protected void initializeWorkbench() { permissionTreeSetup.configureTree(); super.initializeWorkbench(); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final ProfilePreferences profilePreferences, final Event<WorkbenchProfileCssClass> workbenchProfileCssClassEvent, final AppFormerJsBridge appFormerJsBridge); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); void refreshMenuOnProfilesChange(@Observes PreferenceUpdatedEvent event); }
@Test public void testInitializeWorkbench() { kieWorkbenchEntryPoint.initializeWorkbench(); verify(permissionTreeSetup).configureTree(); }
KieWorkbenchEntryPoint extends DefaultWorkbenchEntryPoint { @Override public void setupMenu() { navigationManager.init(() -> { NavTree navTree = navTreeDefinitions.buildDefaultNavTree(); navigationManager.setDefaultNavTree(navTree); initMenuBar(); workbench.removeStartupBlocker(KieWorkbenchEntryPoint.class); }); } @Inject KieWorkbenchEntryPoint(final Caller<AppConfigService> appConfigService, final ActivityBeansCache activityBeansCache, final DefaultWorkbenchFeaturesMenusHelper menusHelper, final ClientUserSystemManager userSystemManager, final WorkbenchMegaMenuPresenter menuBar, final Workbench workbench, final PermissionTreeSetup permissionTreeSetup, final DefaultAdminPageHelper adminPageHelper, final NavTreeDefinitions navTreeDefinitions, final NavigationManager navigationManager, final NavigationExplorerScreen navigationExplorerScreen, final DefaultWorkbenchErrorCallback defaultWorkbenchErrorCallback, final ProfilePreferences profilePreferences, final Event<WorkbenchProfileCssClass> workbenchProfileCssClassEvent, final AppFormerJsBridge appFormerJsBridge); @PostConstruct void init(); @Override void setupMenu(); void onNavTreeChanged(@Observes final NavTreeChangedEvent event); void onAuthzPolicyChanged(@Observes final SaveRoleEvent event); void onAuthzPolicyChanged(@Observes final SaveGroupEvent event); void refreshMenuOnProfilesChange(@Observes PreferenceUpdatedEvent event); }
@Test public void setupMenuTest() { kieWorkbenchEntryPoint.setupMenu(); verify(menuBar).addMenus(any()); verify(menusHelper).addUtilitiesMenuItems(); verify(workbench).removeStartupBlocker(KieWorkbenchEntryPoint.class); verify(workbenchProfileCssClassEvent).fire(any(WorkbenchProfileCssClass.class)); } @Test public void defaultNavTreeTest() { kieWorkbenchEntryPoint.setupMenu(); NavTree navTree = navigationManager.getNavTree(); NavGroup workbench = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_WORKBENCH); NavGroup design = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_DESIGN); NavItem projects = navTree.getItemById(NavTreeDefinitions.ENTRY_PROJECTS); NavItem pages = navTree.getItemById(NavTreeDefinitions.ENTRY_PAGES); NavGroup deploy = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_DEPLOY); NavItem execServers = navTree.getItemById(NavTreeDefinitions.ENTRY_EXECUTION_SERVERS); NavGroup manage = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_MANAGE); NavItem processDef = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_DEFINITIONS); NavItem processInst = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_INSTANCES); NavItem taskAdmin = navTree.getItemById(NavTreeDefinitions.ENTRY_ADMINISTRATION_TASKS); NavItem jobs = navTree.getItemById(NavTreeDefinitions.ENTRY_JOBS); NavItem executionErrors = navTree.getItemById(NavTreeDefinitions.ENTRY_EXECUTION_ERRORS); NavGroup track = (NavGroup) navTree.getItemById(NavTreeDefinitions.GROUP_TRACK); NavItem tasks = navTree.getItemById(NavTreeDefinitions.ENTRY_TASKS_LIST); NavItem processDashboard = navTree.getItemById(NavTreeDefinitions.ENTRY_PROCESS_DASHBOARD); NavItem taskDashboard = navTree.getItemById(NavTreeDefinitions.ENTRY_TASK_DASHBOARD); assertNotNull(workbench); assertNotNull(design); assertNotNull(deploy); assertNotNull(manage); assertNotNull(track); assertEquals(design.getParent(), workbench); assertEquals(deploy.getParent(), workbench); assertEquals(manage.getParent(), workbench); assertEquals(track.getParent(), workbench); assertNotNull(projects); assertNotNull(pages); assertEquals(projects.getParent(), design); assertEquals(pages.getParent(), design); assertNotNull(execServers); assertEquals(execServers.getParent(), deploy); assertNotNull(processDef); assertNotNull(processInst); assertNotNull(taskAdmin); assertNotNull(jobs); assertNotNull(executionErrors); assertEquals(processDef.getParent(), manage); assertEquals(processInst.getParent(), manage); assertEquals(taskAdmin.getParent(), manage); assertEquals(jobs.getParent(), manage); assertEquals(executionErrors.getParent(), manage); assertNotNull(tasks); assertNotNull(processDashboard); assertNotNull(taskDashboard); assertEquals(tasks.getParent(), track); assertEquals(processDashboard.getParent(), track); assertEquals(taskDashboard.getParent(), track); assertFalse(design.isModifiable()); assertFalse(pages.isModifiable()); }
AuthoringPerspective { @OnOpen public void onOpen() { placeManager.closeAllPlaces(); if (!projectPathString.isEmpty()) { vfsServices.call((RemoteCallback<Boolean>) isRegularFile -> { if (isRegularFile) { vfsServices.call((RemoteCallback<Path>) path -> { setWorkspaceContext(path, () -> placeManager.goTo(path)); }).get(projectPathString); } }).isRegularFile(projectPathString); } } @Inject AuthoringPerspective(final PlaceManager placeManager, final Caller<VFSService> vfsServices, final Event<WorkspaceProjectContextChangeEvent> workspaceProjectContextChangeEvent, final Caller<WorkspaceProjectService> workspaceProjectService, final ProjectController projectController, final Promises promises, final Event<NotificationEvent> notificationEvent); @PostConstruct void init(); @Perspective PerspectiveDefinition getPerspective(); @OnOpen void onOpen(); static final String IDENTIFIER; }
@Test public void onOpenTest() { final Path path = mock(Path.class); final WorkspaceProject workspaceProject = mock(WorkspaceProject.class); authoringPerspective.projectPathString = "git: doReturn(promises.resolve(true)).when(projectController).canReadBranch(workspaceProject); doReturn(true).when(vfsServices).isRegularFile(authoringPerspective.projectPathString); doReturn(path).when(vfsServices).get(authoringPerspective.projectPathString); doReturn(workspaceProject).when(workspaceProjectService).resolveProject(path); authoringPerspective.onOpen(); verify(placeManager).closeAllPlaces(); verify(workspaceProjectContextChangeEvent).fire(new WorkspaceProjectContextChangeEvent(workspaceProject)); verify(placeManager).goTo(same(path)); }
AreaController { @RequestMapping(value = "/get/{id}") public ActionResultObj get(@PathVariable Long id) { ActionResultObj result = new ActionResultObj(); try { if (id > 0) { EArea area = areaDao.fetch(id); if (area != null) { WMap map = new WMap(); map.put("data", area); result.ok(map); result.okMsg("查询成功!"); } else { result.errorMsg("查询失败!"); } } else { result.errorMsg("查询失败,链接不存在!"); } } catch (Exception e) { LOG.error("查询失败,原因:" + e.getMessage()); result.error(e); } return result; } @RequestMapping(value = "/list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value = "/allArea", method = RequestMethod.POST) ActionResultObj findAllArea(@RequestBody SearchQueryJS queryJs); @RequestMapping(value = "/save") ActionResultObj save(@RequestBody EArea area); @RequestMapping(value = "/get/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value = "/delete/{id}") ActionResultObj delete(@PathVariable Long id); @RequestMapping(value = "/kunMingArea") ActionResultObj getKunMingArea(); @Autowired public AreaService areaService; @Autowired public AreaDao areaDao; }
@Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/area/delete/2").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
MoneyUtil { public static Double getWeightedAverage(Map<Double, Long> amounts) { Double totalAmount = 0d; Long quantity = 0L; if (amounts != null && amounts.size() > 0) { for (Double money : amounts.keySet()) { Double amount = ArithUtils.mul(money, amounts.get(money).doubleValue()); totalAmount = ArithUtils.add(totalAmount, amount); quantity += amounts.get(money); } } return ArithUtils.div(totalAmount, quantity.doubleValue()); } static boolean equals(Double money1, Double money2); static Double fixPrice(Double price); static Double fixDiscount(Double discount); static Double getWeightedAverage(Map<Double, Long> amounts); static Double getWeightedAverage(Double money1, Long quantity1, Double money2, Long quantity2); static String formatMoney(Object money, int bit); static Long parseLong(Object number); static Double parseDouble(Object number); static String numberFormat(Object object, String format); }
@Test() public void testGetWeightedAverage1() { Double d1 = 150d; Double d2 = 149d; Long q1 = 0L; Long q2 = 1L; Double result = MoneyUtil.getWeightedAverage(d1, q1, d2, q2); assertEquals(149d, result.doubleValue(), 2); }
OrgController { @RequestMapping(value = "/get/{id}") public ActionResultObj get(@PathVariable Long id) { ActionResultObj result = new ActionResultObj(); try { if (id != 0) { EOrg org = orgDao.fetch(id); if (org != null) { WMap map = new WMap(); map.put("data", org); result.ok(map); result.okMsg("查询成功!"); } else { result.errorMsg("查询失败!"); } } else { result.errorMsg("查询失败,链接不存在!"); } } catch (Exception e) { LOG.error("查询失败,原因:" + e.getMessage()); result.error(e); } return result; } @RequestMapping(value = "/list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value = "/get/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value = "/save") ActionResultObj save(@RequestBody EOrg org); @RequestMapping(value = "/delete/{id}") ActionResultObj delete(@PathVariable Long id); @RequestMapping(value = "/getOrgs/{type}") ActionResultObj getOrgsByListByType(@PathVariable String type); @Autowired public OrgService orgService; @Autowired public OrgDao orgDao; @Autowired public AreaDao areaDao; }
@Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/org/3").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
DictController { @RequestMapping(value="/{id}") public ActionResultObj get(@PathVariable Long id){ ActionResultObj result = new ActionResultObj(); try{ if(id != 0){ EDict dict = dictDao.fetch(id); if(dict != null){ result.ok(dict); result.okMsg("查询成功!"); }else{ result.errorMsg("查询失败!"); } }else{ result.errorMsg("查询失败,链接不存在!"); } }catch(Exception e){ LOG.error("查询失败,原因:"+e.getMessage()); result.error(e); } return result; } @RequestMapping(value="list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value="type/{type}") ActionResultObj findByType(@PathVariable String type); @RequestMapping(value="/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value="save") ActionResultObj save(@RequestBody EDict dict); @RequestMapping(value="delete") ActionResultObj delete(@RequestBody Long id); @Autowired public DictService dictService; @Autowired public DictDao dictDao; }
@Test public void get() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/dict/3").accept(MediaType.APPLICATION_JSON)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
DictController { @RequestMapping(value="list") public ActionResultObj list(@RequestBody SearchQueryJS queryJs){ ActionResultObj result = new ActionResultObj(); try{ Pager pager = queryJs.toPager(); WMap query = queryJs.getQuery(); Criteria cnd = Cnd.cri(); if(query.get("type") != null && StringUtil.isNotBlank(query.get("type").toString())){ cnd.where().andEquals("type", query.get("type").toString()); } cnd.getGroupBy().groupBy("type"); cnd.getOrderBy().desc("sort"); List<EDict> projectList = dictDao.query(cnd, pager); WMap map = new WMap(); if(queryJs.getQuery() != null){ map.putAll(queryJs.getQuery()); } map.put("data", projectList); map.put("page", queryJs.toWPage(pager)); result.ok(map); result.okMsg("查询成功!"); }catch(Exception e){ e.printStackTrace(); LOG.error("查询失败,原因:"+e.getMessage()); result.error(e); } return result; } @RequestMapping(value="list") ActionResultObj list(@RequestBody SearchQueryJS queryJs); @RequestMapping(value="type/{type}") ActionResultObj findByType(@PathVariable String type); @RequestMapping(value="/{id}") ActionResultObj get(@PathVariable Long id); @RequestMapping(value="save") ActionResultObj save(@RequestBody EDict dict); @RequestMapping(value="delete") ActionResultObj delete(@RequestBody Long id); @Autowired public DictService dictService; @Autowired public DictDao dictDao; }
@Test public void list() throws Exception { SearchQueryJS queryJs = new SearchQueryJS(); WMap query = new WMap(); queryJs.setQuery(query); String json = mapper.writeValueAsString(queryJs); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/dict/type/unit").contentType(MediaType.APPLICATION_JSON).content(json)).andReturn(); int status = mvcResult.getResponse().getStatus(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(status + "--" + content); }
Gsm7BitCharset extends Charset { public CharsetEncoder newEncoder() { return new Gsm7BitEncoder(this); } protected Gsm7BitCharset(String canonical, String[] aliases); CharsetEncoder newEncoder(); CharsetDecoder newDecoder(); boolean contains(Charset cs); }
@Test public void testEncoderOverflow() { assertEquals(CoderResult.OVERFLOW, charset.newEncoder().encode(CharBuffer.wrap("00"), ByteBuffer.wrap(new byte[1]), true)); }
ByteBuffer extends SmppObject { public void appendShort(short data) { byte[] shortBuf = new byte[SZ_SHORT]; shortBuf[1] = (byte) (data & 0xff); shortBuf[0] = (byte) ((data >>> 8) & 0xff); appendBytes0(shortBuf, SZ_SHORT); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendShort0() { buffer.appendShort(t_short); assertBufferMatches((byte) 0x02, (byte) 0x9a); }
ByteBuffer extends SmppObject { public void appendInt(int data) { byte[] intBuf = new byte[SZ_INT]; intBuf[3] = (byte) (data & 0xff); intBuf[2] = (byte) ((data >>> 8) & 0xff); intBuf[1] = (byte) ((data >>> 16) & 0xff); intBuf[0] = (byte) ((data >>> 24) & 0xff); appendBytes0(intBuf, SZ_INT); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendInt0() { buffer.appendInt(666); assertBufferMatches(NULL, NULL, (byte) 0x02, (byte) 0x9a); }
ByteBuffer extends SmppObject { public void appendCString(String string) { try { appendString0(string, true, Data.ENC_ASCII); } catch (UnsupportedEncodingException e) { } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendCString0() { buffer.appendCString(ABC); assertBufferMatches(A, B, C, NULL); } @Test public void testAppendCStringWithNullAppendsNull() { buffer.appendCString(null); assertBufferMatches(NULL); } @Test public void testAppendCStringWithInvalidEncodingThrowsException() throws Exception { thrown.expect(UnsupportedEncodingException.class); buffer.appendCString(ABC, INVALID); }
ByteBuffer extends SmppObject { public void appendString(String string) { try { appendString(string, Data.ENC_ASCII); } catch (UnsupportedEncodingException e) { } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendString() { buffer.appendString(ABC); assertBufferMatches(A, B, C); } @Test public void testAppendStringWithCount() { buffer.appendString(ABC, 2); assertBufferMatches(A, B); } @Test public void testAppendStringWithZeroCount() { buffer = new ByteBuffer(new byte[] { }); buffer.appendString(ABC, 0); assertBufferMatches(new byte[] { }); } @Test public void testAppendStringWithExcessiveCountThrowsException() throws Exception { thrown.expect(StringIndexOutOfBoundsException.class); buffer.appendString(ABC, 4); } @Test public void testAppenStringWithCountAndInvalidEncodingThrowsException() throws Exception { thrown.expect(UnsupportedEncodingException.class); buffer.appendString(ABC, 1, INVALID); }
Gsm7BitCharset extends Charset { public CharsetDecoder newDecoder() { return new Gsm7BitDecoder(this); } protected Gsm7BitCharset(String canonical, String[] aliases); CharsetEncoder newEncoder(); CharsetDecoder newDecoder(); boolean contains(Charset cs); }
@Test public void testDecoderOverflow() { assertEquals(CoderResult.OVERFLOW, charset.newDecoder().decode(ByteBuffer.wrap(new byte[] { 0x30, 0x30 }), CharBuffer.allocate(1), true)); }
ByteBuffer extends SmppObject { public void appendBytes(ByteBuffer bytes, int count) throws NotEnoughDataInByteBufferException { if (count > 0) { if (bytes == null) { throw new NotEnoughDataInByteBufferException(0, count); } if (bytes.length() < count) { throw new NotEnoughDataInByteBufferException(bytes.length(), count); } appendBytes0(bytes.getBuffer(), count); } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendBytes() { buffer.appendBytes(new byte[] { A, B, C }); assertBufferMatches(A, B, C); } @Test public void testAppendBytesWithCountHonoursCount() { buffer.appendBytes(new byte[] { 0x01, 0x02, 0x03 }, 2); assertBufferMatches((byte) 0x01, (byte) 0x02); } @Test public void testAppendBytesWithExcessiveCountReducesCount() { buffer.appendBytes(new byte[] { t_bite }, 1234); assertBufferMatches(t_bite); } @Test public void testAppendByteBufferWithNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1234, 0)); buffer.appendBytes((ByteBuffer) null, 1234); } @Test public void testAppendByteBufferWithExcessiveCountThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(2, 1)); buffer.appendBytes(bufferOf(t_bite), 2); }
ByteBuffer extends SmppObject { public void appendBuffer(ByteBuffer buf) { if (buf != null) { try { appendBytes(buf, buf.length()); } catch (NotEnoughDataInByteBufferException e) { } } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendBufferWithNullDoesNothing() { buffer = bufferOf(NULL); buffer.appendBuffer(null); assertBufferMatches(NULL); } @Test public void testAppendBuferAppendsAll() { buffer.appendBuffer(bufferOf(A, B, C)); assertBufferMatches(A, B, C); }
ByteBuffer extends SmppObject { public ByteBuffer readBytes(int count) throws NotEnoughDataInByteBufferException { int len = length(); ByteBuffer result = null; if (count > 0) { if (len >= count) { byte[] resBuf = new byte[count]; System.arraycopy(buffer, 0, resBuf, 0, count); result = new ByteBuffer(resBuf); return result; } else { throw new NotEnoughDataInByteBufferException(len, count); } } else { return result; } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testReadBytesWithZeroCountReturnsNull() throws Exception { assertNull(buffer.readBytes(0)); } @Test public void testReadBytesWithExcessiveCountThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.readBytes(1); } @Test public void testRemoveBufferFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.readBytes(1); }
ByteBuffer extends SmppObject { public byte removeByte() throws NotEnoughDataInByteBufferException { byte result = 0; byte[] resBuff = removeBytes(SZ_BYTE).getBuffer(); result = resBuff[0]; return result; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testRemoveByteFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.removeByte(); } @Test public void testRemoveByteFromEmptyThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer = new ByteBuffer(new byte[] { }); buffer.removeByte(); } @Test public void testRemoveByteRemovesFirstByte() throws Exception { buffer = bufferOf(A, B, C); byte bite = buffer.removeByte(); assertEquals(A, bite); }
Gsm7BitCharsetProvider extends CharsetProvider { public Charset charsetForName (String charsetName) { if(charsetName.equalsIgnoreCase(CHARSET_NAME)) { return(gsm7Bit); } return(null); } Gsm7BitCharsetProvider(); Charset charsetForName(String charsetName); Iterator<Charset> charsets(); }
@Test public void testCharsetName() { Gsm7BitCharsetProvider provider = new Gsm7BitCharsetProvider(); Charset charset = provider.charsetForName("X-Gsm7Bit"); assertNotNull(charset); }
ByteBuffer extends SmppObject { public short removeShort() throws NotEnoughDataInByteBufferException { short result = 0; byte[] resBuff = removeBytes(SZ_SHORT).getBuffer(); result |= resBuff[0] & 0xff; result <<= 8; result |= resBuff[1] & 0xff; return result; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testRemoveShortFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(2, 0)); buffer.removeShort(); } @Test public void testRemoveShortFromSmallBufferThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(2, 1)); buffer = bufferOf(NULL); buffer.removeShort(); } @Test public void testRemoveShortRemovesFirstShort() throws Exception { buffer = bufferOf((byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04); short s = buffer.removeShort(); assertEquals((1 << 8) + 2, s); }
ByteBuffer extends SmppObject { public int readInt() throws NotEnoughDataInByteBufferException { int result = 0; int len = length(); if (len >= SZ_INT) { result |= buffer[0] & 0xff; result <<= 8; result |= buffer[1] & 0xff; result <<= 8; result |= buffer[2] & 0xff; result <<= 8; result |= buffer[3] & 0xff; return result; } else { throw new NotEnoughDataInByteBufferException(len, 4); } } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testReadIntFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(4, 0)); buffer.readInt(); } @Test public void testReadIntReadsFirstInt() throws Exception { buffer = bufferOf((byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08); int i = buffer.readInt(); assertEquals((1 << 24) + (2 << 16) + (3 << 8) + 4, i); } @Test public void testReadIntFromSmallBufferThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(4, 2)); buffer = bufferOf(NULL, NULL); buffer.readInt(); }
ByteBuffer extends SmppObject { public int removeInt() throws NotEnoughDataInByteBufferException { int result = readInt(); removeBytes0(SZ_INT); return result; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testRemoveIntFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(4, 0)); buffer.removeInt(); } @Test public void testRemoveIntFromSmallBufferThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(4, 2)); buffer = bufferOf(NULL, NULL); buffer.removeInt(); } @Test public void testRemoveIntReadsFirstInt() throws Exception { buffer = bufferOf((byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07, (byte) 0x08); int i = buffer.removeInt(); assertEquals((1 << 24) + (2 << 16) + (3 << 8) + 4, i); }
Queue extends SmppObject { public void enqueue(Object obj) throws IndexOutOfBoundsException { synchronized (mutex) { if ((maxQueueSize > 0) && (size() >= maxQueueSize)) { throw new IndexOutOfBoundsException("Queue is full. Element not added."); } queueData.add(obj); } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }
@Test public void testConstructorLimitsSize() throws IndexOutOfBoundsException { thrown.expect(IndexOutOfBoundsException.class); queue = new Queue(10); for (int i = 0; i < 11; i++) { queue.enqueue(new Object()); } }
ByteBuffer extends SmppObject { public String removeCString() throws NotEnoughDataInByteBufferException, TerminatingZeroNotFoundException { try { return removeCString(Data.ENC_ASCII); } catch (UnsupportedEncodingException e) { } return null; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testRemoveCStringFromNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.removeCString(); } @Test public void testRemoveCStringFromEmptyThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer = new ByteBuffer(new byte[] {}); buffer.removeCString(); } @Test public void testRemoveCStringWithSingleNonTerminatorThrowsException() throws Exception { thrown.expect(TerminatingZeroNotFoundException.class); buffer = bufferOf((byte) 0x01); buffer.removeCString(); } @Test public void testRemoveCStringWithMultipleNonTerminatorThrowsException() throws Exception { thrown.expect(TerminatingZeroNotFoundException.class); buffer = bufferOf((byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x01); buffer.removeCString(); } @Test public void testRemoveCStringRemovesFirstString() throws Exception { buffer = bufferOf(A, B, NULL, C, NULL); assertEquals("AB", buffer.removeCString()); } @Test public void testRemoveCStringRemovesWithDefaultEncoding() throws Exception { buffer = bufferOf(A, UNDERLINE, NULL); assertEquals("A_", buffer.removeCString()); } @Test public void testRemoveCStringRemovesWithASCIIEncoding() throws Exception { buffer = bufferOf(A, UNDERLINE, NULL); assertEquals("A_", buffer.removeCString(Data.ENC_ASCII)); }
ByteBuffer extends SmppObject { public String removeString(int size, String encoding) throws NotEnoughDataInByteBufferException, UnsupportedEncodingException { int len = length(); if (len < size) { throw new NotEnoughDataInByteBufferException(len, size); } UnsupportedEncodingException encodingException = null; String result = null; if (len > 0) { try { if (encoding != null) { result = new String(buffer, 0, size, encoding); } else { result = new String(buffer, 0, size); } } catch (UnsupportedEncodingException e) { debug.write("Unsupported encoding exception " + e); event.write(e, null); encodingException = e; } removeBytes0(size); } else { result = new String(""); } if (encodingException != null) { throw encodingException; } return result; } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testRemoveStringWithNullThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(1, 0)); buffer.removeString(1, ASCII); } @Test public void testRemoveStringZeroLength() throws Exception { assertEquals("", buffer.removeString(0, ASCII)); } @Test public void testRemoveStringWithInvalidEncodingThrowsException() throws Exception { thrown.expect(UnsupportedEncodingException.class); buffer = bufferOf(A, B, C); buffer.removeString(3, INVALID); } @Test public void testRemoveStringWithEncodingAscii() throws Exception { buffer = bufferOf(A, B, C); assertEquals(ABC, buffer.removeString(3, ASCII)); } @Test public void testRemoveStringWithNullEncoding() throws Exception { buffer = bufferOf(A, B, C); assertEquals(ABC, buffer.removeString(3, null)); }
Queue extends SmppObject { public boolean isEmpty() { synchronized (mutex) { return queueData.isEmpty(); } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }
@Test public void testIsEmpty() { assertTrue(queue.isEmpty()); queue.enqueue(new Object()); assertFalse(queue.isEmpty()); queue.dequeue(); assertTrue(queue.isEmpty()); }
ByteBuffer extends SmppObject { public ByteBuffer removeBuffer(int count) throws NotEnoughDataInByteBufferException { return removeBytes(count); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testRemoveBufferWithExcessiveSizeThrowsException() throws Exception { thrown.expect(NotEnoughDataInByteBufferException.class); thrown.expect(notEnoughData(10, 1)); buffer = bufferOf(NULL); buffer.removeBuffer(10); }
ByteBuffer extends SmppObject { public String getHexDump() { StringBuffer dump = new StringBuffer(); try { int dataLen = length(); byte[] buffer = getBuffer(); for (int i=0; i<dataLen; i++) { dump.append(Character.forDigit((buffer[i] >> 4) & 0x0f, 16)); dump.append(Character.forDigit(buffer[i] & 0x0f, 16)); } } catch (Throwable t) { dump = new StringBuffer("Throwable caught when dumping = ").append(t); } return dump.toString(); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testHexDump() { assertEquals("414243", bufferOf(A, B, C).getHexDump()); } @Test public void testHexDumpWithNullBuffer() { assertEquals("", buffer.getHexDump()); }
Unprocessed { public void reset() { hasUnprocessed = false; unprocessed.setBuffer(null); expected = 0; } void reset(); void check(); void setHasUnprocessed(boolean value); void setExpected(int value); void setLastTimeReceived(long value); void setLastTimeReceived(); ByteBuffer getUnprocessed(); boolean getHasUnprocessed(); int getExpected(); long getLastTimeReceived(); }
@Test public void testReset() { unprocessed.getUnprocessed().setBuffer(new byte[] { 0x00 }); unprocessed.setExpected(1); unprocessed.setHasUnprocessed(true); unprocessed.setLastTimeReceived(1); unprocessed.reset(); assertNull(unprocessed.getUnprocessed().getBuffer()); assertEquals(0, unprocessed.getExpected()); assertFalse(unprocessed.getHasUnprocessed()); assertEquals(1, unprocessed.getLastTimeReceived()); }
Unprocessed { public void setExpected(int value) { expected = value; } void reset(); void check(); void setHasUnprocessed(boolean value); void setExpected(int value); void setLastTimeReceived(long value); void setLastTimeReceived(); ByteBuffer getUnprocessed(); boolean getHasUnprocessed(); int getExpected(); long getLastTimeReceived(); }
@Test public void testSetExpected() { unprocessed.setExpected(1234); assertEquals(1234, unprocessed.getExpected()); }
DefaultEvent implements Event { public void write(String msg) { if (active) { System.out.println(msg); } } void write(String msg); void write(Exception e, String msg); void activate(); void deactivate(); }
@Test public void testInactiveByDefault() { event = new DefaultEvent(); event.write("HELLO"); assertEquals("", out.toString()); } @Test public void testWrite() { event.write("HELLO"); assertEquals("HELLO" + newLine, out.toString()); } @Test public void testWriteException() { try { throw new RuntimeException(); } catch (Exception ex) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ex.printStackTrace(new PrintStream(baos)); String expected = "Exception: " + baos.toString() + " END" + newLine; event.write(ex, "END"); assertEquals(expected, out.toString()); } }
Queue extends SmppObject { public int size() { synchronized (mutex) { return queueData.size(); } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }
@Test public void testSize() { int size = 0; assertEquals(size, queue.size()); for (int i = 0; i < 10; i++) { queue.enqueue(size++); assertEquals(size, queue.size()); } }
DefaultEvent implements Event { public void deactivate() { active = false; } void write(String msg); void write(Exception e, String msg); void activate(); void deactivate(); }
@Test public void testDeactivate() { event.deactivate(); event.write("HELLO"); assertEquals("", out.toString()); }
DefaultDebug implements Debug { public void enter(int group, Object from, String name) { enter(from, name); } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }
@Test public void testEnterWithName() { debug.enter(0, OBJECT, NAME); assertEquals("-> OBJECT NAME" + newLine, out.toString()); } @Test public void testEnterWithoutName() { debug.enter(0, OBJECT, EMPTY); assertEquals("-> OBJECT" + newLine, out.toString()); } @Test public void testNestedEnter() { debug.enter(OBJECT, NAME); debug.enter(OBJECT, NAME); assertEquals("-> OBJECT NAME" + newLine + " -> OBJECT NAME" + newLine, out.toString()); }
DefaultDebug implements Debug { public void exit(int group, Object from) { exit(from); } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }
@Test public void testExit() { debug.exit(0, OBJECT); assertEquals("<- OBJECT" + newLine, out.toString()); }
DefaultDebug implements Debug { public void write(int group, String msg) { write(msg); } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }
@Test public void testWrite() { debug.write(0, "HELLO"); assertEquals(" HELLO" + newLine, out.toString()); }
DefaultDebug implements Debug { public void deactivate() { active = false; } void enter(int group, Object from, String name); void enter(Object from, String name); void write(int group, String msg); void write(String msg); void exit(int group, Object from); void exit(Object from); void activate(); void activate(int group); void deactivate(); void deactivate(int group); boolean active(int group); }
@Test public void testDeactivate() { debug.deactivate(); debug.write(0, "HELLO"); assertEquals("", out.toString()); }
Address extends ByteData { public String getAddress() { return address; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test public void testConstructorStringSpecifiesAddress() throws Exception { assertEquals("1234", new Address("1234").getAddress()); }
Queue extends SmppObject { public Object find(Object obj) { synchronized (mutex) { Object current; ListIterator<Object> iter = queueData.listIterator(0); while (iter.hasNext()) { current = iter.next(); if (current.equals(obj)) { return current; } } } return null; } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }
@Test public void testFind() { Object a = new Object(); Object b = new Object(); Object c = new Object(); queue.enqueue(a); queue.enqueue(b); queue.enqueue(c); assertEquals(3, queue.size()); assertSame(a, queue.find(a)); assertSame(b, queue.find(b)); assertSame(c, queue.find(c)); assertEquals(3, queue.size()); }
Address extends ByteData { public Address() { this(Data.getDefaultTon(), Data.getDefaultNpi(), defaultMaxAddressLength); } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test(expected = WrongLengthOfStringException.class) public void testConstructorStringUsesDefaultMaxLength() throws Exception { new Address(address(21)); } @Test(expected = WrongLengthOfStringException.class) public void testConstructorStringIntSpecifiesAddressLength() throws Exception { new Address(address(5), 5); }
Address extends ByteData { public void setData(ByteBuffer buffer) throws NotEnoughDataInByteBufferException, TerminatingZeroNotFoundException, WrongLengthOfStringException { byte ton = buffer.removeByte(); byte npi = buffer.removeByte(); String address = buffer.removeCString(); setAddress(address); setTon(ton); setNpi(npi); } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test public void testSetData() throws Exception { ByteBuffer buffer = mock(ByteBuffer.class); when(buffer.removeByte()).thenReturn((byte) 0x01, (byte) 0x02); when(buffer.removeCString()).thenReturn("1234567890"); address.setData(buffer); assertEquals(0x01, address.getTon()); assertEquals(0x02, address.getNpi()); assertEquals("1234567890", address.getAddress()); }
Address extends ByteData { public ByteBuffer getData() { ByteBuffer addressBuf = new ByteBuffer(); addressBuf.appendByte(getTon()); addressBuf.appendByte(getNpi()); try { addressBuf.appendCString(getAddress(), Data.ENC_ASCII); } catch(UnsupportedEncodingException e) { } return addressBuf; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test public void testGetData() throws Exception { for (byte ton : TONS) { for (byte npi : NPIS) { for (int len = 1; len <= MAX_ADDRESS_LENGTH; len++) { String a = address(len); address = new Address(ton, npi, a, len + 1); ByteBuffer buffer = address.getData(); assertEquals(ton, buffer.removeByte()); assertEquals(npi, buffer.removeByte()); assertEquals(a, buffer.removeCString()); } } } }
Address extends ByteData { public void setTon(byte ton) { this.ton = ton; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test public void testSetTon() { for (byte ton : TONS) { address.setTon(ton); assertEquals(ton, address.getTon()); } }
Address extends ByteData { public void setNpi(byte npi) { this.npi = npi; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test public void testSetNpi() { for (byte npi : NPIS) { address.setNpi(npi); assertEquals(npi, address.getNpi()); } }
Address extends ByteData { public String debugString() { String dbgs = "(addr: "; dbgs += super.debugString(); dbgs += Integer.toString(getTon()); dbgs += " "; dbgs += Integer.toString(getNpi()); dbgs += " "; dbgs += getAddress(); dbgs += ") "; return dbgs; } Address(); Address(int maxAddressLength); Address(byte ton, byte npi, int maxAddressLength); Address(String address); Address(String address, int maxAddressLength); Address(byte ton, byte npi, String address); Address(byte ton, byte npi, String address, int maxAddressLength); void setData(ByteBuffer buffer); ByteBuffer getData(); void setTon(byte ton); void setNpi(byte npi); void setAddress(String address); void setAddress(String address, int maxAddressLength); byte getTon(); byte getNpi(); String getAddress(); String getAddress(String encoding); String debugString(); }
@Test public void testDebugString() throws Exception { for (byte ton : TONS) { for (byte npi : NPIS) { for (int len = 1; len <= MAX_ADDRESS_LENGTH; len++) { String a = address(len); address = new Address(ton, npi, a, len + 1); String s = "(addr: " + Integer.toString(ton) + " " + Integer.toString(npi) + " " + a + ") "; assertEquals(s, address.debugString()); } } } }
ByteData extends SmppObject { protected static void checkString(String string, int max) throws WrongLengthOfStringException { checkString(string, 0, max); } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }
@Test public void testCheckStringEqualZero() throws Exception { checkString("", 0); } @Test public void testCheckStringNonZero() throws Exception { checkString(" ", 1); } @Test public void testCheckStringOneZero() throws Exception { thrown.expect(stringLengthException(0, 0, 1)); checkString(" ", 0); } @Test public void testCheckStringUTF16() throws Exception { thrown.expect(stringLengthException(0, 1, 4)); checkString(" ", 1, "UTF-16"); } @Test public void testCheckStringInvalidEncoding() throws Exception { thrown.expect(UnsupportedEncodingException.class); checkString(" ", 1, "UTF-17"); }
Queue extends SmppObject { public Object dequeue() { synchronized (mutex) { Object first = null; if (size() > 0) { first = queueData.removeFirst(); } return first; } } Queue(); Queue(int maxSize); int size(); boolean isEmpty(); Object dequeue(); Object dequeue(Object obj); void enqueue(Object obj); Object find(Object obj); }
@Test public void testDequeueReturnsNullWhenEmpty() { assertNull(queue.dequeue()); }
ByteData extends SmppObject { protected static void checkCString(String string, int max) throws WrongLengthOfStringException { checkCString(string, 1, max); } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }
@Test public void testCheckCString() throws Exception { thrown.expect(stringLengthException(0, 0, 1)); invokeMethod(CLAZZ, "checkCString", (String) null, 0, 0); }
ByteData extends SmppObject { protected static void checkRange(int min, int val, int max) throws IntegerOutOfRangeException { if ((val < min) || (val > max)) { throw new IntegerOutOfRangeException(min, max, val); } } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }
@Test public void testCheckRange() throws Exception { checkRange(0, 0, 0); checkRange(0, 10, 100); } @Test public void testCheckRangeBelow() throws Exception { thrown.expect(integerOutOfRange(5, 10, 1)); checkRange(5, 1, 10); } @Test public void testCheckRangeAbove() throws Exception { thrown.expect(integerOutOfRange(5, 10, 11)); checkRange(5, 11, 10); }
ByteData extends SmppObject { protected static short decodeUnsigned(byte signed) { if (signed >= 0) { return signed; } else { return (short) (256 + (short) signed); } } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }
@Test public void testDecodeUnsignedByte() throws Exception { assertEquals(0, decodeUnsigned((byte) 0x00)); assertEquals(127, decodeUnsigned((byte) 0x7f)); assertEquals(255, decodeUnsigned((byte) 0xff)); } @Test public void testDecodeUnsignedShort() throws Exception { assertEquals(0, decodeUnsigned((short) 0)); assertEquals(32768, decodeUnsigned((short) 32768)); }
ByteData extends SmppObject { protected static byte encodeUnsigned(short positive) { if (positive < 128) { return (byte) positive; } else { return (byte) (- (256 - positive)); } } ByteData(); abstract void setData(ByteBuffer buffer); abstract ByteBuffer getData(); String debugString(); }
@Test public void testEncodeUnsignedShort() throws Exception { assertEquals((byte) 0x00, encodeUnsigned((short) 0)); assertEquals((byte) 0xff, encodeUnsigned((short) 255)); } @Test public void testEncodeUnsignedInt() throws Exception { assertEquals((short) 0, encodeUnsigned((int) 0)); assertEquals((short) 32768, encodeUnsigned((int) 32768)); }
ByteBuffer extends SmppObject { public void appendByte(byte data) { byte[] byteBuf = new byte[SZ_BYTE]; byteBuf[0] = data; appendBytes0(byteBuf, SZ_BYTE); } ByteBuffer(); ByteBuffer(byte[] buffer); byte[] getBuffer(); void setBuffer(byte[] buffer); int length(); void appendByte(byte data); void appendShort(short data); void appendInt(int data); void appendCString(String string); void appendCString(String string, String encoding); void appendString(String string); void appendString(String string, String encoding); void appendString(String string, int count); void appendString(String string, int count, String encoding); void appendBuffer(ByteBuffer buf); void appendBytes(ByteBuffer bytes, int count); void appendBytes(byte[] bytes, int count); void appendBytes(byte[] bytes); byte removeByte(); short removeUnsignedByte(); short removeShort(); int removeInt(); int readInt(); String removeCString(); String removeCString(String encoding); String removeString(int size, String encoding); ByteBuffer removeBuffer(int count); ByteBuffer removeBytes(int count); void removeBytes0(int count); ByteBuffer readBytes(int count); String getHexDump(); }
@Test public void testAppendByte0() { buffer.appendByte(t_bite); assertBufferMatches(t_bite); } @Test public void testAppendByte1() { buffer = new ByteBuffer(new byte[] {}); buffer.appendByte(t_bite); assertBufferMatches(t_bite); }
SmppObject { static public Debug getDebug() { return debug; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }
@Test public void testDefaultDebug() { assertEquals(DefaultDebug.class, SmppObject.getDebug().getClass()); }
SmppObject { static public Event getEvent() { return event; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }
@Test public void testDefaultEvent() { assertEquals(DefaultEvent.class, SmppObject.getEvent().getClass()); }
SmppObject { static public void setDebug(Debug dbg) { debug = dbg; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }
@Test public void testSetDebug() { Debug debug = mock(Debug.class); SmppObject.setDebug(debug); assertEquals(debug, SmppObject.getDebug()); }
SmppObject { static public void setEvent(Event evt) { event = evt; } static void setDebug(Debug dbg); static void setEvent(Event evt); static Debug getDebug(); static Event getEvent(); static final int DRXTX; static final int DRXTXD; static final int DRXTXD2; static final int DSESS; static final int DPDU; static final int DPDUD; static final int DCOM; static final int DCOMD; static final int DUTL; static final int DUTLD; }
@Test public void testSetEvent() { Event event = mock(Event.class); SmppObject.setEvent(event); assertEquals(event, SmppObject.getEvent()); }
Driver { public void processOne() throws DriverException, CloseException { Request request; try { request = this.reader.read(); } catch (CloseException ex) { throw ex; } catch (Exception ex) { final Response response = createFatalResponse(ex); try { this.writer.write(response); } catch (IOException ex2) { throw new DriverException("exception while writing fatal response", ex2); } return; } final Response response = this.processRequest(request); this.writer.setContent(request.content); try { this.writer.write(response); } catch (IOException ex) { throw new DriverException("exception writing response", ex); } } Driver(final RequestReader reader, final ResponseWriter writer); void run(); void processOne(); }
@Test public void process() throws DriverException, CloseException { final String input = "{\"content\":\"package foo;\"}\n{\"content\":\"package bar;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final Driver driver = new Driver(reader, writer); driver.processOne(); driver.processOne(); } @Test public void processError() throws DriverException, CloseException { final String input = "{\"content\":\"package\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final Driver driver = new Driver(reader, writer); driver.processOne(); assertThat(out.toString()).contains("\"status\":\"error\""); } @Test public void processInvalid() throws DriverException, CloseException { final String input = "garbage"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final Driver driver = new Driver(reader, writer); driver.processOne(); final String result = new String(out.toByteArray()); assertThat(result).contains("{\"status\":\"fatal\",\"errors\":[\""); assertThat(result).contains("Unrecognized token 'garbage'"); } @Test public void processComment() throws DriverException, CloseException { final String input = "{\"content\":\"class EOF_Test { public void method() {\\r\\n } }\"}"; final Driver driver = process(input); driver.processOne(); } @Test public void processStringLiteral() throws DriverException, IOException { final String input = "{\"content\":\"class String_Test { String s = \\\"b\\\\nc\\\\41\\\"; \\r\\n }\"}"; final Driver driver = process(input); driver.processOne(); String json = driver.writer.out.toString(); final ObjectNode node = new ObjectMapper().readValue(json, ObjectNode.class); JsonNode newNode = node.findPath("unescapedValue"); assertThat(newNode.isMissingNode()).isFalse(); assertThat(newNode.asText()).isEqualTo("b\nc!"); }
RequestReader { public Request read() throws IOException { final String line = this.reader.readLine(); if (line == null) { throw new CloseException("exception while reading line (null)"); } return mapper.readValue(line, Request.class); } RequestReader(final InputStream in); Request read(); }
@Test public void throwOnClosed() throws IOException { final InputStream in = new ByteArrayInputStream(new byte[]{}) { @Override public int read(byte[] var1) throws IOException { throw new IOException("closed"); } }; final RequestReader reader = new RequestReader(in); boolean thrown = false; try { reader.read(); } catch (IOException ex) { thrown = true; } assertThat(thrown).isTrue(); } @Test public void twoValid() throws IOException { final String input = "{\"content\":\"package foo;\"}\n{\"content\":\"package bar;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); Request request = reader.read(); Request expected = new Request(); expected.content = "package foo;"; assertThat(request.content).isEqualTo(expected.content); assertThat(request).isEqualTo(expected); request = reader.read(); expected = new Request(); expected.content = "package bar;"; assertThat(request.content).isEqualTo(expected.content); assertThat(request).isEqualTo(expected); } @Test public void oneMalformedOnValid() throws IOException { final String input = "foo\n{\"content\":\"package foo;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); boolean thrown = false; try { reader.read(); } catch (IOException ex) { thrown = true; } assertThat(thrown).isTrue(); Request request = reader.read(); Request expected = new Request(); expected.content = "package foo;"; assertThat(request.content).isEqualTo(expected.content); assertThat(request).isEqualTo(expected); }
Driver { public void run() throws DriverException, CloseException { while (true) { this.processOne(); } } Driver(final RequestReader reader, final ResponseWriter writer); void run(); void processOne(); }
@Test public void exitOnCloseIn() throws DriverException, CloseException { final String input = "{\"content\":\"package foo;\"}\n{\"content\":\"package bar;\"}\n"; final InputStream in = new ByteArrayInputStream(input.getBytes()); final RequestReader reader = new RequestReader(in); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final Driver driver = new Driver(reader, writer); try { driver.run(); } catch (CloseException ex) { } }
ResponseWriter { public void write(final Response response) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, response); out.write('\n'); this.out.write(out.toByteArray()); } ResponseWriter(final OutputStream out); void setContent(String content); void write(final Response response); }
@Test public void error() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); Response response; response = new Response(); response.status = "fatal"; response.errors = new ArrayList<>(); response.errors.add("error"); writer.write(response); final String result = new String(out.toByteArray()); final String expected = "{\"status\":\"fatal\",\"errors\":[\"error\"]}\n"; assertThat(result).isEqualTo(expected); } @Test public void valid() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ResponseWriter writer = new ResponseWriter(out); final EclipseParser parser = new EclipseParser(); Response response; final String source = IOUtils.toString( getClass().getResourceAsStream("/helloWorld.java"), StandardCharsets.UTF_8); response = new Response(); response.status = "ok"; response.ast = parser.parse(source); writer.write(response); }
EventController { @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody List<Event> event() { return repository.findAll(); } @Autowired EventController(EventRepository repository); @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody List<Event> event(); @RequestMapping(method = RequestMethod.GET, value = "", params = "name", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody Event eventByName(@RequestParam("name") String name); @RequestMapping(method = RequestMethod.GET, value = "", params = "privacy", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody List<Event> eventByPrivacy(@RequestParam("privacy") Boolean privacy); @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody Event insertData(ModelMap model, @ModelAttribute("insertEvent") @Valid Event event, BindingResult result); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteEvent(@PathVariable("id") long id); @ExceptionHandler(CustomException.class) ResponseEntity<ErrorResponse> exceptionHandler(Exception ex); }
@Test public void event() throws Exception { mockMvc.perform(get("/event")) .andExpect(status().isOk()) .andExpect( content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].name", is("Chess Tournament"))) .andExpect(jsonPath("$[0].location", is("Bursa"))) .andExpect(jsonPath("$[0].privacy", is(false))) .andExpect(jsonPath("$[1].name", is("Tennis Tournament"))) .andExpect(jsonPath("$[1].location", is("Ankara"))) .andExpect(jsonPath("$[1].privacy", is(true))); verify(repo, times(1)).findAll(); verifyNoMoreInteractions(repo); }
UserController { @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public @ResponseBody List<User> user() { return repository.findAll(); } @Autowired UserController(UserRepository repository); @RequestMapping(method = RequestMethod.GET, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userByUsername(@RequestParam("username") String username); @RequestMapping(method = RequestMethod.GET, value = "", params = "fullname", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userByFullname(@RequestParam("fullname") String fullname); @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User userById(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody List<User> user(); @RequestMapping(method = RequestMethod.PUT, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User update(@PathVariable("id") long id, @RequestParam MultiValueMap<String, String> params); @RequestMapping(method = RequestMethod.PUT, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User updateByUsername(@RequestParam MultiValueMap<String, String> params); @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody User insertData(@ModelAttribute("insertUser") @Valid User user, BindingResult result); @RequestMapping(method = RequestMethod.DELETE, value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteUserById(@PathVariable("id") long id); @RequestMapping(method = RequestMethod.DELETE, value = "", params = "username", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody ResponseEntity<Void> deleteUserByUsername(@RequestParam("username") String username); @ExceptionHandler(CustomException.class) ResponseEntity<ErrorResponse> exceptionHandler(CustomException ex); }
@Test public void user() throws Exception { mockMvc.perform(get("/user")) .andExpect(status().isOk()) .andExpect( content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].username", is("gokce"))) .andExpect(jsonPath("$[0].fullname", is("Gökçe Uludoğan"))) .andExpect(jsonPath("$[0].email", is("[email protected]"))) .andExpect(jsonPath("$[1].username", is("samed"))) .andExpect(jsonPath("$[1].fullname", is("Samed Düzçay"))) .andExpect(jsonPath("$[1].email", is("[email protected]"))); verify(repo, times(1)).findAll(); verifyNoMoreInteractions(repo); }