auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void locateFileFromResource(String res) { CDebugUtils.FileParts missingFileParts = CDebugUtils.getFileParts(missingFile); if (res != null) { CDebugUtils.FileParts resParts = CDebugUtils.getFileParts(res); if (resParts.getFileName().toLowerCase().equals(missingFileParts.getFileName().toLowerCase())) { String compPath = missingFileParts.getFolder(); IPath newSourcePath = new Path(resParts.getFolder()); if (compPath.length() > 0) { try { if (isDebugElement) addSourceMappingToLaunch(compPath, newSourcePath); else addSourceMappingToCommon(compPath, newSourcePath); } catch (CoreException e) { } } IWorkbenchPage page = getEditorSite().getPage(); if (isDebugElement) { ISourceDisplay adapter = context.getAdapter(ISourceDisplay.class); if (adapter != null) { adapter.displaySource(context, page, true); } } else if (isTranslationUnit) { reopenTranslationUnit(tunit); } closeEditor(); } } }

Target:
protected void locateFileFromResource(String res) { if (res == null){ throw new NullPointerException("Tried to initialize 'null' resource"); } CDebugUtils.FileParts missingFileParts = CDebugUtils.getFileParts(missingFile); CDebugUtils.FileParts resParts = CDebugUtils.getFileParts(res); if (resParts.getFileName().toLowerCase().equals(missingFileParts.getFileName().toLowerCase())) { String compPath = missingFileParts.getFolder(); IPath newSourcePath = new Path(resParts.getFolder()); if (compPath.length() > 0) { try { if (isDebugElement) addSourceMappingToLaunch(compPath, newSourcePath); else addSourceMappingToCommon(compPath, newSourcePath); } catch (CoreException e) { } } IWorkbenchPage page = getEditorSite().getPage(); if (isDebugElement) { ISourceDisplay adapter = context.getAdapter(ISourceDisplay.class); if (adapter != null) { adapter.displaySource(context, page, true); } } else if (isTranslationUnit) { reopenTranslationUnit(tunit); } closeEditor(); } }
Source:
public String stopAllJobExecutions( @CliOption(key = "force", help = "bypass confirmation prompt", unspecifiedDefaultValue = "false", specifiedDefaultValue = "true") boolean force) { jobOperations().stopAllJobExecutions(); return String.format("Stopped all the job executions"); }

Target:
public String stopAllJobExecutions( @CliOption(key = "force", help = "bypass confirmation prompt", unspecifiedDefaultValue = "false", specifiedDefaultValue = "true") boolean force) { if (force || "y".equalsIgnoreCase(userInput.prompt("Really stop all job executions?", "n", "y", "n"))) { jobOperations().stopAllJobExecutions(); return String.format("Stopped all the job executions"); } else { return ""; } }
Source:
protected boolean set(EntityShulker container, DyeColor value) { if (!(container instanceof IMixinShulker)) return false; ((IMixinShulker) container).setColor(value); return true; }

Target:
protected boolean set(EntityShulker container, DyeColor value) { ((IMixinShulker) container).setColor(value); return true; }
Source:
public CoordinatorStats run( DruidCoordinator coordinator, DruidCoordinatorRuntimeParams params, DataSegment segment ) { final Set<ServerHolder> loadServerHolders = new HashSet<>(); final Set<ServerHolder> dropServerHolders = new HashSet<>(); final List<String> colocatedDataSources = getColocatedDataSources(); if (colocatedDataSources == null || colocatedDataSources.isEmpty()) { loadServerHolders.addAll(params.getDruidCluster().getAllServers()); } else { params.getDruidCluster().getAllServers().forEach( eachHolder -> { if (colocatedDataSources.stream() .anyMatch(source -> eachHolder.getServer().getDataSource(source) != null && !eachHolder.isMaintenance())) { loadServerHolders.add(eachHolder); } else if (eachHolder.isServingSegment(segment)) { if (!eachHolder.getPeon().getSegmentsToDrop().contains(segment)) { dropServerHolders.add(eachHolder); } } } ); } final CoordinatorStats stats = new CoordinatorStats(); return stats.accumulate(assign(loadServerHolders, segment)) .accumulate(drop(dropServerHolders, segment)); }

Target:
public CoordinatorStats run(DruidCoordinator coordinator, DruidCoordinatorRuntimeParams params, DataSegment segment) { final Set<ServerHolder> loadServerHolders = new HashSet<>(); final Set<ServerHolder> dropServerHolders = new HashSet<>(); final List<String> colocatedDataSources = getColocatedDataSources(); if (colocatedDataSources == null || colocatedDataSources.isEmpty()) { loadServerHolders.addAll(params.getDruidCluster().getAllServers()); } else { params.getDruidCluster().getAllServers().forEach( eachHolder -> { if (!eachHolder.isInMaintenance() && colocatedDataSources.stream() .anyMatch(source -> eachHolder.getServer().getDataSource(source) != null)) { loadServerHolders.add(eachHolder); } else if (eachHolder.isServingSegment(segment)) { if (!eachHolder.getPeon().getSegmentsToDrop().contains(segment)) { dropServerHolders.add(eachHolder); } } } ); } final CoordinatorStats stats = new CoordinatorStats(); return stats.accumulate(assign(loadServerHolders, segment)) .accumulate(drop(dropServerHolders, segment)); }
Source:
public void testSeekForRwServer() throws Exception { Layout layout = org.apache.log4j.Logger.getRootLogger().getAppender("CONSOLE") .getLayout(); ByteArrayOutputStream os = new ByteArrayOutputStream(); WriterAppender appender = new WriterAppender(layout, os); appender.setImmediateFlush(true); appender.setThreshold(Level.INFO); org.apache.log4j.Logger zlogger = org.apache.log4j.Logger.getLogger("org.apache.zookeeper"); zlogger.addAppender(appender); try { qu.shutdown(2); CountdownWatcher watcher = new CountdownWatcher(); ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true); watcher.waitForConnected(CONNECTION_TIMEOUT); qu.getPeer(1).peer.suspend(); watcher.reset(); qu.start(2); qu.start(3); ClientBase.waitForServerUp(qu.getConnString(), 2000); watcher.waitForConnected(CONNECTION_TIMEOUT); zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); qu.getPeer(1).peer.resume(); } finally { zlogger.removeAppender(appender); } os.close(); LineNumberReader r = new LineNumberReader(new StringReader(os .toString())); String line; Pattern p = Pattern.compile(".*Majority server found.*"); boolean found = false; while ((line = r.readLine()) != null) { if (p.matcher(line).matches()) { found = true; break; } } Assert.assertTrue( "Majority server wasn't found while connected to r/o server", found); }

