auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void innerMap( InputRow inputRow, Context context ) throws IOException { final List<Object> groupKey = Rows.toGroupKey( rollupGranularity.bucketStart(inputRow.getTimestamp()).getMillis(), inputRow ); Interval interval; if (determineIntervals) { interval = config.getGranularitySpec() .getSegmentGranularity() .bucket(DateTimes.utc(inputRow.getTimestampFromEpoch())); hyperLogLogs.putIfAbsent(interval, HyperLogLogCollector.makeLatestCollector()); } else { final Optional<Interval> maybeInterval = config.getGranularitySpec() .bucketInterval(DateTimes.utc(inputRow.getTimestampFromEpoch())); if (!maybeInterval.isPresent()) { throw new ISE("WTF?! No bucket found for timestamp: %s", inputRow.getTimestampFromEpoch()); } interval = maybeInterval.get(); } hyperLogLogs .get(interval) .add(hashFunction.hashBytes(HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsBytes(groupKey)).asBytes()); context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.ROWS_PROCESSED_COUNTER).increment(1); }

Target:
protected void innerMap( InputRow inputRow, Context context ) throws IOException { final List<Object> groupKey = Rows.toGroupKey( rollupGranularity.bucketStart(inputRow.getTimestamp()).getMillis(), inputRow ); Interval interval; if (determineIntervals) { interval = config.getGranularitySpec() .getSegmentGranularity() .bucket(DateTimes.utc(inputRow.getTimestampFromEpoch())); hyperLogLogs.computeIfAbsent(interval, intv -> HyperLogLogCollector.makeLatestCollector()); } else { final Optional<Interval> maybeInterval = config.getGranularitySpec() .bucketInterval(DateTimes.utc(inputRow.getTimestampFromEpoch())); if (!maybeInterval.isPresent()) { throw new ISE("WTF?! No bucket found for timestamp: %s", inputRow.getTimestampFromEpoch()); } interval = maybeInterval.get(); } hyperLogLogs .get(interval) .add(hashFunction.hashBytes(HadoopDruidIndexerConfig.JSON_MAPPER.writeValueAsBytes(groupKey)).asBytes()); context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.ROWS_PROCESSED_COUNTER).increment(1); }
Source:
void display(PrintWriter writer) throws UnloggedFailure, OrmException { AccountGroup group = groupCache.get(new AccountGroup.NameKey(name)); String errorText = "Group not found or not visible\n"; if (group == null) { writer.write(errorText); writer.flush(); return; } try { List<AccountInfo> members = apply(group.getGroupUUID()); ColumnFormatter formatter = new ColumnFormatter(writer, '\t'); formatter.addColumn("userid"); formatter.addColumn("name"); formatter.addColumn("email"); formatter.nextLine(); for (AccountInfo member : members) { if (member == null) { continue; } AccountState account = accounts.get(member._id); formatter.addColumn(Objects.firstNonNull( account != null ? account.getUserName() : null, "n/a")); formatter.addColumn(Objects.firstNonNull( Strings.emptyToNull(member.name), "n/a")); formatter.addColumn(Objects.firstNonNull(member.email, "n/a")); formatter.nextLine(); } formatter.finish(); } catch (MethodNotAllowedException e) { writer.write(errorText); writer.flush(); } }

Target:
void display(PrintWriter writer) throws UnloggedFailure, OrmException { AccountGroup group = groupCache.get(new AccountGroup.NameKey(name)); String errorText = "Group not found or not visible\n"; if (group == null) { writer.write(errorText); writer.flush(); return; } try { List<AccountInfo> members = apply(group.getGroupUUID()); ColumnFormatter formatter = new ColumnFormatter(writer, '\t'); formatter.addColumn("id"); formatter.addColumn("username"); formatter.addColumn("full name"); formatter.addColumn("email"); formatter.nextLine(); for (AccountInfo member : members) { if (member == null) { continue; } formatter.addColumn(member._id.toString()); formatter.addColumn(Objects.firstNonNull(member.username, "n/a")); formatter.addColumn(Objects.firstNonNull( Strings.emptyToNull(member.name), "n/a")); formatter.addColumn(Objects.firstNonNull(member.email, "n/a")); formatter.nextLine(); } formatter.finish(); } catch (MethodNotAllowedException e) { writer.write(errorText); writer.flush(); } }
Source:
public DocumentModel getOrCreateDocument(DocumentModel docModel) { return getOrCreateDocument(docModel, null); }

Target:
public DocumentModel getOrCreateDocument(DocumentModel docModel) { return getOrCreateDocument(docModel, Function.identity()); }
Source:
protected Map<Guid, Guid> addAllTemplateDisks() { processIllegalDisks(); Map<Guid, Guid> idMap = super.addAllTemplateDisks(); if (!idMap.isEmpty()) { lockSnapshot(); } return idMap; }

Target:
protected Map<Guid, Guid> addAllTemplateDisks() { processIllegalDisks(); Map<Guid, Guid> srcDeviceIdToTargetDeviceIdMapping = super.addAllTemplateDisks(); if (!srcDeviceIdToTargetDeviceIdMapping.isEmpty()) { lockSnapshot(); } return srcDeviceIdToTargetDeviceIdMapping; }
Source:
public static void setJobIdOffset(int jobIdOffset) { if (jobIdOffset > JobIds.RESERVED_JOB_ID_RANGE_START - 500) { throw new IllegalArgumentException("offset is too close to Integer.MAX_VALUE"); } JobConfig.jobIdOffset = jobIdOffset; }

Target:
public static void setJobIdOffset(int jobIdOffset) { JobPreconditions.checkArgumentNonnegative(jobIdOffset, "offset can't be negative"); if (jobIdOffset > JobIdsInternal.RESERVED_JOB_ID_RANGE_START - 500) { throw new IllegalArgumentException("offset is too close to Integer.MAX_VALUE"); } JobConfig.jobIdOffset = jobIdOffset; }
Source:
void testFindGetterIdentifier() { AggregateModel<SomeGetterIdAnnotatedHandlers> inspector = AnnotatedAggregateMetaModelFactory.inspectAggregate(SomeGetterIdAnnotatedHandlers.class); assertEquals("SomeGetterIdAnnotatedHandlers", inspector.type()); assertEquals("id", inspector.getIdentifier(new SomeGetterIdAnnotatedHandlers())); assertEquals("getId", inspector.routingKey()); }

