Dataset Viewer
Auto-converted to Parquet
id
stringlengths
8
11
source
stringlengths
164
3.08k
target
stringlengths
60
1.1k
781084_0
class WebHookSecurityInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return webHookAdapter.isValidRequest(request); } } class TestWebHookSecurityInterceptor { @Test public void testPreHandle() throws Exception {
MyTestWebHookAdapter adapter = new MyTestWebHookAdapter(); WebHookSecurityInterceptor interceptor = new WebHookSecurityInterceptor(); // set the adapter like spring would do. Field field = WebHookSecurityInterceptor.class.getDeclaredField("webHookAdapter"); field.setAccessible(true); field.set(interceptor, adapter); field.setAccessible(false); // call the interceptor. interceptor.preHandle(new MockHttpServletRequest(), new MockHttpServletResponse(), null); // all we have to check is if the adapter was called. assertTrue(adapter.wasCalled("isValidRequest")); } }
1552601_0
class FilePublicKeyProvider extends AbstractKeyPairProvider { public Iterable<KeyPair> loadKeys() { if (!SecurityUtils.isBouncyCastleRegistered()) { throw new IllegalStateException("BouncyCastle must be registered as a JCE provider"); } List<KeyPair> keys = new ArrayList<KeyPair>(); for (String file : files) { try { Object o = KeyPairUtils.readKey(new InputStreamReader(new FileInputStream(file))); if (o instanceof KeyPair) { keys.add(new KeyPair(((KeyPair)o).getPublic(), null)); } else if (o instanceof PublicKey) { keys.add(new KeyPair((PublicKey)o, null)); } else if (o instanceof PEMKeyPair) { PEMKeyPair keyPair = (PEMKeyPair)o; keys.add(convertPemKeyPair(keyPair)); } else if (o instanceof SubjectPublicKeyInfo) { PEMKeyPair keyPair = new PEMKeyPair((SubjectPublicKeyInfo) o, null); keys.add(convertPemKeyPair(keyPair)); } else { throw new UnsupportedOperationException(String.format("Key type %s not supported.", o.getClass().getName())); } } catch (Exception e) { LOG.info("Unable to read key {}: {}", file, e); } } return keys; } FilePublicKeyProvider(String[] files); private KeyPair convertPemKeyPair(PEMKeyPair pemKeyPair); } class FilePublicKeyProviderTest { @Test public void test() {
String pubKeyFile = Thread.currentThread().getContextClassLoader().getResource("test_authorized_key.pem").getFile(); assertTrue(new File(pubKeyFile).exists()); FilePublicKeyProvider SUT = new FilePublicKeyProvider(new String[]{pubKeyFile}); assertTrue(SUT.loadKeys().iterator().hasNext()); } }
1556938_0
class Erector { public BlueprintTemplate getTemplate() { return blueprintTemplate; } public Erector(); public Object createNewInstance(); public void addCommands(ModelField modelField, Set<Command> commands); public void addCommand( ModelField modelField, Command command ); public Set<Command> getCommands( ModelField modelField ); public void clearCommands(); public Object getBlueprint(); public void setBlueprint(Object blueprint); public Collection<ModelField> getModelFields(); public ModelField getModelField(String name); public void setModelFields(Collection<ModelField> modelFields); public void addModelField(ModelField modelField); public void setTemplate(BlueprintTemplate blueprintTemplate); public Class getTarget(); public void setTarget(Class target); public Object getReference(); public void setReference(Object reference); public Constructable getNewInstance(); public void setNewInstance(Constructable newInstance); public void setCallbacks(String type, List<Callback> callbacks); public List<Callback> getCallbacks(String type); public String toString(); public Erector erector; public DefaultField defaultField; public CarBlueprint carBlueprint; } class ErectorTest { public Erector erector; public DefaultField defaultField; public CarBlueprint carBlueprint; @Test public void testGet() throws BlueprintTemplateException {
Car car = new Car(); car.setMileage(new Float(123.456)); Float val = (Float) erector.getTemplate().get(car, "mileage"); assertEquals(new Float(123.456), val); } }
1644710_0
class RestBuilder { public Model buildModel(Iterable<NamedInputSupplier> suppliers) throws IOException { List<Model> models = Lists.newArrayList(); for (NamedInputSupplier supplier : suppliers) { Model model = buildModel(supplier); models.add(model); } return new MultiModel(models).resolve(); } public boolean isTracingEnabled(); public void setTracingEnabled(boolean tracingEnabled); private Model buildModel(NamedInputSupplier supplier); private Model model; } class RestBuilderTest { private Model model; @Test public void testBuildModel() throws Exception {
assertThat(model) .describedAs("A restbuilder model object") .isNotNull() .isInstanceOf(Model.class); assertThat(model.getNamespace()).isEqualTo("example"); assertThat(model.getOperations()).isNotEmpty().hasSize(2); Resource accountResource = model.getResources().get("account"); assertThat(accountResource.getPreamble()).isNotEmpty(); assertThat(accountResource.getComment()).isNotEmpty(); Operation cancellationOperation = accountResource.getOperations().get("cancellation"); assertThat(cancellationOperation.getAttributes()).isNotEmpty(); } }
2827764_0
class App { public String getMessage() { return message; } public App(); public App(String message); public static void main(String[] args); public void setMessage(String message); public void run(); protected void readMessageFromFile(String file); private static final Logger LOG; private App app; } class AppTest { private static final Logger LOG; private App app; @Test public void testDefaultMessage() {
String message = app.getMessage(); assertEquals("Hello, world!", message); LOG.debug(message); } }
18242149_0
class AsmApi { static int value() { return Opcodes.ASM7; } private AsmApi(); } class AsmApiTest { @Test public void testValue() {
assertEquals(Opcodes.ASM7, AsmApi.value()); } }
23330642_0
class Main extends MainSupport { @Override protected Map<String, CamelContext> getCamelContextMap() { BeanManager manager = container.getBeanManager(); return manager.getBeans(CamelContext.class, Any.Literal.INSTANCE).stream() .map(bean -> getReference(manager, CamelContext.class, bean)) .collect(toMap(CamelContext::getName, identity())); } public static void main(String... args); public static Main getInstance(); @Override protected ProducerTemplate findOrCreateCamelTemplate(); @Override protected void doStart(); private void warnIfNoCamelFound(); @Override protected void doStop(); } class MainTest { @Test public void testMainSupport() throws Exception {
Main main = new Main(); main.start(); assertThat("Camel contexts are not deployed!", main.getCamelContextMap(), allOf(hasKey("default"), hasKey("foo"))); CamelContext context = main.getCamelContextMap().get("default"); assertThat("Default Camel context is not started", context.getStatus(), is(equalTo(ServiceStatus.Started))); assertThat("Foo Camel context is not started", main.getCamelContextMap().get("foo").getStatus(), is(equalTo(ServiceStatus.Started))); MockEndpoint outbound = context.getEndpoint("mock:outbound", MockEndpoint.class); outbound.expectedMessageCount(1); outbound.expectedBodiesReceived("message"); ProducerTemplate producer = main.getCamelTemplate(); producer.sendBody("direct:inbound", "message"); MockEndpoint.assertIsSatisfied(2L, TimeUnit.SECONDS, outbound); main.stop(); } }
27062690_0
class XModifier { private void create(Node parent, XModifyNode node) throws XPathExpressionException { Node newNode; if (node.isAttributeModifier()) { //attribute createAttributeByXPath(parent, node.getCurNode().substring(1), node.getValue()); } else { //element if (node.isRootNode()) { //root node newNode = parent; boolean canMoveToNext = node.moveNext(); if (!canMoveToNext) { //last node newNode.setTextContent(node.getValue()); } else { //next node create(newNode, node); } } else if (node.getCurNode().equals("text()")) { parent.setTextContent(node.getValue()); } else { //element findOrCreateElement(parent, node); } } } public XModifier(Document document); public void setNamespace(String prefix, String url); public void addModify(String xPath, String value); public void addModify(String xPath); public void modify(); private void initXPath(); private void createAttributeByXPath(Node node, String current, String value); private void findOrCreateElement(Node parent, XModifyNode node); private Element createNewElement(String namespaceURI, String local, String[] conditions); } class XModifierTest { @Test public void create() throws ParserConfigurationException, IOException, SAXException {
Document document = createDocument(); Document documentExpected = readDocument("createExpected.xml"); XModifier modifier = new XModifier(document); modifier.setNamespace("ns", "http://localhost"); // create an empty element modifier.addModify("/ns:root/ns:element1"); // create an element with attribute modifier.addModify("/ns:root/ns:element2[@attr=1]"); // append an new element to existing element1 modifier.addModify("/ns:root/ns:element1/ns:element11"); // create an element with text modifier.addModify("/ns:root/ns:element3", "TEXT"); modifier.modify(); assertXmlEquals(documentExpected, document); } }
33403291_0
class MinecraftlyUtil { public static long convertMillisToTicks( long milliseconds ) { double nearestTickTime = round( milliseconds, 50 ); return (long) ((nearestTickTime / 1000) * 20); } public static UUID convertFromNoDashes( String uuidString ); public static String convertToNoDashes( UUID uuid ); public static String convertToNoDashes( String uuidString ); public static String downloadText( String url ); public static String downloadText( URL url ); public static String readText( String filePath ); public static String readText( File file ); public static double round( double value, double factor ); public static InetSocketAddress parseAddress( String address ); public static String getTimeString( long millis ); } class MinecraftlyUtilTest { @Test public void tickConversionTest() {
Assert.assertEquals( 1, MinecraftlyUtil.convertMillisToTicks( 40 ) ); Assert.assertEquals( 1, MinecraftlyUtil.convertMillisToTicks( 50 ) ); Assert.assertEquals( 1, MinecraftlyUtil.convertMillisToTicks( 60 ) ); Assert.assertEquals( 3, MinecraftlyUtil.convertMillisToTicks( 140 ) ); Assert.assertEquals( 3, MinecraftlyUtil.convertMillisToTicks( 150 ) ); Assert.assertEquals( 3, MinecraftlyUtil.convertMillisToTicks( 160 ) ); } }
49875177_0
class Primes { public final int compute() { long start = System.currentTimeMillis(); int cnt = 0; int prntCnt = 97; int res; for (;;) { res = next(); cnt += 1; if (cnt % prntCnt == 0) { log("Computed " + cnt + " primes in " + (System.currentTimeMillis() - start) + " ms. Last one is " + res); prntCnt *= 2; } if (cnt >= 100000) { break; } } return res; } protected Primes(); int next(); protected abstract void log(String msg); public static void main(String... args); } class PrimesTest { @Test public void fifthThousandThPrime() {
Primes p = new Primes() { @Override protected void log(String msg) { } }; int last = p.compute(); assertEquals("100000th prime is", 1_299_709, last); } }
59995075_0
class Step6GraphTransitivityCleaner { public static Set<Set<String>> mergeClusters(Set<Set<String>> equalClusters) { // create a new undirected graph Graph graph = new DefaultGraph("CC Test"); graph.setAutoCreate(true); graph.setStrict(false); // add all "edges"; for each pair from each cluster for (Set<String> cluster : equalClusters) { List<String> clusterList = new ArrayList<>(cluster); for (int i = 0; i < clusterList.size(); i++) { for (int j = i + 1; j < clusterList.size(); j++) { // edge name String iName = clusterList.get(i); String jName = clusterList.get(j); List<String> names = Arrays.asList(iName, jName); Collections.sort(names); String edgeName = StringUtils.join(names, "_"); graph.addEdge(edgeName, iName, jName); } } } // compute connected components ConnectedComponents cc = new ConnectedComponents(); cc.init(graph); Set<Set<String>> result = new HashSet<>(); cc.setCountAttribute("cluster"); cc.compute(); // System.out.println(cc.getConnectedComponentsCount()); // re-create clusters from all connected components for (ConnectedComponents.ConnectedComponent component : cc) { Set<String> cluster = new HashSet<>(); for (Node n : component) { cluster.add(n.getId()); } result.add(cluster); } // System.out.println(result); return result; } public Step6GraphTransitivityCleaner(ArgumentPairListSorter argumentPairListSorter, boolean removeEqualEdgesParam); public GraphCleaningResults processSingleFile(File file, File outputDir, String prefix, Boolean collectGeneratedArgumentPairs); public static Graph cleanCopyGraph(Graph graph); private static DescriptiveStatistics computeTransitivityScores(Graph graph); private static List<List<Object>> findCyclesInGraph(Graph graph); protected static Set<Set<String>> buildEquivalencyClusters( List<AnnotatedArgumentPair> argumentPairs); public static Graph buildGraphFromArgumentPairs(List<AnnotatedArgumentPair> argumentPairs); public static double computeEdgeWeight(AnnotatedArgumentPair annotatedArgumentPair, double lambda); @SuppressWarnings("unchecked") public static void collectResults(String[] args); @SuppressWarnings("unchecked") public static void printResultStatistics(File xmlFile); public static SortedMap<String, DescriptiveStatistics> collectStatisticsOverGraphCleaningResults( Collection<GraphCleaningResults> results); @SuppressWarnings("unchecked") public static void main(String[] args); } class Step6GraphTransitivityCleanerTest { @Test public void testMergeClusters() throws Exception {
Set<Set<String>> c1 = new HashSet<>(); c1.add(new HashSet<>(Arrays.asList("1", "2"))); c1.add(new HashSet<>(Arrays.asList("3", "4"))); Set<Set<String>> merged1 = Step6GraphTransitivityCleaner.mergeClusters(c1); assertEquals(2, merged1.size()); Set<Set<String>> c2 = new HashSet<>(); c2.add(new HashSet<>(Arrays.asList("1", "2"))); c2.add(new HashSet<>(Arrays.asList("3", "4"))); c2.add(new HashSet<>(Arrays.asList("5", "4"))); Set<Set<String>> merged2 = Step6GraphTransitivityCleaner.mergeClusters(c2); assertEquals(2, merged2.size()); Set<Set<String>> c3 = new HashSet<>(); c3.add(new HashSet<>(Arrays.asList("1", "5"))); c3.add(new HashSet<>(Arrays.asList("3", "4"))); c3.add(new HashSet<>(Arrays.asList("5", "4"))); Set<Set<String>> merged3 = Step6GraphTransitivityCleaner.mergeClusters(c3); assertEquals(1, merged3.size()); } }
78699707_0
class ReversedCharSequence extends ReverseIndexMapperBase implements ReverseCharSequence { @Override public ReversedCharSequence subSequence(int start, int end) { if (start < 0 || end > length()) throw new IndexOutOfBoundsException("[" + start + ", " + end + ") not in [0," + length() + "]"); final int startIndex = mapBoundary(end); final int endIndex = startIndex + end - start; return startIndex == myStartIndex && endIndex == myEndIndex ? this : new ReversedCharSequence(myChars, startIndex, endIndex); } @SuppressWarnings("WeakerAccess") private ReversedCharSequence(CharSequence chars, int start, int end); @Override public CharSequence getReversedChars(); public int getStartIndex(); @Override public IndexMapper getIndexMapper(); @Override public int getEndIndex(); @Override public int length(); @Override public char charAt(int index); @Override public String toString(); @Override public boolean equals(Object o); @Override public int hashCode(); public static ReversedCharSequence of(final CharSequence chars); public static ReversedCharSequence of(final CharSequence chars, final int start); public static ReversedCharSequence of(final CharSequence chars, final int start, final int end); } class ReversedCharSequenceTest { @Test public void subSequence() throws Exception {
CharSequence orig = "abcdef"; CharSequence reved = "fedcba"; ReversedCharSequence test = (ReversedCharSequence) ReversedCharSequence.of(orig); int iMax = orig.length(); for (int i = 0; i < iMax; i++) { for (int j = iMax - i - 1; j >= 0 && j >= i; j--) { assertEquals("subSequence(" + i + "," + j + ")", reved.subSequence(i, j), test.subSequence(i, j).toString()); assertEquals("reverse.of(subSequence(" + i + "," + j + "))", orig.subSequence(test.mapIndex(j) + 1, test.mapIndex(j) + 1 + j - i), ReversedCharSequence.of(test.subSequence(i, j)).toString()); assertEquals("subSequence(" + i + "," + j + ").hashCode()", reved.subSequence(i, j).hashCode(), test.subSequence(i, j).hashCode()); assertEquals("subSequence(" + i + "," + j + ").equals()", true, test.subSequence(i, j).equals(reved.subSequence(i, j))); } } } }
95789248_0
class TracingHandler implements Handler<RoutingContext> { public static SpanContext serverSpanContext(RoutingContext routingContext) { SpanContext serverContext = null; Object object = routingContext.get(CURRENT_SPAN); if (object instanceof Span) { Span span = (Span) object; serverContext = span.context(); } else { log.error("Sever SpanContext is null or not an instance of SpanContext"); } return serverContext; } public TracingHandler(Tracer tracer); public TracingHandler(Tracer tracer, List<WebSpanDecorator> decorators); @Override public void handle(RoutingContext routingContext); protected void handlerNormal(RoutingContext routingContext); protected void handlerFailure(RoutingContext routingContext); private Handler<Void> finishEndHandler(RoutingContext routingContext, Span span); protected MockTracer mockTracer; } class TracingHandlerTest { protected MockTracer mockTracer; @Test public void testLocalSpan() throws Exception {
{ router.route("/localSpan").handler(routingContext -> { SpanContext serverSpanContext = TracingHandler.serverSpanContext(routingContext); io.opentracing.Tracer.SpanBuilder spanBuilder = mockTracer.buildSpan("localSpan"); spanBuilder.asChildOf(serverSpanContext) .start() .finish(); routingContext.response() .setStatusCode(202) .end(); }); request("/localSpan", HttpMethod.GET, 202); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(2, mockSpans.size()); Assert.assertEquals(mockSpans.get(0).parentId(), mockSpans.get(1).context().spanId()); Assert.assertEquals(mockSpans.get(0).context().traceId(), mockSpans.get(1).context().traceId()); } }
106042361_0
class SPIDIntegrationUtil { public Element xmlStringToElement(String xmlData) throws SAXException, IOException, ParserConfigurationException { InputStream xmlByteArrayInputStream = new ByteArrayInputStream(xmlData.getBytes()); Element node = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlByteArrayInputStream).getDocumentElement(); return node; } public SPIDIntegrationUtil(); public String encodeAndPrintAuthnRequest(AuthnRequest authnRequest); public String printAuthnRequest(AuthnRequest authnRequest); public Credential getCredential(); public KeyStore getKeyStore(); public Signature getSignature(); @Autowired private SPIDIntegrationUtil spidIntegrationUtil; } class SPIDIntegrationUtilTest { @Autowired private SPIDIntegrationUtil spidIntegrationUtil; @Test public void xmlStringToXMLObjectTest() {
ClassLoader classLoader = getClass().getClassLoader(); File xmlFile = new File(classLoader.getResource("metadata/idp/telecom-metadata.xml").getFile()); try (Scanner scanner = new Scanner(xmlFile)) { String xmlData = scanner.useDelimiter("\\Z").next(); Element node = spidIntegrationUtil.xmlStringToElement(xmlData); Assert.assertEquals("md:EntityDescriptor", node.getNodeName()); } catch (SAXException | IOException | ParserConfigurationException e) { e.printStackTrace(); Assert.fail(); } } }
110417923_0
class CoffeeMachine { public Coffee brewCoffee(CoffeeSelection selection) throws CoffeeException { switch (selection) { case FILTER_COFFEE: return brewFilterCoffee(); case ESPRESSO: return brewEspresso(); default: throw new CoffeeException("CoffeeSelection ["+selection+"] not supported!"); } } public CoffeeMachine(Map<CoffeeSelection, CoffeeBean> beans); private Coffee brewEspresso(); private Coffee brewFilterCoffee(); } class TestCoffeeMachine { @Test public void testEspresso() throws CoffeeException {
// create a Map of available coffee beans Map<CoffeeSelection, CoffeeBean> beans = new HashMap<CoffeeSelection, CoffeeBean>(); beans.put(CoffeeSelection.ESPRESSO, new CoffeeBean("My favorite espresso bean", 1000)); beans.put(CoffeeSelection.FILTER_COFFEE, new CoffeeBean("My favorite filter coffee bean", 1000)); // get a new CoffeeMachine object CoffeeMachine machine = new CoffeeMachine(beans); // brew a fresh coffee Coffee espresso = machine.brewCoffee(CoffeeSelection.ESPRESSO); Assert.assertEquals(CoffeeSelection.ESPRESSO, espresso.getSelection()); Assert.assertEquals(28d, espresso.getQuantity(), 0.01); } }
144712336_0
class NacosConfigEndpoint implements ApplicationListener<NacosConfigMetadataEvent> { @ReadOperation public Map<String, Object> invoke() { Map<String, Object> result = new HashMap<>(8); if (!(ClassUtils.isAssignable(applicationContext.getEnvironment().getClass(), ConfigurableEnvironment.class))) { result.put("error", "environment type not match ConfigurableEnvironment: " + applicationContext.getEnvironment().getClass().getName()); } else { result.put("nacosConfigMetadata", nacosConfigMetadataMap.values()); result.put("nacosConfigGlobalProperties", PropertiesUtils.extractSafeProperties(applicationContext.getBean( CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class))); } return result; } @Override public void onApplicationEvent(NacosConfigMetadataEvent event); private String buildMetadataKey(NacosConfigMetadataEvent event); @Autowired private NacosConfigEndpoint nacosConfigEndpoint; } class NacosConfigEndpointTest { @Autowired private NacosConfigEndpoint nacosConfigEndpoint; @Test public void testInvoke() {
Map<String, Object> metadata = nacosConfigEndpoint.invoke(); Assert.assertNotNull(metadata.get("nacosConfigMetadata")); } }
159422409_0
class AsyncService { @Async public CompletableFuture<List<String>> completableFutureTask(String start) { logger.warn(Thread.currentThread().getName() + "start this task!"); // 找出所有以 F 开头的电影 List<String> results = movies.stream().filter(movie -> movie.startsWith(start)).collect(Collectors.toList()); // 模拟这是一个耗时的任务 try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } // 返回一个已经用给定值完成的新的CompletableFuture。 return CompletableFuture.completedFuture(results); } @Autowired AsyncService asyncService; } class AsyncServiceTest { @Autowired AsyncService asyncService; @Test public void testCompletableFutureTask() throws InterruptedException, ExecutionException {
// 开始时间 long start = System.currentTimeMillis(); // 开始执行大量的异步任务 List<String> words = Arrays.asList("F", "T", "S", "Z", "J", "C"); List<CompletableFuture<List<String>>> completableFutureList = words.stream() .map(word -> asyncService.completableFutureTask(word)) .collect(Collectors.toList()); // CompletableFuture.join()方法可以获取他们的结果并将结果连接起来 List<List<String>> results = completableFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList()); // 打印结果以及运行程序运行花费时间 System.out.println("Elapsed time: " + (System.currentTimeMillis() - start)); System.out.println(results.toString()); } }
171409385_0
class StockAPI { @GetMapping public ResponseEntity<List<Stock>> findAll() { return ResponseEntity.ok(stockService.findAll()); } @GetMapping("/{stockId}") public ResponseEntity<Stock> findById(@PathVariable Long stockId); @PostMapping public ResponseEntity create(@RequestBody Stock stock); @PatchMapping("/{stockId}") public ResponseEntity<Stock> update(@PathVariable Long stockId, @RequestBody Stock updatingStock); @DeleteMapping("/{id}") public ResponseEntity delete(@PathVariable Long id); @Autowired private MockMvc mockMvc; @MockBean private StockService stockService; } class StockAPITest { @Autowired private MockMvc mockMvc; @MockBean private StockService stockService; @Test public void findAll() throws Exception {
// given Stock stock = new Stock(); stock.setId(1L); stock.setName("Stock 1"); stock.setPrice(new BigDecimal(1)); List<Stock> stocks = Arrays.asList(stock); given(stockService.findAll()).willReturn(stocks); // when + then this.mockMvc.perform(get("/api/v1/stocks")) .andExpect(status().isOk()) .andExpect(content().json("[{'id': 1,'name': 'Stock 1';'price': 1}]")); } }
188574042_0
class AsgardBundle { public String getBundleName() { return bundleName; } public AsgardBundle(BundleConfiguration bundleConfiguration, ClassLoader parentClassLoader); public synchronized void init(); public Class<?> getSharedClass(String classFullName); public BundleService getBundleService(); public AsgardClassLoader getBundleClassLoader(); private void initBundleClassLoader(); private URL[] buildClassPathUrls(String extractPath); private void bundleCustomRun(); private void loadConfigure(String extractPath); private void loadBundleExportClasses(AsgardClassLoader bundleClassLoader); private void unpackBundleZip(File bundleFile); public static final String BUNDLE_TEST_PATH; } class AsgardBundleTest { public static final String BUNDLE_TEST_PATH; @Test public void test_INIT_bundle() throws Exception {
String bundleFileName = "/sample-auth-bundle1-2048-SNAPSHOT-release.zip"; URL url = AsgardBundleTest.class.getResource(bundleFileName); String moduleName = StringUtils.substringBeforeLast("sample-auth-bundle1-2048-SNAPSHOT-release.zip", ".zip"); String bundleExtractPath = BUNDLE_TEST_PATH + moduleName + "/"; AsgardBundle asgardBundle = initBundle(url.getFile()).getBundle(); assertThat(asgardBundle.getBundleName()).isEqualTo("sample-auth-bundle1-2048-SNAPSHOT-release"); File extractPath = new File(bundleExtractPath); assertThat(extractPath.exists()).isTrue(); File bundleClassPath = new File(bundleExtractPath + "BUNDLE-CLASS"); assertThat(bundleClassPath.exists() && bundleClassPath.isDirectory()).isTrue(); File bundleJarPath = new File(bundleExtractPath + "lib"); assertThat(bundleJarPath.exists() && bundleJarPath.isDirectory()).isTrue(); File metaInfPath = new File(bundleExtractPath + "META-INF"); assertThat(metaInfPath.exists() && metaInfPath.isDirectory()).isTrue(); } }
196205406_0
class MyService { public String message(){ return "this is module for helloworld.service method message"; } @Autowired private MyService myService; } class MyServiceTest { @Autowired private MyService myService; @Test public void contextLoads(){
assertThat(myService.message()).isNotNull(); } }
255292250_0
class Account { public BigDecimal balance() { return activities.stream() .map(AccountActivity::getAmount) .reduce(initialBalance, BigDecimal::add); } public Account(String number, BigDecimal initialBalance); public String getNumber(); public List<AccountActivity> getActivities(); public void recharge(Recharge recharge); public boolean consume(BigDecimal value); private boolean hasEnoughBalance(BigDecimal value); } class AccountTest { @Test public void should_return_zero_no_recharge() {
Account account = new Account("1", BigDecimal.ZERO); assertEquals(BigDecimal.ZERO, account.balance()); } }
README.md exists but content is empty.
Downloads last month
257