Target:
public void testSeekForRwServer() throws Exception { Layout layout = Logger.getRootLogger().getAppender("CONSOLE") .getLayout(); ByteArrayOutputStream os = new ByteArrayOutputStream(); WriterAppender appender = new WriterAppender(layout, os); appender.setImmediateFlush(true); appender.setThreshold(Level.INFO); Logger zlogger = Logger.getLogger("org.apache.zookeeper"); zlogger.addAppender(appender); try { qu.shutdown(2); CountdownWatcher watcher = new CountdownWatcher(); ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true); watcher.waitForConnected(CONNECTION_TIMEOUT); qu.getPeer(1).peer.suspend(); watcher.reset(); qu.start(2); qu.start(3); ClientBase.waitForServerUp(qu.getConnString(), 2000); watcher.waitForConnected(CONNECTION_TIMEOUT); zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); qu.getPeer(1).peer.resume(); } finally { zlogger.removeAppender(appender); } os.close(); LineNumberReader r = new LineNumberReader(new StringReader(os .toString())); String line; Pattern p = Pattern.compile(".*Majority server found.*"); boolean found = false; while ((line = r.readLine()) != null) { if (p.matcher(line).matches()) { found = true; break; } } Assert.assertTrue( "Majority server wasn't found while connected to r/o server", found); }
Source:
public void testPutAndDeleteSynonymCatalog() throws Exception { final SynonymCatalogModel dictionaryModel = new SynonymCatalogModel("synonymCatalog", Collections.singletonList(new SynonymModel("foo", Arrays.asList("bar", "baz"))), true); final MvcResult mvcResult = _mockMvc.perform( put("/test/referencedata/synonymCatalog/testCatalog").contentType(MediaType.APPLICATION_JSON) .content(_objectMapper.writeValueAsString(dictionaryModel))).andExpect(status().isCreated()) .andExpect(header().string("Location", is("http://localhost/test/referencedata/synonymCatalog/testCatalog"))).andReturn(); final String location = mvcResult.getResponse().getHeader("Location"); _mockMvc.perform(get(location)).andExpect(status().isOk()).andExpect(jsonPath("$.name", is("testCatalog"))) .andExpect(jsonPath("$.entries", hasSize(1))).andExpect(jsonPath("$.entries[0].masterTerm", is("foo"))) .andExpect(jsonPath("$.entries[0].synonyms", hasSize(2))) .andExpect(jsonPath("$.entries[0].synonyms[1]", is("baz"))) .andExpect(jsonPath("$.caseSensitive", is(true))); _mockMvc.perform(delete(location)).andExpect(status().isNoContent()); _mockMvc.perform(get(location)).andExpect(status().isNotFound()); }

Target:
public void testPutAndDeleteSynonymCatalog() throws Exception { final SynonymCatalogModel synonymCatalogModel = new SynonymCatalogModel("synonymCatalog", Collections.singletonList(new SynonymModel("foo", Arrays.asList("bar", "baz"))), true); final MvcResult mvcResult = _mockMvc.perform( put("/test/referencedata/synonymCatalog/testCatalog").contentType(MediaType.APPLICATION_JSON) .content(_objectMapper.writeValueAsString(synonymCatalogModel))).andExpect(status().isCreated()) .andExpect(header().string("Location", is("http://localhost/test/referencedata/synonymCatalog/testCatalog"))).andReturn(); final String location = mvcResult.getResponse().getHeader("Location"); _mockMvc.perform(get(location)).andExpect(status().isOk()).andExpect(jsonPath("$.name", is("testCatalog"))) .andExpect(jsonPath("$.entries", hasSize(1))).andExpect(jsonPath("$.entries[0].masterTerm", is("foo"))) .andExpect(jsonPath("$.entries[0].synonyms", hasSize(2))) .andExpect(jsonPath("$.entries[0].synonyms[1]", is("baz"))) .andExpect(jsonPath("$.caseSensitive", is(true))); _mockMvc.perform(delete(location)).andExpect(status().isNoContent()); _mockMvc.perform(get(location)).andExpect(status().isNotFound()); }
Source:
public void testGetNotifications() { Notification expired = testNotification(); Notification current = anotherTestNotification(); curationApiAdmin.createNotification(expired); curationApiAdmin.createNotification(current); List<Notification> activeNotifications = curationApiUser.getActiveNotifications(); assertEquals(activeNotifications.size(), 1); assertEquals(activeNotifications.get(0).getMessage(), "ayy"); }

Target:
public void testGetNotifications() { Notification expired = testNotification(); Notification current = anotherTestNotification(); curationApiAdmin.createNotification(expired); curationApiAdmin.createNotification(current); List<Notification> activeNotifications = curationApiUser.getActiveNotifications(); assertEquals(1, activeNotifications.size()); assertEquals("ayy", activeNotifications.get(0).getMessage()); }
Source:
@Test public void testFilterTimestamp() { String sql = "select count(*) as c\n" + "from \"foodmart\"\n" + "where extract(year from \"timestamp\") = 1997\n" + "and extract(month from \"timestamp\") in (4, 6)\n"; final String explain = "EnumerableInterpreter\n" + " BindableAggregate(group=[{}], C=[COUNT()])\n" + " BindableFilter(condition=[AND(>=(/INT(Reinterpret($0), 86400000), 1997-01-01), <(/INT(Reinterpret($0), 86400000), 1998-01-01), OR(AND(>=(/INT(Reinterpret($0), 86400000), 1997-04-01), <(/INT(Reinterpret($0), 86400000), 1997-05-01)), AND(>=(/INT(Reinterpret($0), 86400000), 1997-06-01), <(/INT(Reinterpret($0), 86400000), 1997-07-01))))])\n" + " DruidQuery(table=[[foodmart, foodmart]], intervals=[[1900-01-09T00:00:00.000/2992-01-10T00:00:00.000]], projects=[[$0]])"; sql(sql) .returnsUnordered("C=13500"); }