Target:
void testFindGetterIdentifier() { AggregateModel<SomeGetterIdAnnotatedHandlers> inspector = AnnotatedAggregateMetaModelFactory.inspectAggregate(SomeGetterIdAnnotatedHandlers.class); assertEquals("SomeGetterIdAnnotatedHandlers", inspector.type()); assertEquals("id", inspector.getIdentifier(new SomeGetterIdAnnotatedHandlers())); assertEquals("id", inspector.routingKey()); }
Source:
private void shuffleAndPopulate(Map<String, Integer> availableReplicaCountPerDatacenter) { for (String dataCenter : replicaListPerDatacenter.keySet()) { List<ReplicaId> replicaList = shuffleReplicaListForDataCenter(dataCenter, availableReplicaCountPerDatacenter); replicaListPerDatacenter.put(dataCenter, replicaList); replicasInFlightPerDatacenter.put(dataCenter, new ArrayList<ReplicaId>()); } }

Target:
private void shuffleAndPopulate(Map<String, Integer> availableReplicaCountPerDatacenter) { for (String dataCenter : replicaListPerDatacenter.keySet()) { shuffleReplicasForDataCenter(dataCenter, availableReplicaCountPerDatacenter); replicasInFlightPerDatacenter.put(dataCenter, new ArrayList<ReplicaId>()); } }
Source:
public static void main(String... args) { EngineConfigCLIParser parser = null; try { parser = new EngineConfigCLIParser(); parser.parse(args); EngineConfigMap argsMap = parser.getEngineConfigMap(); if (argsMap.getLogFile() != null) { JavaLoggingUtils.addFileHandler(argsMap.getLogFile(), argsMap.getLogLevel()); } } catch (Throwable t) { System.out.println(t.getMessage()); System.exit(1); } try { EngineConfig.getInstance().setUpAndExecute(parser); } catch (Throwable t) { LoggerFactory.getLogger(EngineConfigExecutor.class).debug("Exiting with error: ", t); System.out.println(t.getMessage()); System.exit(1); } }

Target:
public static void main(String... args) { EngineConfigCLIParser parser = null; try { parser = new EngineConfigCLIParser(); parser.parse(args); EngineConfigMap argsMap = parser.getEngineConfigMap(); if (argsMap.getLogFile() != null) { JavaLoggingUtils.addFileHandler(argsMap.getLogFile()); } if (argsMap.getLogLevel() != null) { JavaLoggingUtils.setLogLevel(argsMap.getLogLevel()); } } catch (Throwable t) { System.out.println(t.getMessage()); System.exit(1); } try { EngineConfig.getInstance().setUpAndExecute(parser); } catch (Throwable t) { LoggerFactory.getLogger(EngineConfigExecutor.class).debug("Exiting with error: ", t); System.out.println(t.getMessage()); System.exit(1); } }
Source:
private Class<?> getImplementationClass() throws NoSuchAlgorithmException { Reference<Class<?>> implementationClassRef = this.implementationClassRef; Class<?> implementationClass = implementationClassRef != null ? implementationClassRef.get() : null; if (implementationClass == null) { ClassLoader classLoader = WildFlyElytronProvider.class.getClassLoader(); try { implementationClass = Class.forName(getClassName(), true, classLoader); } catch (ClassNotFoundException e) { throw log.noSuchAlgorithmCreateService(getType(), getAlgorithm(), e); } this.implementationClassRef = new WeakReference<>(implementationClass); } return implementationClass; }

Target:
private Class<?> getImplementationClass() throws NoSuchAlgorithmException { Reference<Class<?>> implementationClassRef = this.implementationClassRef; Class<?> implementationClass = implementationClassRef != null ? implementationClassRef.get() : null; if (implementationClass == null) { ClassLoader classLoader = WildFlyElytronProvider.class.getClassLoader(); try { implementationClass = Class.forName(getClassName(), false, classLoader); } catch (ClassNotFoundException e) { throw log.noSuchAlgorithmCreateService(getType(), getAlgorithm(), e); } this.implementationClassRef = new WeakReference<>(implementationClass); } return implementationClass; }
Source:
public final CloseableStreamBuildListener createBuildListener() throws IOException, InterruptedException { OutputStream logger = createOutputStream(); if (!(loggable instanceof Run<?,?>)) { throw new IOException("Loggable is not a Run instance: " + loggable.getClass()); } Run<?,?> build = (Run<?, ?>)loggable; for (ConsoleLogFilter filter : ConsoleLogFilter.all()) { logger = filter.decorateLogger(build, logger); } final Job<?, ?> project = build.getParent(); if (project instanceof BuildableItemWithBuildWrappers && build instanceof AbstractBuild) { BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; for (BuildWrapper bw : biwbw.getBuildWrappersList()) { logger = bw.decorateLogger((AbstractBuild) build, logger); } } final ConsoleLogFilter f = getExtraConsoleLogFilter(); if (f != null) { LOGGER.log(Level.INFO, "Decorated run {0} by a custom log filter {1}", new Object[]{this, f}); logger = f.decorateLogger(build, logger); } return new CloseableStreamBuildListener(logger, getOwner().getCharset()); }

Target:
public final StreamBuildListener createBuildListener() throws IOException, InterruptedException { OutputStream logger = createOutputStream(); if (!(loggable instanceof Run<?,?>)) { throw new IOException("Loggable is not a Run instance: " + loggable.getClass()); } Run<?,?> build = (Run<?, ?>)loggable; for (ConsoleLogFilter filter : ConsoleLogFilter.all()) { logger = filter.decorateLogger(build, logger); } final Job<?, ?> project = build.getParent(); if (project instanceof BuildableItemWithBuildWrappers && build instanceof AbstractBuild) { BuildableItemWithBuildWrappers biwbw = (BuildableItemWithBuildWrappers) project; for (BuildWrapper bw : biwbw.getBuildWrappersList()) { logger = bw.decorateLogger((AbstractBuild) build, logger); } } final ConsoleLogFilter f = getExtraConsoleLogFilter(); if (f != null) { LOGGER.log(Level.INFO, "Decorated run {0} by a custom log filter {1}", new Object[]{this, f}); logger = f.decorateLogger(build, logger); } return new StreamBuildListener(logger, getOwner().getCharset()); }
Source:
public void renameAndAddIndexedField() { final int oldTestVal = 7; final Long testVal = Long.valueOf(293); RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.schema.get("MigrationIndexedFieldRenamed") .renameField("testField", "oldTestField") .addField("testField", Long.class); } }; RealmConfiguration config = configFactory.createConfigurationBuilder() .schema(MigrationIndexedFieldRenamed.class) .schemaVersion(2) .migration(migration) .assetFile("rename-and-add-indexed.realm") .build(); realm = Realm.getInstance(config); realm.beginTransaction(); MigrationIndexedFieldRenamed obj = realm.createObject(MigrationIndexedFieldRenamed.class, 2); obj.oldTestField = oldTestVal; obj.testField = testVal; realm.commitTransaction(); assertTrue(realm.getSchema().get("MigrationIndexedFieldRenamed").hasField("testField")); assertTrue(realm.getSchema().get("MigrationIndexedFieldRenamed").hasField("oldTestField")); RealmResults<MigrationIndexedFieldRenamed> result = realm.where(MigrationIndexedFieldRenamed.class).equalTo("id", 2).findAll(); assertEquals("There should be an object with PK=2", 1, result.size()); assertEquals("Unexpected oldTestField value", oldTestVal, result.first().oldTestField); assertEquals("Unexpected testField value", testVal, result.first().testField); realm.close(); }

Target:
public void renameAndAddIndexedField() { final Class<MigrationIndexedFieldRenamed> schemaClass = MigrationIndexedFieldRenamed.class; final int oldTestVal = 7; final Long testVal = Long.valueOf(293); RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.getSchema().get(schemaClass.getSimpleName()) .renameField("testField", "oldTestField") .addField("testField", Long.class); } }; RealmConfiguration config = configFactory.createConfigurationBuilder() .schema(schemaClass) .schemaVersion(2) .migration(migration) .assetFile("rename-and-add-indexed.realm") .build(); realm = Realm.getInstance(config); realm.beginTransaction(); MigrationIndexedFieldRenamed obj = realm.createObject(schemaClass, 2); obj.oldTestField = oldTestVal; obj.testField = testVal; realm.commitTransaction(); RealmObjectSchema schema = realm.getSchema().get(schemaClass.getSimpleName()); assertTrue(schema.hasField("testField")); assertTrue(schema.hasField("oldTestField")); assertTrue(schema.hasIndex("oldTestField")); RealmResults<MigrationIndexedFieldRenamed> result = realm.where(schemaClass).equalTo("id", 2).findAll(); assertEquals("There should be an object with PK=2", 1, result.size()); assertEquals("Unexpected oldTestField value", oldTestVal, result.first().oldTestField); assertEquals("Unexpected testField value", testVal, result.first().testField); realm.close(); }
Source:
public void close() { logger.debug("Closing connection to broker '{}'", name); try { if (started) { client.disconnect(); } } catch (MqttException e) { logger.error(String.format("Error closing connection to broker '{}'", name), e); } started = false; }

Target:
public void close() { logger.debug("Closing connection to broker '{}'", name); try { if (started) { client.disconnect(); } } catch (MqttException e) { logger.error("Error closing connection to broker", e); } started = false; }
Source:
public Object convert(Object value) { Object convertedValue; if (isInstanceOfMultiValue(value)) { convertedValue = convertMultiValue(value); } else if (isInstanceOfMap(value)) { convertedValue = convertMap(value); } else if (isInstanceOfRecord(value)) { convertedValue = convertRecord(value); } else { convertedValue = convertSingleValue(value); } return convertedValue; }

Target:
public Object convert(Object value) { Object convertedValue; if (isMultiValue(value)) { convertedValue = convertMultiValue(value); } else if (isMap(value)) { convertedValue = convertMap(value); } else if (isRecord(value)) { convertedValue = convertRecord(value); } else { convertedValue = convertSingleValue(value); } return convertedValue; }
Source:
public PlanningErrorException(Throwable e) { super(e.getCause()); }

Target:
public PlanningErrorException(Throwable e) { super(e); }
Source:
public boolean verifyOrder(String[] testNames) throws IllegalArgumentException { int testIndex = 0; int testLength = testNames.length; if (testLength == 0) return true; for (int nX = 0; nX < methodList.size(); nX++) { String methodName = methodList.get(nX); String testName = testNames[testIndex]; testMethodName(testName); if (testName.equals(methodName)) ++testIndex; if (testIndex >= testLength) return true; } return false; }

Target:
public boolean verifyOrder(String[] testNames) throws IllegalArgumentException { int testIndex = 0; int testLength = testNames.length; if (testLength == 0) return true; for (String methodName : methodList) { String testName = testNames[testIndex]; testMethodName(testName); if (testName.equals(methodName)) ++testIndex; if (testIndex >= testLength) return true; } return false; }
Source:
public FileStatus getFileStatus(Path path) throws IOException { if (files.containsKey(path)) { return generateURIStatus(path, files.get(path).length); } else { throw new FileNotFoundException(path.toString()); } }

Target:
public FileStatus getFileStatus(Path path) { if (files.containsKey(path)) { return generateURIStatus(path, files.get(path).length); } return null; }
Source:
public void testSwapRefAlt(final VariantContext swapMe, final VariantContext expected) throws Exception { VcfTestUtils.assertEquals(LiftoverUtils.swapRefAlt(swapMe, annotationsToSwap, annotationsToDrop), expected); }

Target:
public void testSwapRefAlt(final VariantContext swapMe, final VariantContext expected) { VcfTestUtils.assertEquals(LiftoverUtils.swapRefAlt(swapMe, annotationsToSwap, annotationsToDrop), expected); }
Source:
public boolean isValid(String type, ConstraintValidatorContext context) { boolean isValid = catalog.isSupported(type); if (!isValid) { context.buildConstraintViolationWithTemplate("unsupported operation"); } return isValid; }