Target:
@Test public void testFilterTimestamp() { String sql = "select count(*) as c\n" + "from \"foodmart\"\n" + "where extract(year from \"timestamp\") = 1997\n" + "and extract(month from \"timestamp\") in (4, 6)\n"; final String explain = "PLAN=EnumerableInterpreter\n" + " DruidQuery(table=[[foodmart, foodmart]], " + "intervals=[[1900-01-09T00:00:00.000/2992-01-10T00:00:00.000]], filter=[AND(=" + "(EXTRACT_DATE(FLAG(YEAR), /INT(Reinterpret($0), 86400000)), 1997), OR(=(EXTRACT_DATE" + "(FLAG(MONTH), /INT(Reinterpret($0), 86400000)), 4), =(EXTRACT_DATE(FLAG(MONTH), /INT" + "(Reinterpret($0), 86400000)), 6)))], groups=[{}], aggs=[[COUNT()]])"; sql(sql) .explainContains(explain) .returnsUnordered("C=13500"); }
Source:
protected void writeToFile(File downloadFolder, ArrayList<SEDRow> results) throws IOException { String csvFilename = downloadFolder.getAbsolutePath() + File.separator + "chpl-sed-all-details" + ".csv"; File csvFile = new File(csvFilename); if (!csvFile.exists()) { csvFile.createNewFile(); } else { csvFile.delete(); } CertifiedProductCsvPresenter csvPresenter = new CertifiedProductCsvPresenter(); Date start = new Date(); int numRows = csvPresenter.presentAsFileSED(csvFile, results); Date end = new Date(); LOGGER.info("Wrote " + numRows + " rows to SED detailed data CSV file in " + (end.getTime() - start.getTime()) / 1000 + " seconds"); }

Target:
protected void writeToFile(File downloadFolder, ArrayList<SEDRow> results) throws IOException { String csvFilename = downloadFolder.getAbsolutePath() + File.separator + "chpl-sed-all-details.csv"; File csvFile = new File(csvFilename); if (!csvFile.exists()) { csvFile.createNewFile(); } else { csvFile.delete(); } SEDCsvPresenter csvPresenter = new SEDCsvPresenter(); Date start = new Date(); int numRows = csvPresenter.presentAsFile(csvFile, results); Date end = new Date(); LOGGER.info("Wrote " + numRows + " rows to SED detailed data CSV file in " + (end.getTime() - start.getTime()) / 1000 + " seconds"); }
Source:
Map<Integer,InputStream> createInputMap(final Map<Integer, ExposedByteArrayOutputStream> outputMap) throws IOException { final Map<Integer,InputStream> inputMap = new HashMap<>(); for (final Map.Entry<Integer, ExposedByteArrayOutputStream> mapEntry : outputMap.entrySet()) { try (final ByteArrayInputStream is = new ByteArrayInputStream(mapEntry.getValue().toByteArray())) { inputMap.put(mapEntry.getKey(), is); } } return inputMap; }

Target:
Map<Integer,InputStream> createInputMap(final Map<Integer, ExposedByteArrayOutputStream> outputMap) { return outputMap.entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> new ByteArrayInputStream(e.getValue().toByteArray()))); }
Source:
static Response parseResponse(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); String reason = statusLine.getReasonPhrase(); List<Header> headers = new ArrayList<Header>(); String contentType = "application/octet-stream"; for (org.apache.http.Header header : response.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); if ("Content-Type".equalsIgnoreCase(name)) { contentType = value; } headers.add(new Header(name, value)); } TypedByteArray body = null; HttpEntity entity = response.getEntity(); boolean isGzipped = false; if (entity != null) { if (entity.getContentEncoding() != null) { HeaderElement[] codecs = entity.getContentEncoding().getElements(); for (HeaderElement codec : codecs) { if ("gzip".equalsIgnoreCase(codec.getName())) { isGzipped = true; break; } } } byte[] bytes; if (isGzipped) { final GZIPInputStream gin = new GZIPInputStream(entity.getContent()); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = gin.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } bytes = baos.toByteArray(); } else { bytes = EntityUtils.toByteArray(entity); } body = new TypedByteArray(contentType, bytes); } return new Response(status, reason, headers, body); }

Target:
static Response parseResponse(HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); int status = statusLine.getStatusCode(); String reason = statusLine.getReasonPhrase(); List<Header> headers = new ArrayList<Header>(); String contentType = "application/octet-stream"; for (org.apache.http.Header header : response.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); if ("Content-Type".equalsIgnoreCase(name)) { contentType = value; } headers.add(new Header(name, value)); } TypedByteArray body = null; final HttpEntity entity = response.getEntity(); if (entity != null) { boolean isGzipped = false; if (entity.getContentEncoding() != null) { HeaderElement[] codecs = entity.getContentEncoding().getElements(); for (HeaderElement codec : codecs) { if ("gzip".equalsIgnoreCase(codec.getName())) { isGzipped = true; break; } } } byte[] bytes; if (isGzipped) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { final GZIPInputStream gin = new GZIPInputStream(entity.getContent()); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = gin.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } bytes = baos.toByteArray(); } finally { baos.close(); } } else { bytes = EntityUtils.toByteArray(entity); } body = new TypedByteArray(contentType, bytes); } return new Response(status, reason, headers, body); }
Source:
public void should_extract_null_from_unknown_key() { Map<String, List<String>> map = createTestData(); assertThat(map) .flatExtracting("name", "id") .contains("Jeff", (Object) null); }

Target:
public void should_extract_null_from_unknown_key() { Map<String, List<String>> map = createTestData(); assertThat(map).flatExtracting("name", "id") .containsNull(); }
Source:
protected double convertDegreesToValue(double degrees) { return ((degrees - ServoSubsystem.kMinServoAngle)) / getServoAngleRange(); }

Target:
protected static double convertDegreesToValue(double degrees) { return ((degrees - ServoSubsystem.MIN_SERVO_ANGLE)) / ServoSubsystem.getServoAngleRange(); }
Source:
private AccountGroup findGroup(final String name) throws OrmException, Failure { final AccountGroup g = groupCache.get(new AccountGroup.NameKey(name)); if (g == null) { throw new Failure(new NoSuchEntityException()); } return g; }