Target:
public boolean isValid(String type, ConstraintValidatorContext context) { boolean isValid = catalog.isSupported(type); if (!isValid) { String message = context.getDefaultConstraintMessageTemplate(); context.buildConstraintViolationWithTemplate(message); } return isValid; }
Source:
private void updateOverlayCoverageLayer(int zoomLevel) { final List<Overlay> overlays = mMap.getOverlays(); if (mCoverageTilesOverlayLowZoom == null || mCoverageTilesOverlayHighZoom == null || zoomLevel < CoverageOverlay.LOW_ZOOM_LEVEL) { if (mCoverageTilesOverlayDefaultZoom != null && !overlays.contains(mCoverageTilesOverlayDefaultZoom)) { overlays.remove(mCoverageTilesOverlayLowZoom); overlays.remove(mCoverageTilesOverlayHighZoom); overlays.add(0, mCoverageTilesOverlayDefaultZoom); mMap.invalidate(); } return; } final Overlay overlayRemoved = (!isHighZoom(zoomLevel)) ? mCoverageTilesOverlayHighZoom : mCoverageTilesOverlayLowZoom; final Overlay overlayAdded = (isHighZoom(zoomLevel)) ? mCoverageTilesOverlayHighZoom : mCoverageTilesOverlayLowZoom; overlays.remove(overlayRemoved); overlays.remove(mCoverageTilesOverlayDefaultZoom); if (!overlays.contains(overlayAdded)) { boolean hasMapOverlay = overlays.contains(mLowResMapOverlayHighZoom) || overlays.contains(mLowResMapOverlayLowZoom); int idx = hasMapOverlay ? 1 : 0; overlays.add(idx, overlayAdded); mMap.invalidate(); } }

Target:
private void updateOverlayCoverageLayer(int zoomLevel) { if (mCoverageTilesOverlayLowZoom == null || mCoverageTilesOverlayHighZoom == null || mCoverageTilesOverlayOriginalZoom == null) { return; } final List<Overlay> overlays = mMap.getOverlays(); if (zoomLevel < CoverageOverlay.LOW_ZOOM_LEVEL) { if (!overlays.contains(mCoverageTilesOverlayOriginalZoom)) { overlays.remove(mCoverageTilesOverlayLowZoom); overlays.remove(mCoverageTilesOverlayHighZoom); overlays.add(0, mCoverageTilesOverlayOriginalZoom); mMap.invalidate(); } return; } final Overlay overlayRemoved = (!isHighZoom(zoomLevel)) ? mCoverageTilesOverlayHighZoom : mCoverageTilesOverlayLowZoom; final Overlay overlayAdded = (isHighZoom(zoomLevel)) ? mCoverageTilesOverlayHighZoom : mCoverageTilesOverlayLowZoom; overlays.remove(overlayRemoved); overlays.remove(mCoverageTilesOverlayOriginalZoom); if (!overlays.contains(overlayAdded)) { boolean hasMapOverlay = overlays.contains(mLowResMapOverlayHighZoom) || overlays.contains(mLowResMapOverlayLowZoom); int idx = hasMapOverlay ? 1 : 0; overlays.add(idx, overlayAdded); mMap.invalidate(); } }
Source:
public void changeProjectFeatureFlag() throws Exception { boolean value = false; final FeatureFlagService featureFlagService = gd.getFeatureFlagService(); ProjectFeatureFlag featureFlag = featureFlagService.getProjectFeatureFlag(project, PROJECT_FEATURE_FLAG); featureFlag.setEnabled(value); featureFlagService.updateProjectFeatureFlag(featureFlag); int count = 0; while (count++ < 20) { featureFlag = featureFlagService.getProjectFeatureFlag(project, PROJECT_FEATURE_FLAG); checkProjectFeatureFlag(featureFlag, PROJECT_FEATURE_FLAG, value); value = !value; featureFlag.setEnabled(value); featureFlagService.updateProjectFeatureFlag(featureFlag); } }

Target:
public void changeProjectFeatureFlag() throws Exception { final FeatureFlagService featureFlagService = gd.getFeatureFlagService(); ProjectFeatureFlag featureFlag = featureFlagService.getProjectFeatureFlag(project, PROJECT_FEATURE_FLAG); boolean value = !featureFlag.isEnabled(); featureFlag.setEnabled(value); featureFlagService.updateProjectFeatureFlag(featureFlag); checkProjectFeatureFlag(featureFlag, PROJECT_FEATURE_FLAG, value); }
Source:
public void process() { PerformanceMonitor.startActivity("rendering/backdrop"); FBO sceneOpaqueFbo = displayResolutionDependentFBOs.get(new ResourceUrn("engine:sceneOpaque")); sceneOpaqueFbo.bind(); sceneOpaqueFbo.setRenderBufferMask(true, false, false); glCallList(skySphere); sceneOpaqueFbo.setRenderBufferMask(true, true, true); PerformanceMonitor.endActivity(); }

Target:
public void process() { PerformanceMonitor.startActivity("rendering/backdrop"); sceneOpaqueFbo.bind(); sceneOpaqueFbo.setRenderBufferMask(true, false, false); glCallList(skySphere); sceneOpaqueFbo.setRenderBufferMask(true, true, true); PerformanceMonitor.endActivity(); }
Source:
private void fetchNextIfNeeded() { if (!isNextFetched) { isNextFetched = true; if (next == null) { next = isAscending ? range.getFrom() : range.getTo(); } else { next = isAscending ? increment(next) : decrement(next); } } }

Target:
private void fetchNextIfNeeded() { if (!isNextFetched) { isNextFetched = true; if (next == null) { next = isAscending ? range.getFrom() : range.getTo(); } else { next = isAscending ? increment(next, step) : decrement(next, step); } } }
Source:
public void process(Exchange exchange) { String issueKey = exchange.getIn().getHeader(ISSUE_KEY, String.class); if (issueKey == null) { throw new IllegalArgumentException("Missing exchange input header named " + ISSUE_KEY); } JiraRestClient client = ((JiraEndpoint) getEndpoint()).getClient(); IssueRestClient issueClient = client.getIssueClient(); Issue issue = issueClient.getIssue(issueKey).claim(); if (exchange.getPattern().isOutCapable()) { exchange.getOut().copyFrom(exchange.getIn()); exchange.getOut().setBody(issue); } else { exchange.getIn().setBody(issue); } }

Target:
public void process(Exchange exchange) { String issueKey = exchange.getIn().getHeader(ISSUE_KEY, String.class); if (issueKey == null) { throw new IllegalArgumentException("Missing exchange input header named " + ISSUE_KEY); } JiraRestClient client = ((JiraEndpoint) getEndpoint()).getClient(); IssueRestClient issueClient = client.getIssueClient(); Issue issue = issueClient.getIssue(issueKey).claim(); exchange.getMessage().setBody(issue); }
Source:
public ResponseEntity<List<DownloadBundleDTO>> getDownloadHistory(Principal principal) throws PermissionDeniedException { final AthenaUser user = userService.getUser(principal); return ResponseEntity.ok(vocabularyService.getDownloadHistory(user.getId())); }

Target:
public List<DownloadBundleDTO> getDownloadHistory(Principal principal) throws PermissionDeniedException { final AthenaUser user = userService.getUser(principal); return vocabularyService.getDownloadHistory(user.getId()); }
Source:
public void rm(String key) throws IOException { key = key.replace(" ", ""); zkState.delete(key); }

Target:
public void rm(String key) throws IOException { zkState.delete(key); }
Source:
public Response toolsIndexSearch(String query, MultivaluedMap<String, String> queryParameters, SecurityContext securityContext) { if (!config.getEsConfiguration().getHostname().isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { HttpEntity entity = query == null ? null : new NStringEntity(query, ContentType.APPLICATION_JSON); Map<String, String> parameters = new HashMap<>(); if (queryParameters != null) { queryParameters.forEach((key, value) -> parameters.put(key, value.get(0))); } org.elasticsearch.client.Response get = restClient.performRequest("GET", "/entry/_search", parameters, entity); if (get.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new CustomWebApplicationException("Could not submit index to elastic search", HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(get.getEntity().getContent()).build(); } catch (ResponseException e) { int[] codesToResurface = {HttpStatus.SC_BAD_REQUEST}; int statusCode = e.getResponse().getStatusLine().getStatusCode(); if (ArrayUtils.contains(codesToResurface, statusCode)) { throw new CustomWebApplicationException(e.getMessage(), statusCode); } else { throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e2) { throw new CustomWebApplicationException(e2.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } return Response.ok().entity(0).build(); }

Target:
public Response toolsIndexSearch(String query, MultivaluedMap<String, String> queryParameters, SecurityContext securityContext) { if (!config.getEsConfiguration().getHostname().isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { HttpEntity entity = query == null ? null : new NStringEntity(query, ContentType.APPLICATION_JSON); Map<String, String> parameters = new HashMap<>(); if (queryParameters != null) { queryParameters.forEach((key, value) -> parameters.put(key, value.get(0))); } org.elasticsearch.client.Response get = restClient.performRequest("GET", "/entry/_search", parameters, entity); if (get.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new CustomWebApplicationException("Could not submit index to elastic search", HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(get.getEntity().getContent()).build(); } catch (ResponseException e) { int[] codesToResurface = {HttpStatus.SC_BAD_REQUEST}; int statusCode = e.getResponse().getStatusLine().getStatusCode(); LOG.error("Could not use Elasticsearch search", e); if (ArrayUtils.contains(codesToResurface, statusCode)) { throw new CustomWebApplicationException(e.getMessage(), statusCode); } else { throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e2) { LOG.error("Could not use Elasticsearch search", e2); throw new CustomWebApplicationException(e2.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } return Response.ok().entity(0).build(); }
Source:
private void updateQuerySource(BrokerRequest brokerRequest) { String tableName = brokerRequest.getQuerySource().getTableName(); String[] querySourceSplits = tableName.split("\\.", 2); if (querySourceSplits.length != 2) { return; } if (_enableCaseInsensitive && _tableCache.existTableName(querySourceSplits[1]) && !_tableCache .existTableName(tableName)) { brokerRequest.getQuerySource().setTableName(querySourceSplits[1]); return; } TableType tableType = TableNameBuilder.getTableTypeFromTableName(tableName); if (tableType != null && _routingManager.routingExists(querySourceSplits[1]) && !_routingManager .routingExists(tableName)) { brokerRequest.getQuerySource().setTableName(querySourceSplits[1]); return; } if (_routingManager.routingExists(TableNameBuilder.REALTIME.tableNameWithType(querySourceSplits[1])) && !_routingManager.routingExists(TableNameBuilder.REALTIME.tableNameWithType(tableName))) { brokerRequest.getQuerySource().setTableName(querySourceSplits[1]); return; } if (_routingManager.routingExists(TableNameBuilder.OFFLINE.tableNameWithType(querySourceSplits[1])) && !_routingManager.routingExists(TableNameBuilder.OFFLINE.tableNameWithType(tableName))) { brokerRequest.getQuerySource().setTableName(querySourceSplits[1]); } }

Target:
private void updateQuerySource(BrokerRequest brokerRequest) { String tableName = brokerRequest.getQuerySource().getTableName(); String[] tableNameSplits = StringUtils.split(tableName, '.'); if (tableNameSplits.length != 2) { return; } if (_enableCaseInsensitive) { if (_tableCache.containsTable(tableNameSplits[1]) && !_tableCache.containsTable(tableName)) { brokerRequest.getQuerySource().setTableName(tableNameSplits[1]); } return; } if (TableNameBuilder.isTableResource(tableName)) { if (_routingManager.routingExists(tableNameSplits[1]) && !_routingManager.routingExists(tableName)) { brokerRequest.getQuerySource().setTableName(tableNameSplits[1]); } return; } if (_routingManager.routingExists(TableNameBuilder.REALTIME.tableNameWithType(tableNameSplits[1])) && !_routingManager.routingExists(TableNameBuilder.REALTIME.tableNameWithType(tableName))) { brokerRequest.getQuerySource().setTableName(tableNameSplits[1]); return; } if (_routingManager.routingExists(TableNameBuilder.OFFLINE.tableNameWithType(tableNameSplits[1])) && !_routingManager.routingExists(TableNameBuilder.OFFLINE.tableNameWithType(tableName))) { brokerRequest.getQuerySource().setTableName(tableNameSplits[1]); } }
Source:
public void visitNode(AstNode node) { if (CheckUtils.isMethodDefinition(node) && !alreadyStaticMethod(node) && hasValuableCode(node)){ String self = getFirstArgument(node); if (self != null && !isUsed(node, self) &&!isDocStringsAndNotImplementedError(node)){ getContext().createLineViolation(this, MESSAGE, node.getFirstChild(PythonGrammar.FUNCNAME)); } } }

Target:
public void visitNode(AstNode node) { if (CheckUtils.isMethodDefinition(node) && !alreadyStaticMethod(node) && hasValuableCode(node)){ String self = getFirstArgument(node); if (self != null && !isUsed(node, self) && !onlyRaisesNotImplementedError(node)){ getContext().createLineViolation(this, MESSAGE, node.getFirstChild(PythonGrammar.FUNCNAME)); } } }
Source:
public ExecutionResult execute(final TaskConfig config, final TaskExecutionContext taskExecutionContext) { return pluginRequestHelper.submitRequest(pluginId, JsonBasedTaskExtension.EXECUTION_REQUEST, new PluginInteractionCallback<ExecutionResult>() { @Override public String requestBody(String resolvedExtensionVersion) { return handlerMap.get(resolvedExtensionVersion).getTaskExecutionBody(config, taskExecutionContext); } @Override public Map<String, Object> requestParams(String resolvedExtensionVersion) { final LinkedHashMap params = new LinkedHashMap(); params.put("console", new ConsoleWrapper(taskExecutionContext)); return params; } @Override public ExecutionResult onSuccess(String responseBody, String resolvedExtensionVersion) { return handlerMap.get(resolvedExtensionVersion).toExecutionResult(responseBody); } }); }

Target:
public ExecutionResult execute(final TaskConfig config, final TaskExecutionContext taskExecutionContext) { return pluginRequestHelper.submitRequest(pluginId, JsonBasedTaskExtension.EXECUTION_REQUEST, new PluginInteractionCallback<ExecutionResult>() { @Override public String requestBody(String resolvedExtensionVersion) { return handlerMap.get(resolvedExtensionVersion).getTaskExecutionBody(config, taskExecutionContext); } @Override public Map<String, String> requestParams(String resolvedExtensionVersion) { return null; } @Override public ExecutionResult onSuccess(String responseBody, String resolvedExtensionVersion) { return handlerMap.get(resolvedExtensionVersion).toExecutionResult(responseBody); } }); }
Source:
public static IndexWriterConfig population() { IndexWriterConfig writerConfig = standard(); writerConfig.setMaxBufferedDocs( POPULATION_MAX_BUFFERED_DOCS ); writerConfig.setRAMBufferSizeMB( POPULATION_RAM_BUFFER_SIZE_MB ); return writerConfig; }

Target:
public static IndexWriterConfig population() { Analyzer analyzer = LuceneDataSource.KEYWORD_ANALYZER; return population( analyzer ); }
Source:
private void addBootstrap3And4Style( String bootstrap3FileName, InputStream bootstrap3Data, Resource bootstrap4resource) { try (InputStream bootstrap4Data = bootstrap4resource.getInputStream()) { String bootstrap4FileName = bootstrap4resource.getFilename(); LOG.debug("Adding matching bootstrap 4 theme with name {}", bootstrap4FileName); styleService.addStyle( bootstrap3FileName, bootstrap3FileName, bootstrap3Data, bootstrap4FileName, bootstrap4Data); } catch (IOException e) { LOG.error("error adding new bootstrap 4 theme", e); } }

Target:
private void addBootstrap3And4Style( String bootstrap3FileName, InputStream bootstrap3Data, Resource bootstrap4resource) { try (InputStream bootstrap4Data = bootstrap4resource.getInputStream()) { String bootstrap4FileName = bootstrap4resource.getFilename(); LOG.debug("Adding matching bootstrap 4 theme with name {}", bootstrap4FileName); styleService.addStyle( bootstrap3FileName, bootstrap3FileName, bootstrap3Data, bootstrap4FileName, bootstrap4Data); } catch (Exception e) { LOG.error("error adding new bootstrap 4 theme", e); } }
Source:
public ProvisionAdviceHolder(Binding<T> binding, AdviceElementImpl element) { Method member = (Method)element.injectionPoint.getMember(); this.order = Optional.ofNullable(member.getAnnotation(Order.class)).map(order -> order.value()).orElse(1000); this.binding = binding; }

Target:
public ProvisionAdviceHolder(Binding<T> binding, AdviceElementImpl element) { this.order = ((Advises)(element.getQualifier())).order(); this.binding = binding; }
Source:
private void verifyNotEmpty(String name, String value) throws ConfigurationException { if (org.apache.commons.lang.StringUtils.isEmpty(value)) { throw new ConfigurationException("Unable to find " + name); } }

Target:
private void verifyNotEmpty(String name, String value) throws ConfigurationException { if (StringUtils.isEmpty(value)) { throw new ConfigurationException("Unable to find " + name); } }
Source:
public void MessageWall_008_blockedUserPostsOnHisWall() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialBlockListPageObject blockListPage = base.openSpecialBlockListPage(wikiURL); boolean ifUserBlocked = blockListPage.ifUserIsBlocked(credentials.userNameBlockedAccount); if (!ifUserBlocked) { base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialBlockPageObject blockPage = base.openSpecialBlockPage(wikiURL); blockPage.typeInUserName(credentials.userNameBlockedAccount); blockPage.typeExpiration("10 year"); blockPage.typeReason("block QATestsBlockedUser"); blockPage.clickBlockButton(); } base.logInCookie(credentials.userNameBlockedAccount, credentials.passwordBlockedAccount, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userNameBlockedAccount, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.messageWallMessagePrefix + wall.getTimeStamp(); String title = PageContent.messageWallTitlePrefix+ wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userName); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.messageWallQuotePrefix + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply);; wall.submitQuote(); wall.verifyQuote(reply); }

Target:
public void MessageWall_008_blockedUserPostsOnHisWall() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialBlockListPageObject blockListPage = base.openSpecialBlockListPage(wikiURL); boolean isUserBlocked = blockListPage.isUserBlocked(credentials.userNameBlockedAccount); if (!isUserBlocked) { base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialBlockPageObject blockPage = base.openSpecialBlockPage(wikiURL); blockPage.typeInUserName(credentials.userNameBlockedAccount); blockPage.typeExpiration("10 year"); blockPage.typeReason("block QATestsBlockedUser"); blockPage.clickBlockButton(); } base.logInCookie(credentials.userNameBlockedAccount, credentials.passwordBlockedAccount, wikiURL); NewMessageWall wall = base.openMessageWall(credentials.userNameBlockedAccount, wikiURL); MiniEditorComponentObject mini = wall.triggerMessageArea(); String message = PageContent.messageWallMessagePrefix + wall.getTimeStamp(); String title = PageContent.messageWallTitlePrefix+ wall.getTimeStamp(); mini.switchAndWrite(message); wall.writeTitle(title); wall.submit(); wall.verifyMessageText(title, message, credentials.userNameBlockedAccount); MiniEditorComponentObject miniReply = wall.triggerReplyMessageArea(); String reply = PageContent.messageWallQuotePrefix + wall.getTimeStamp(); miniReply.switchAndQuoteMessageWall(reply); wall.submitQuote(); wall.verifyQuote(reply); }
Source:
public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { try { return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } } }

Target:
public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } }
Source:
private static List<Page> pullAvailablePages(Operator operator) throws InterruptedException { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); List<Page> outputPages = new ArrayList<>(); boolean unblocked = false; while (System.nanoTime() < endTime) { if (operator.isFinished()) { break; } if (operator.isBlocked().isDone()) { unblocked = true; break; } else { Thread.sleep(10); } } assertTrue(unblocked); while (operator.isBlocked().isDone() && System.nanoTime() < endTime) { assertEquals(operator.needsInput(), false); if (operator.isFinished()) { break; } Page outputPage = operator.getOutput(); if (outputPage != null) { outputPages.add(outputPage); } else { Thread.sleep(10); } } assertEquals(operator.needsInput(), false); assertNull(operator.getOutput()); return outputPages; }

Target:
private static List<Page> pullAvailablePages(Operator operator) throws InterruptedException { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(1); List<Page> outputPages = new ArrayList<>(); assertOperatorIsUnblocked(operator); while (operator.isBlocked().isDone() && System.nanoTime() < endTime) { assertEquals(operator.needsInput(), false); if (operator.isFinished()) { break; } Page outputPage = operator.getOutput(); if (outputPage != null) { outputPages.add(outputPage); } else { Thread.sleep(10); } } assertEquals(operator.needsInput(), false, "Operator still wants input"); assertNull(operator.getOutput(), "Not finished pulling pages"); return outputPages; }
Source:
public void set(@NonNull final MainPageCard card) { setTitle(String.format(getString(R.string.view_main_page_card_title), WikipediaApp.getInstance().getAppLanguageLocalizedName(card.site().languageCode()))); setSubtitle(String.format(getString(R.string.view_main_page_card_subtitle), DateFormat.getDateInstance().format(new Date()))); setIcon(R.drawable.icon_feed_today); setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (callback != null) { callback.onSelectPage(new PageTitle(MainPageNameData .valueFor(app.getAppOrSystemLanguageCode()), app.getSite())); } } }); }