Target:
private AccountGroup findGroup(final String name) throws OrmException, Failure { final AccountGroup g = groupCache.get(new AccountGroup.NameKey(name)); if (g == null) { throw new Failure(new NoSuchGroupException(name)); } return g; }
Source:
RegionStateNode createRegionStateNode(RegionInfo regionInfo) { synchronized (regionsMapLock) { RegionStateNode node = regionsMap.computeIfAbsent(regionInfo.getRegionName(), key -> new RegionStateNode(regionInfo, regionInTransition)); return encodedRegionsMap.putIfAbsent(regionInfo.getEncodedName(), node); } }

Target:
RegionStateNode createRegionStateNode(RegionInfo regionInfo) { synchronized (regionsMapLock) { RegionStateNode node = regionsMap.computeIfAbsent(regionInfo.getRegionName(), key -> new RegionStateNode(regionInfo, regionInTransition)); if (encodedRegionsMap.get(regionInfo.getEncodedName()) != node) { encodedRegionsMap.put(regionInfo.getEncodedName(), node); } return node; } }
Source:
public void assertOpen() { Status reason = this.terminationReason; if ( reason != null ) { throw new TransactionTerminatedException( reason ); } if ( closed ) { throw new NotInTransactionException( "The statement has been closed." ); } }

Target:
public void assertOpen() { Status reason = this.terminationReason; if ( reason != null ) { throw new TransactionTerminatedException( reason ); } if ( closed ) { throw new NotInTransactionException( "The transaction has been closed." ); } }
Source:
public FeedLoadResult copyTables() { FeedLoadResult result = new FeedLoadResult(); try { connection = dataSource.getConnection(); this.tablePrefix = randomIdString(); result.uniqueIdentifier = tablePrefix; registerSnapshot(); this.tablePrefix += "."; long startTime = System.currentTimeMillis(); result.agency = copy(Table.AGENCY, true, true); result.calendar = copy(Table.CALENDAR, true, true); result.calendarDates = copy(Table.CALENDAR_DATES, true, false); result.fareAttributes = copy(Table.FARE_ATTRIBUTES, true, true); result.fareRules = copy(Table.FARE_RULES, true, true); result.feedInfo = copy(Table.FEED_INFO, true, false); result.frequencies = copy(Table.FREQUENCIES, true, true); result.routes = copy(Table.ROUTES, true, true); copy(Table.PATTERNS, true, true); copy(Table.PATTERN_STOP, true, true); result.shapes = copy(Table.SHAPES, true, false); result.stops = copy(Table.STOPS, true, true); result.stopTimes = copy(Table.STOP_TIMES, true, false); result.transfers = copy(Table.TRANSFERS, true, true); result.trips = copy(Table.TRIPS, true, true); LOG.info("Copying tables took sec", (System.currentTimeMillis() - startTime) / 1000); } catch (Exception ex) { LOG.error("Exception while creating snapshot: {}", ex.toString()); ex.printStackTrace(); result.fatalException = ex.getMessage(); } return result; }

Target:
public FeedLoadResult copyTables() { FeedLoadResult result = new FeedLoadResult(); try { long startTime = System.currentTimeMillis(); connection = dataSource.getConnection(); this.tablePrefix = randomIdString(); result.uniqueIdentifier = tablePrefix; registerSnapshot(); this.tablePrefix += "."; result.agency = copy(Table.AGENCY, true); result.calendar = copy(Table.CALENDAR, true); result.calendarDates = copy(Table.CALENDAR_DATES, true); result.fareAttributes = copy(Table.FARE_ATTRIBUTES, true); result.fareRules = copy(Table.FARE_RULES, true); result.feedInfo = copy(Table.FEED_INFO, true); result.frequencies = copy(Table.FREQUENCIES, true); result.routes = copy(Table.ROUTES, true); copy(Table.PATTERNS, true); copy(Table.PATTERN_STOP, true); result.shapes = copy(Table.SHAPES, true); result.stops = copy(Table.STOPS, true); result.stopTimes = copy(Table.STOP_TIMES, true); result.transfers = copy(Table.TRANSFERS, true); result.trips = copy(Table.TRIPS, true); result.completionTime = System.currentTimeMillis(); result.loadTimeMillis = result.completionTime - startTime; LOG.info("Copying tables took sec", (result.loadTimeMillis) / 1000); } catch (Exception ex) { LOG.error("Exception while creating snapshot: {}", ex.toString()); ex.printStackTrace(); result.fatalException = ex.getMessage(); } return result; }
Source:
public Utf8PrintStream(final OutputStream output, final boolean flush) throws UnsupportedEncodingException { super(output, flush, Utf8PrintStream.ENCODING); }

Target:
public Utf8PrintStream(final OutputStream output, final boolean flush) throws UnsupportedEncodingException { super(output, flush, StandardCharsets.UTF_8.toString()); }
Source:
public void notifyHasMessage(final Mailbox mailbox, final MessageKind kind) { final Receiver receiver = mailbox.getReceiver(); final CommunicationGroup group = getGroup(receiver); if (kind == null) { group.defaultMailboxes.add(mailbox); } else if (kind == MessageKind.MONOTONE) { group.monotoneMailboxes.add(mailbox); } else if (kind == MessageKind.ANTI_MONOTONE) { group.nonMonotoneMailboxes.add(mailbox); } else { throw new IllegalArgumentException(); } activate(group); }

Target:
public void notifyHasMessage(final Mailbox mailbox, final MessageKind kind) { final Receiver receiver = mailbox.getReceiver(); final CommunicationGroup group = this.groupMap.get(receiver); group.notifyHasMessage(mailbox, kind); activate(group); }
Source:
public String getText(Object arg0) { if (arg0 instanceof IAtsInsertionActivity) { IAtsWorkPackage workPacakage = (IAtsWorkPackage) arg0; IAtsInsertionActivity insertionActivity = AtsClientService.get().getProgramService().getInsertionActivity(workPacakage); IAtsInsertion insertion = AtsClientService.get().getProgramService().getInsertion(insertionActivity); IAtsProgram program = AtsClientService.get().getProgramService().getProgram(insertion); return String.format("%s - %s - %s - %", program, insertion, insertionActivity, workPacakage); } return super.getText(arg0); }