Target:
public void set(@NonNull final MainPageCard card) { setTitle(String.format(getString(R.string.view_main_page_card_title), WikipediaApp.getInstance().getAppLanguageLocalizedName(card.site().languageCode()))); setSubtitle(String.format(getString(R.string.view_main_page_card_subtitle), DateFormat.getDateInstance().format(new Date()))); setIcon(R.drawable.icon_today_48_x_48_dp); setOnClickListener(new CallbackAdapter(callback)); }
Source:
public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { if (event.character == SWT.ESC) cancelPressed(); } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); }

Target:
public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { if (event.character == SWT.ESC) { cancelPressed(); } } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); }
Source:
public void start(Map<String, String> props) { logger.info("Starting"); try { apiName = props.get("apiName"); apiObj = IOTestUtil.readApi(apiName); scriptPath = IOTestUtil.getScriptPath(apiObj); apiPath = IOTestUtil.getApiPath(scriptPath); IOTestUtil.load(apiName, apiObj, scriptPath, apiPath); String forestName = props.get("forestName"); String endpointState = "{\"next\":"+1+"}"; String workUnit = "{\"limit\":"+100+"}"+"{\"forestName\":"+forestName+"}"; bulkCaller = OutputEndpoint.on(IOTestUtil.db, new JacksonHandle(apiObj)).bulkCaller(); bulkCaller.setEndpointState(new ByteArrayInputStream(endpointState.getBytes())); bulkCaller.setWorkUnit(new ByteArrayInputStream(workUnit.getBytes())); sourceOffset = 0; } catch (Exception ex) { ex.printStackTrace(); } }

Target:
public void start(Map<String, String> props) { logger.info("*******************Starting******************"); try { apiName = props.get("apiName"); apiObj = IOTestUtil.readApi(apiName); scriptPath = IOTestUtil.getScriptPath(apiObj); apiPath = IOTestUtil.getApiPath(scriptPath); IOTestUtil.load(apiName, apiObj, scriptPath, apiPath); String forestName = props.get("forestName"); String endpointState = "{\"next\":"+1+"}"; String workUnit = "{\"limit\":"+100+"}"+"{\"forestName\":"+forestName+"}"; bulkCaller = OutputEndpoint.on(IOTestUtil.db, new JacksonHandle(apiObj)).bulkCaller(); bulkCaller.setEndpointState(new ByteArrayInputStream(endpointState.getBytes())); bulkCaller.setWorkUnit(new ByteArrayInputStream(workUnit.getBytes())); sourceOffset = 0; } catch (Exception ex) { ex.printStackTrace(); } }
Source:
public static CodedValueType createCodeValueType(String code, String codeSys, String codeSysName, String dispName) { CodedValueType codeValueType = new CodedValueType(); if (NullChecker.isNotNullish(code)) { codeValueType.setCode(code); } if (NullChecker.isNotNullish(codeSys)) { codeValueType.setCodeSystem(codeSys); } if (NullChecker.isNotNullish(codeSysName)) { codeValueType.setCodeSystemName(codeSysName); } if (NullChecker.isNotNullish(dispName)) { codeValueType.setDisplayName(dispName); } return codeValueType; }