Target:
public String getText(Object arg0) { if (arg0 instanceof IAtsInsertionActivity) { IAtsWorkPackage workPacakage = (IAtsWorkPackage) arg0; IAtsInsertionActivity insertionActivity = AtsClientService.get().getProgramService().getInsertionActivity(workPacakage); IAtsInsertion insertion = AtsClientService.get().getProgramService().getInsertion(insertionActivity); IAtsProgram program = AtsClientService.get().getProgramService().getProgram(insertion); return String.format("%s - %s - %s - %s", program, insertion, insertionActivity, workPacakage); } return super.getText(arg0); }
Source:
PaxosQuorumCheckingCoalescingFunction<REQ, RESP, F> wrapWithRemotes( List<SERVICE> services, Map<SERVICE, CheckedRejectionExecutorService> executors, int quorumSize, Function<SERVICE, F> functionFactory) { List<FunctionAndExecutor<F>> functionsAndExecutors = KeyedStream.of(services) .map(executors::get) .mapKeys(functionFactory) .entries() .<FunctionAndExecutor<F>>map(entry -> ImmutableFunctionAndExecutor.of(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); List<F> functions = new ArrayList<>(services.size()); Map<F, CheckedRejectionExecutorService> executorMap = new HashMap<>(services.size()); for (SERVICE service: services) { F function = functionFactory.apply(service); functions.add(function); executorMap.put(function, executors.get(service)); } return new PaxosQuorumCheckingCoalescingFunction<>(functions, executorMap, quorumSize); }

Target:
PaxosQuorumCheckingCoalescingFunction<REQ, RESP, F> wrapWithRemotes( List<SERVICE> services, Map<SERVICE, CheckedRejectionExecutorService> executors, int quorumSize, Function<SERVICE, F> functionFactory) { List<F> functions = new ArrayList<>(services.size()); Map<F, CheckedRejectionExecutorService> executorMap = new HashMap<>(services.size()); for (SERVICE service: services) { F function = functionFactory.apply(service); functions.add(function); executorMap.put(function, executors.get(service)); } return new PaxosQuorumCheckingCoalescingFunction<>(functions, executorMap, quorumSize); }
Source:
public void run() throws XMLStreamException { int index = 0; final var iterator = source.iterator(); while (true) { try { if (!iterator.hasNext()) { break; } final var o = iterator.next(); final String pid = o.getObjectInfo().getPid(); if (pid != null) { if ((limit < 0 || index++ < limit) && acceptPid(pid)) { LOGGER.info("Processing \"" + pid + "\"..."); try { o.processObject(handler); } catch (Exception ex) { LOGGER.error("MIGRATION_FAILURE: pid=\"{}\", message=\"{}\"", pid, ex.getMessage(), ex); if (this.continueOnError) { continue; } else { throw new RuntimeException(ex); } } } } } catch (Exception ex) { if (this.continueOnError) { LOGGER.error("MIGRATION_FAILURE: UNREADABLE_OBJECT: message=\"{}\"", ex.getMessage(), ex); continue; } else { throw new RuntimeException(ex); } } } }

Target:
public void run() throws XMLStreamException { int index = 0; for (final var iterator = source.iterator(); iterator.hasNext();) { try { final var o = iterator.next(); final String pid = o.getObjectInfo().getPid(); if (pid != null) { if ((limit < 0 || index++ < limit) && acceptPid(pid)) { LOGGER.info("Processing \"" + pid + "\"..."); try { o.processObject(handler); } catch (Exception ex) { LOGGER.error("MIGRATION_FAILURE: pid=\"{}\", message=\"{}\"", pid, ex.getMessage(), ex); if (this.continueOnError) { continue; } else { throw new RuntimeException(ex); } } } } } catch (Exception ex) { if (this.continueOnError) { LOGGER.error("MIGRATION_FAILURE: UNREADABLE_OBJECT: message=\"{}\"", ex.getMessage(), ex); continue; } else { throw new RuntimeException(ex); } } } }
Source:
protected void appendGroupByClause(StringBuilder sbSelectFrom) { Set<String> clauses = new LinkedHashSet<String>(); groupByManager.buildGroupByClauses(clauses); for (ExpressionTransformerGroup<?> transformerGroup : transformerGroups) { clauses.addAll(transformerGroup.getRequiredGroupByClauses()); } if (hasGroupBy) { if (mainQuery.getQueryConfiguration().isImplicitGroupByFromSelectEnabled()) { selectManager.buildGroupByClauses(cbf.getMetamodel(), clauses); } if (mainQuery.getQueryConfiguration().isImplicitGroupByFromHavingEnabled()) { havingManager.buildGroupByClauses(clauses); } if (mainQuery.getQueryConfiguration().isImplicitGroupByFromOrderByEnabled()) { orderByManager.buildGroupByClauses(clauses); } } if (!clauses.isEmpty()) { for (ExpressionTransformerGroup<?> transformerGroup : transformerGroups) { clauses.addAll(transformerGroup.getOptionalGroupByClauses()); } } groupByManager.buildGroupBy(sbSelectFrom, clauses); havingManager.buildClause(sbSelectFrom); }

Target:
protected void appendGroupByClause(StringBuilder sbSelectFrom) { Set<String> clauses = new LinkedHashSet<String>(); groupByManager.buildGroupByClauses(clauses); int size = transformerGroups.size(); for (int i = 0; i < transformerGroups.size(); i++) { ExpressionTransformerGroup<?> transformerGroup = transformerGroups.get(i); clauses.addAll(transformerGroup.getRequiredGroupByClauses()); } if (hasGroupBy) { if (mainQuery.getQueryConfiguration().isImplicitGroupByFromSelectEnabled()) { selectManager.buildGroupByClauses(cbf.getMetamodel(), clauses); } if (mainQuery.getQueryConfiguration().isImplicitGroupByFromHavingEnabled()) { havingManager.buildGroupByClauses(clauses); } if (mainQuery.getQueryConfiguration().isImplicitGroupByFromOrderByEnabled()) { orderByManager.buildGroupByClauses(clauses); } } if (!clauses.isEmpty()) { for (int i = 0; i < size; i++) { ExpressionTransformerGroup<?> transformerGroup = transformerGroups.get(i); clauses.addAll(transformerGroup.getOptionalGroupByClauses()); } } groupByManager.buildGroupBy(sbSelectFrom, clauses); havingManager.buildClause(sbSelectFrom); }
Source:
public void setCountriesOfOrigin(Iterable<Country> countries) { this.countriesOfOrigin = Sets.newHashSet(countries); }

Target:
public void setCountriesOfOrigin(Iterable<Country> countries) { this.countriesOfOrigin = ImmutableSet.copyOf(countries); }
Source:
public Image getImage(Object element) { return TasksUiPlugin.getDefault().getBrandingIcon(MYLYN_GERRIT); }

Target:
public Image getImage(Object element) { return TasksUiPlugin.getDefault().getBrandingIcon(((ActivityEvent) element).getKind()); }
Source:
public void with_decorators() throws Exception { assertThat(Kind.CLASS_DECLARATION) .matches("@decorator class A {}") .matches("@decorator1 @decorator2 class A {}") .matches("class C { @decorator method(){} }") .matches("class C { @decorator static method(){} }") .matches("class C { @decorator1 @decorator2 method(){} }") .matches("class C {method(){} property; }") .matches("class C { property; property=42; }") ; }

Target:
public void with_decorators() throws Exception { assertThat(Kind.CLASS_DECLARATION) .matches("@decorator class A {}") .matches("@decorator1 @decorator2 class A {}") .matches("class C { @decorator method(){} }") .matches("class C { @decorator static method(){} }") .matches("class C { @decorator1 @decorator2 method(){} }") ; }
Source:
public SQLQueryEngine(EntityManagerFactory emf, MetaDataStore metaDataStore) { this.emf = emf; this.dictionary = metaDataStore.getDictionary(); Set<Table> tables = metaDataStore.getMetaData(Table.class); tables.addAll(metaDataStore.getMetaData(AnalyticView.class)); this.tables = tables.stream() .map(table -> table instanceof AnalyticView ? new SQLAnalyticView(table.getCls(), dictionary) : new SQLTable(table.getCls(), dictionary)) .collect(Collectors.toMap(Table::getCls, Function.identity())); }

Target:
public SQLQueryEngine(EntityManagerFactory emf, MetaDataStore metaDataStore) { this.emf = emf; this.metadataDictionary = metaDataStore.getDictionary(); Set<Table> tables = metaDataStore.getMetaData(Table.class); tables.addAll(metaDataStore.getMetaData(AnalyticView.class)); this.tables = tables.stream() .map(table -> table instanceof AnalyticView ? new SQLAnalyticView(table.getCls(), metadataDictionary) : new SQLTable(table.getCls(), metadataDictionary)) .collect(Collectors.toMap(Table::getCls, Function.identity())); }
Source:
public void loadDetails() { if(null==currentServer) return; ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(ADDRESS).set(new ResourceAddress().add("host", serverStore.getSelectedServer().getHostName()).add("server", serverStore.getSelectedServer().getServerName())); operation.get(ADDRESS).add("subsystem", "undertow"); operation.get(ADDRESS).add("server", currentServer); operation.get(INCLUDE_RUNTIME).set(true); operation.get(RECURSIVE).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Log.error("Failed to load http server details", response.getFailureDescription()); } else { ModelNode data = response.get(RESULT); List<Property> connectors = new ArrayList<Property>(); connectors.addAll(failSafeGetCollection(data.get("http-listener"))); connectors.addAll(failSafeGetCollection(data.get("ajp-listener"))); connectors.addAll(failSafeGetCollection(data.get("https-listener"))); getView().setConnectors(connectors); } } }); }

Target:
public void loadDetails() { if(null==currentServer) return; ModelNode operation = new ModelNode(); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(ADDRESS).set(RuntimeBaseAddress.get()); operation.get(ADDRESS).add("subsystem", "undertow"); operation.get(ADDRESS).add("server", currentServer); operation.get(INCLUDE_RUNTIME).set(true); operation.get(RECURSIVE).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Log.error("Failed to load http server details", response.getFailureDescription()); } else { ModelNode data = response.get(RESULT); List<Property> connectors = new ArrayList<Property>(); connectors.addAll(failSafeGetCollection(data.get("http-listener"))); connectors.addAll(failSafeGetCollection(data.get("ajp-listener"))); connectors.addAll(failSafeGetCollection(data.get("https-listener"))); getView().setConnectors(connectors); } } }); }
Source:
public void testHasExpired() { CompositeRegistry r = new CompositeRegistry(clock); Counter c1 = r.counter("id1"); Assert.assertTrue(c1.hasExpired()); Registry r1 = new DefaultRegistry(clock); r.add(r1); Assert.assertTrue(c1.hasExpired()); }

Target:
public void testHasExpired() { CompositeRegistry r = new CompositeRegistry(clock); Counter c1 = r.counter("id1"); Assert.assertTrue(c1.hasExpired()); Registry r1 = new DefaultRegistry(clock); r.add(r1); Assert.assertTrue(c1.hasExpired()); c1.increment(); Assert.assertFalse(c1.hasExpired()); }
Source:
public void testAResourceIsDisplayedAsAColumnWhenItsIconIsSelectedInTheTopOfRoomGrid() { HomeAdminPage homeAdminPage = new HomeAdminPage(); RoomsPage roomsPage = homeAdminPage.clickConferenceRoomsLink(); RoomInfoPage roomInfoPage = roomsPage.doubleClickOverRoomName(roomName); RoomResourceAssociationsPage roomResourceAssociationsPage = roomInfoPage .clickResourceAssociationsLink(); roomResourceAssociationsPage.clickAddResourceToARoom(resourceDisplayName); roomResourceAssociationsPage.changeValueForResourceFromAssociatedList(resourceDisplayName, quantity); roomsPage = roomResourceAssociationsPage.clickSaveBtn(); roomsPage.clickResourceIcon(resourceDisplayName); Assert.assertEquals(roomsPage.getResourceQuantity(roomName),"x " + quantity); Assert.assertTrue(roomsPage.isResourcePresentInTableHeader(resourceDisplayName)); }