Target:
private static CodedValueType createCodeValueType(String code, String codeSys, String codeSysName, String dispName) { CodedValueType codeValueType = new CodedValueType(); if (NullChecker.isNotNullish(code)) { codeValueType.setCode(code); } if (NullChecker.isNotNullish(codeSys)) { codeValueType.setCodeSystem(codeSys); } if (NullChecker.isNotNullish(codeSysName)) { codeValueType.setCodeSystemName(codeSysName); } if (NullChecker.isNotNullish(dispName)) { codeValueType.setDisplayName(dispName); } return codeValueType; }
Source:
void validateBonds(VdsNetworkInterface nicWithUnmanagedNetwork, List<Bond> newOrModifiedBonds, BusinessEntityMap<VdsNetworkInterface> existingInterfacesMap) throws ValidationException{ for(Bond newOrModifiedBond:newOrModifiedBonds){ VdsNetworkInterface existingInterface = existingInterfacesMap.get(newOrModifiedBond.getName()); boolean doesInterfaceExist = existingInterface != null; if (doesInterfaceExist){ Bond existingBond = (Bond) existingInterface; Collection<String> addedSlaves = computeAddedSlaves(newOrModifiedBond.getSlaves(), existingBond.getSlaves()); checkIfSlaveWithUnmanagedNetworkIsAddedToBond(nicWithUnmanagedNetwork, newOrModifiedBond, addedSlaves); checkIfSlaveIsAddedToBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond, existingBond, addedSlaves); }else{ checkNewBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond); } } }

Target:
ValidationResult validateBonds(VdsNetworkInterface nicWithUnmanagedNetwork, List<Bond> newOrModifiedBonds, BusinessEntityMap<VdsNetworkInterface> existingInterfacesMap) { for(Bond newOrModifiedBond : newOrModifiedBonds){ VdsNetworkInterface existingInterface = existingInterfacesMap.get(newOrModifiedBond.getName()); boolean doesInterfaceExist = existingInterface != null; if (doesInterfaceExist){ Bond existingBond = (Bond) existingInterface; Collection<String> addedSlaves = computeAddedSlaves(newOrModifiedBond.getSlaves(), existingBond.getSlaves()); ValidationResult result = checkIfSlaveWithUnmanagedNetworkIsAddedToBond(nicWithUnmanagedNetwork, newOrModifiedBond, addedSlaves); if (!result.isValid()) { return result; } result = checkIfSlaveIsAddedToBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond, existingBond, addedSlaves); if (!result.isValid()) { return result; } } else { ValidationResult result = checkNewBondWithUnmanagedNetwork(nicWithUnmanagedNetwork, newOrModifiedBond); if (!result.isValid()) { return result; } } } return ValidationResult.VALID; }
Source:
public void start(BundleContext context) throws Exception { final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); System.out.println("Starting activator " + this + " in bundle " + context.getBundle() + " ..."); ServiceReference serviceRef = context.getServiceReference(HazelcastOSGiService.class.getName()); if (serviceRef == null) { throw new IllegalStateException("There is no registered `HazelcastOSGiService`!"); } HazelcastOSGiService hazelcastOsgiService = (HazelcastOSGiService) context.getService(serviceRef); HazelcastOSGiInstance defaultInstance = hazelcastOsgiService.getDefaultHazelcastInstance(); HazelcastOSGiInstance newInstance1 = hazelcastOsgiService.newHazelcastInstance(); Config config = new Config(); config.setInstanceName("OSGI-Instance"); HazelcastOSGiInstance newInstance2 = hazelcastOsgiService.newHazelcastInstance(config); HazelcastOSGiInstance instance = hazelcastOsgiService.getHazelcastInstanceByName("OSGI-Instance"); hazelcastOsgiService.shutdownHazelcastInstance(instance); for (HazelcastOSGiInstance osgiInstance : hazelcastOsgiService.getAllHazelcastInstances()) { System.out.println(osgiInstance); } hazelcastOsgiService.shutdownAll(); } finally { Thread.currentThread().setContextClassLoader(currentContextClassLoader); } }

Target:
public void start(BundleContext context) throws Exception { System.out.println("Starting activator " + this + " in bundle " + context.getBundle() + " ..."); ServiceReference serviceRef = context.getServiceReference(HazelcastOSGiService.class.getName()); if (serviceRef == null) { throw new IllegalStateException("There is no registered `HazelcastOSGiService`!"); } HazelcastOSGiService hazelcastOsgiService = (HazelcastOSGiService) context.getService(serviceRef); HazelcastOSGiInstance defaultInstance = hazelcastOsgiService.getDefaultHazelcastInstance(); HazelcastOSGiInstance newInstance1 = hazelcastOsgiService.newHazelcastInstance(); Config config = new Config(); config.setInstanceName("OSGI-Instance"); HazelcastOSGiInstance newInstance2 = hazelcastOsgiService.newHazelcastInstance(config); HazelcastOSGiInstance instance = hazelcastOsgiService.getHazelcastInstanceByName("OSGI-Instance"); hazelcastOsgiService.shutdownHazelcastInstance(instance); for (HazelcastOSGiInstance osgiInstance : hazelcastOsgiService.getAllHazelcastInstances()) { System.out.println(osgiInstance); } hazelcastOsgiService.shutdownAll(); }