Target:
public void testAResourceIsDisplayedAsAColumnWhenItsIconIsSelectedInTheTopOfRoomGrid() { HomeAdminPage homeAdminPage = new HomeAdminPage(); RoomsPage roomsPage = homeAdminPage.clickConferenceRoomsLink(); RoomInfoPage roomInfoPage = roomsPage.doubleClickOverRoomName(roomName); RoomResourceAssociationsPage roomResourceAssociationsPage = roomInfoPage .clickResourceAssociationsLink(); roomResourceAssociationsPage.clickAddResourceToARoom(resourceDisplayName) .changeValueForResourceFromAssociatedList(resourceDisplayName,quantity); roomsPage = roomResourceAssociationsPage.clickSaveBtn(); roomsPage.clickResourceIcon(resourceDisplayName); Assert.assertEquals(roomsPage.getResourceQuantity(roomName),"x " + quantity); Assert.assertTrue(roomsPage.isResourcePresentInTableHeader(resourceDisplayName)); Assert.assertTrue(roomsPage.searchResource(resourceDisplayName)); }
Source:
protected IDialogSettings getPersistentPropertyStore() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(fViewId); if (section == null) { section = settings.addNewSection(fViewId); if (section == null) { throw new IllegalStateException(); } } return section; }

Target:
protected IDialogSettings getPersistentPropertyStore() { IDialogSettings settings = Activator.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(fViewId); if (section == null) { section = settings.addNewSection(fViewId); if (section == null) { throw new IllegalStateException("The persistent property section could not be added"); } } return section; }
Source:
public NewExecutableDialog( Shell parentShell, NewExecutableInfo info ) { super( parentShell ); setShellStyle( getShellStyle() | SWT.RESIZE ); fInfo = info != null ? info : new NewExecutableInfo(SessionType.LOCAL); }

Target:
public NewExecutableDialog( Shell parentShell, NewExecutableInfo info ) { super( parentShell ); assert info != null; setShellStyle( getShellStyle() | SWT.RESIZE ); fInfo = info; }
Source:
public Set<String> getErrorCodes() { return errorCodes; }

Target:
public Set<String> getErrorCodes() { if (errorCodes == null) { errorCodes = new HashSet<>(); } else { return errorCodes; } if (lightblueResponse.getErrors()!=null) { for(Error e:lightblueResponse.getErrors()) { errorCodes.add(e.getErrorCode()); } } if (lightblueResponse.getDataErrors()!=null) { for(DataError de:lightblueResponse.getDataErrors()) { if (de.getErrors()!=null) { for(Error e:de.getErrors()) { errorCodes.add(e.getErrorCode()); } } } } return errorCodes; }
Source:
public static void changeValueCommand(final List<Command> response, final ServerAttribute attribute, final Object value) { if (response == null) { return; } if (attribute == null) { LOG.info("Cannot change value on a null attribute to '{}'", value); return; } forceChangeValue(value, response, attribute); }

Target:
public static void changeValueCommand(final List<Command> response, final ServerAttribute attribute, final Object value) { if (response == null) { return; } if (attribute == null) { LOG.error("Cannot change value on a null attribute to '{}'", value); return; } forceChangeValue(value, response, attribute); }
Source:
public void notifyLeaderChanged(RaftGroupMemberId groupMemberId, RaftPeerId raftPeerId) { if (mRaftGroupId == groupMemberId.getGroupId()) { mIsLeader = groupMemberId.getPeerId() == raftPeerId; mJournalSystem.notifyLeadershipStateChanged(mIsLeader); } }

Target:
public void notifyLeaderChanged(RaftGroupMemberId groupMemberId, RaftPeerId raftPeerId) { if (mRaftGroupId == groupMemberId.getGroupId()) { mIsLeader = groupMemberId.getPeerId() == raftPeerId; mJournalSystem.notifyLeadershipStateChanged(mIsLeader); } else { LOG.warn("Received notification for unrecognized group {}, current group is {}", groupMemberId.getGroupId(), mRaftGroupId); } }
Source:
protected void onPageWillGetDeactivated(Direction progress, PageChangingEvent event, DataBindingContext dbc) { class ImageValidator implements IRunnableWithProgress { private boolean imageExistsLocally = false; private boolean imageExistsRemotely = false; @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { this.imageExistsLocally = model.imageExistsLocally(model.getImage()); if(!imageExistsLocally) { this.imageExistsRemotely = model.imageExistsRemotely(model.getImage()); } } } final ImageValidator imageValidator = new ImageValidator(); try { getContainer().run(true, false, imageValidator); } catch (InvocationTargetException | InterruptedException e) { final String message = "Failed to verify if an image with the name '" + model.getImage() + "' exists."; MessageDialog.openError(getShell(), "Error", message); OpenShiftUIActivator.getDefault().getLogger().logError(message, e); } if (imageValidator.imageExistsLocally) { return; } else if (!imageValidator.imageExistsLocally && imageValidator.imageExistsRemotely) { if(!MessageDialog.openConfirm(getShell(), "Missing Docker Image", "This Docker image will need to be pulled before opening the next page.")) { event.doit = false; } } else { MessageDialog.openError(getShell(), "Error", "No Docker image with the given repository and tag could be found."); event.doit = false; } }

Target:
protected void onPageWillGetDeactivated(Direction progress, PageChangingEvent event, DataBindingContext dbc) { class ImageValidatorJob extends Job { public ImageValidatorJob(String name) { super(name); } private boolean imageExistsLocally = false; private boolean imageExistsRemotely = false; @Override protected IStatus run(IProgressMonitor monitor) { this.imageExistsLocally = model.imageExistsLocally(model.getImage()); if(!imageExistsLocally) { this.imageExistsRemotely = model.imageExistsRemotely(model.getImage()); } return Status.OK_STATUS; } } final ImageValidatorJob imageValidator = new ImageValidatorJob("Looking-up the selected Docker image..."); try { final IStatus validatorJobStatus = WizardUtils.runInWizard(imageValidator, getContainer()); if (imageValidator.imageExistsLocally) { return; } else if (imageValidator.imageExistsRemotely) { if (!MessageDialog.openConfirm(getShell(), "Missing Docker Image", "The metadata for the Docker image named '" + model.getImage() + "' will need to be pulled before opening the next page.")) { event.doit = false; } } else if(validatorJobStatus.isOK()){ MessageDialog.openError(getShell(), "Error", "No Docker image named '" + model.getImage() + "' could be found."); event.doit = false; } else { event.doit = false; } } catch (InvocationTargetException | InterruptedException e) { final String message = "Failed to verify if an image named '" + model.getImage() + "' exists."; MessageDialog.openError(getShell(), "Error", message); OpenShiftUIActivator.getDefault().getLogger().logError(message, e); } }
Source:
private void serverRemoved(final MongoDBServer member) { if (LOG.isDebugEnabled()) LOG.debug("Scheduling removal of member from {}: {}", getName(), member); if (member.equals(getAttribute(PRIMARY_ENTITY))) setAttribute(PRIMARY_ENTITY, null); executor.submit(new Runnable() { @Override public void run() { Boolean isAvailable = member.getAttribute(MongoDBServer.SERVICE_UP); MongoDBServer primary = getPrimary(); if (primary != null && !isAvailable) { primary.getClient().removeMemberFromReplicaSet(member); if (LOG.isInfoEnabled()) { LOG.info("Removed from replica set {}", member, getName()); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Rescheduling removal of member from replica set {}: service_up={}, primary={}", new Object[]{member, getName(), isAvailable, primary}); } executor.schedule(this, 3, TimeUnit.SECONDS); } } }); }

Target:
private void serverRemoved(final MongoDBServer member) { if (LOG.isDebugEnabled()) LOG.debug("Scheduling removal of member from {}: {}", getName(), member); if (member.equals(getAttribute(PRIMARY_ENTITY))) setAttribute(PRIMARY_ENTITY, null); executor.submit(new Runnable() { @Override public void run() { Boolean isAvailable = member.getAttribute(MongoDBServer.SERVICE_UP); MongoDBServer primary = getPrimary(); if (primary != null && !isAvailable) { primary.removeMemberFromReplicaSet(member); if (LOG.isInfoEnabled()) { LOG.info("Removed from replica set {}", member, getName()); } } else { if (LOG.isTraceEnabled()) { LOG.trace("Rescheduling removal of member from replica set {}: service_up={}, primary={}", new Object[]{member, getName(), isAvailable, primary}); } executor.schedule(this, 3, TimeUnit.SECONDS); } } }); }
Source:
public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case ACTION_START: SyncthingHelper.startSynchthingService(context); break; case ACTION_STOP: SyncthingHelper.stopSynchtingService(context); break; case ACTION_STOP2: SyncthingHelper.stopSynchtingService2(context); break; } }

Target:
public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case ACTION_START: context.startService(new Intent(context, SyncthingService.class)); break; case ACTION_STOP: if (SyncthingService.alwaysRunInBackground(context)) { final String msg = context.getString(R.string.appconfig_receiver_background_enabled); Context appContext = context.getApplicationContext(); NotificationCompat.Builder nb = new NotificationCompat.Builder(context) .setContentText(msg) .setTicker(msg) .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) .setContentTitle(context.getText(context.getApplicationInfo().labelRes)) .setSmallIcon(R.drawable.ic_stat_notify) .setAutoCancel(true) .setContentIntent(PendingIntent.getActivity(appContext, 0, new Intent(appContext, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { nb.setCategory(Notification.CATEGORY_ERROR); } NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(ID_NOTIFICATION_BACKGROUND_ACTIVE, nb.build()); } else { context.stopService(new Intent(context, SyncthingService.class)); } break; } }
Source:
public void setUp() throws Exception { IOUtils.copy(getClass().getClassLoader().getResourceAsStream(PDF_NAME), new FileOutputStream(pdfFile)); blob = Blobs.createBlob(pdfFile); }

Target:
public void setUp() throws Exception { targetDirectory = Framework.createTempDirectory("target").toFile(); tempDirectory = Framework.createTempDirectory("tmp").toFile(); pdfFile = new File(tempDirectory.getAbsolutePath(), PDF_NAME); blob = Blobs.createBlob(pdfFile); try (InputStream in = getClass().getClassLoader().getResourceAsStream(PDF_NAME); OutputStream out = new FileOutputStream(pdfFile)) { IOUtils.copy(in, out); } }
Source:
public void setup() throws Exception { customDeployer = new CustomDeployer(); artifactsList = new ArrayList<>(); artifact = new Artifact(new File(getTestResourceFile(DEPLOYER_REPO).getAbsolutePath() + File.separator + "sample1.txt")); artifact.setType(new ArtifactType<>("txt")); artifactsList.add(artifact); System.setProperty(org.wso2.carbon.kernel.Constants.CARBON_HOME, getTestResourceFile("yaml").getAbsolutePath()); ConfigProvider configProvider = new ConfigProviderImpl(new YAMLBasedConfigFileReader("deployment.yaml")); CarbonRuntime carbonRuntime = CarbonRuntimeFactory .createCarbonRuntime(configProvider); DataHolder.getInstance().setCarbonRuntime(carbonRuntime); DataHolder.getInstance().setConfigProvider(configProvider); brokerService = new BrokerService(); brokerService.setUseJmx(false); brokerService.setBrokerName("carbon"); brokerService.setDataDirectory("target/activemq-data"); brokerService.start(); Topic topic = new ActiveMQTopic("topic0"); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://carbon?create=false"); Connection connection = connectionFactory.createConnection(); connection.setClientID("carbon"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); topicSubscriber = session.createDurableSubscriber(topic, "durable"); connection.start(); }

Target:
public void setup() throws Exception { customDeployer = new CustomDeployer(); artifactsList = new ArrayList<>(); artifact = new Artifact(new File(getTestResourceFile(DEPLOYER_REPO).getAbsolutePath() + File.separator + "sample1.txt")); artifact.setType(new ArtifactType<>("txt")); artifactsList.add(artifact); System.setProperty(org.wso2.carbon.kernel.Constants.CARBON_HOME, getTestResourceFile("yaml").getAbsolutePath()); ConfigProvider configProvider = new ConfigProviderImpl(new YAMLBasedConfigFileReader(DEPLOYMENT_YAML)); CarbonRuntime carbonRuntime = CarbonRuntimeFactory .createCarbonRuntime(configProvider); DataHolder.getInstance().setCarbonRuntime(carbonRuntime); DataHolder.getInstance().setConfigProvider(configProvider); brokerService = new BrokerService(); brokerService.setUseJmx(false); brokerService.setBrokerName("carbon"); brokerService.setDataDirectory("target/activemq-data"); brokerService.start(); Topic topic = new ActiveMQTopic("topic0"); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://carbon?create=false"); Connection connection = connectionFactory.createConnection(); connection.setClientID("carbon"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); topicSubscriber = session.createDurableSubscriber(topic, "durable"); connection.start(); }