auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void changeCacheGroupKeyLocal(int[] grpIds, byte[] keyIds, byte[][] keys) throws IgniteCheckedException { Map<Integer, Byte> encryptionStatus = U.newHashMap(grpIds.length); for (int i = 0; i < grpIds.length; i++) encryptionStatus.put(grpIds[i], keyIds[i]); WALPointer ptr = ctx.cache().context().wal().log(new ReencryptionStatusRecord(encryptionStatus)); if (ptr != null) ctx.cache().context().wal().flush(ptr, false); for (int i = 0; i < grpIds.length; i++) { int grpId = grpIds[i]; CacheGroupContext grp = ctx.cache().cacheGroup(grpId); if (grp == null) continue; GroupKeyEncrypted key = new GroupKeyEncrypted(keyIds[i] & 0xff, keys[i]); synchronized (metaStorageMux) { grpKeys.addKey(grpId, key); writeToMetaStore(grpId, true, false); GroupKey prevGrpKey = grpKeys.changeActiveKey(grpId, key); assert prevGrpKey != null && prevGrpKey.id() != key.id() : "prev=" + prevGrpKey + ", currId=" + key.id(); grpKeys.reserveWalKey(grpId, prevGrpKey.unsignedId(), ctx.cache().context().wal().currentSegment()); writeToMetaStore(grpId, true, true); } reencryptGroups.put(grpId, pageScanner.pagesCount(grp)); if (log.isInfoEnabled()) log.info("New encryption key for group was added [grpId=" + grpId + ", keyId=" + key.id() + "]"); } startReencryption(encryptionStatus.keySet()); }

Target:
protected void changeCacheGroupKeyLocal(int[] grpIds, byte[] keyIds, byte[][] keys) throws IgniteCheckedException { Map<Integer, Byte> encryptionStatus = U.newHashMap(grpIds.length); for (int i = 0; i < grpIds.length; i++) encryptionStatus.put(grpIds[i], keyIds[i]); WALPointer ptr = ctx.cache().context().wal().log(new ReencryptionStartRecord(encryptionStatus)); if (ptr != null) ctx.cache().context().wal().flush(ptr, false); for (int i = 0; i < grpIds.length; i++) { int grpId = grpIds[i]; int newKeyId = keyIds[i] & 0xff; withMasterKeyChangeReadLock(() -> { synchronized (metaStorageMux) { GroupKey prevGrpKey = grpKeys.changeActiveKey(grpId, newKeyId); writeGroupKeysToMetaStore(grpId, grpKeys.getAll(grpId)); if (ptr == null) return null; grpKeys.reserveWalKey(grpId, prevGrpKey.unsignedId(), ctx.cache().context().wal().currentSegment()); writeTrackedWalIdxsToMetaStore(); } return null; }); CacheGroupContext grp = ctx.cache().cacheGroup(grpId); if (grp != null && grp.affinityNode()) reencryptGroups.put(grpId, pageScanner.pagesCount(grp)); if (log.isInfoEnabled()) log.info("New encryption key for group was added [grpId=" + grpId + ", keyId=" + newKeyId + "]"); } startReencryption(encryptionStatus.keySet()); }
Source:
public List<Report> getReports() { return new ArrayList<Report>(this.reports.values()); }

Target:
public Collection<Report> getReports() { return this.reports.values(); }
Source:
public void getDescription_NoAnnotations() throws NoSuchMethodException { String actualResult = getDescriptionWithMethodNameAndParamIndex(TEST_METHOD_10, FIRST_INDEX); assertEquals(PARAMETER_INFO_DESCRIPTION, actualResult); }

Target:
public void getDescription_NoAnnotations() throws NoSuchMethodException { String actualRes = getDescriptionWithMethodNameAndParamIndex(TEST_METHOD_10, FIRST_INDEX); assertEquals(PARAMETER_INFO_DESCRIPTION, actualRes); }
Source:
void verifyClosureExpressionBraceStyle(ClosureExpressionContext ctx) { ParseTree left = ParseTreeUtil.getLeftNode(ctx); if (left == null) { return; } Location leftLocation; if (left instanceof TerminalNodeImpl) { Token leftToken = ((TerminalNodeImpl) left).getSymbol(); leftLocation = ListenerUtil.getTokenLocation(leftToken); } else { ParserRuleContext leftContext = (ParserRuleContext) left; leftLocation = ListenerUtil.getContextStopLocation(leftContext); } verifyCodeBlockOpenBraceIsInline(ctx, leftLocation, Messages.CLOSURE); ParseTree leftSibling = ParseTreeUtil.getLeftSibling(ctx); if (leftSibling != null && (leftSibling instanceof ParenthesizedExpressionContext || leftSibling instanceof PostfixExpressionContext)) { Token leftToken = ((ParserRuleContext) leftSibling).getStop(); verifySingleSpaceBeforeOpenBrace(ctx, leftToken); } }

Target:
void verifyClosureExpressionBraceStyle(ClosureExpressionContext ctx) { ParseTree left = ParseTreeUtil.getLeftNode(ctx); if (left == null) { return; } Location leftLocation = ListenerUtil.getTokenLocation(ParseTreeUtil.getStopTokenForNode(left)); verifyCodeBlockOpenBraceIsInline(ctx, leftLocation, Messages.CLOSURE); ParseTree leftSibling = ParseTreeUtil.getLeftSibling(ctx); if (leftSibling != null && (leftSibling instanceof ParenthesizedExpressionContext || leftSibling instanceof PostfixExpressionContext)) { Token leftToken = ((ParserRuleContext) leftSibling).getStop(); verifySingleSpaceBeforeOpenBrace(ctx, leftToken); } }
Source:
public Task<Entity> newTask() { return TaskBuilder.<Entity>builder().name("component("+componentId+")").body(new Callable<Entity>() { @Override public Entity call() throws Exception { if (scope == Scope.THIS) return entity(); if (scope == Scope.PARENT) return entity().getParent(); Iterable<Entity> entitiesToSearch = null; if (scope == Scope.GLOBAL) entitiesToSearch = ((EntityManagerInternal)entity().getManagementContext().getEntityManager()) .getAllEntitiesInApplication( entity().getApplication() ); if (scope == Scope.DESCENDANT) { entitiesToSearch = Sets.newHashSet(); addDescendants(entity(), (Set<Entity>)entitiesToSearch); } if (scope == Scope.SIBLING) { entitiesToSearch = entity().getParent().getChildren(); } if (scope == Scope.CHILD) entitiesToSearch = entity().getChildren(); Optional<Entity> result = Iterables.tryFind(entitiesToSearch, new Predicate<Entity>() { @Override public boolean apply(Entity input) { return componentId.equals(input.getConfig(BrooklynCampConstants.PLAN_ID)); } }); if (result.isPresent()) return result.get(); throw new NoSuchElementException("No entity matching id " + componentId); } }).build(); }

Target:
public Task<Entity> newTask() { return TaskBuilder.<Entity>builder().name("component("+componentId+")").body(new Callable<Entity>() { @Override public Entity call() throws Exception { Iterable<Entity> entitiesToSearch = null; switch (scope) { case THIS: return entity(); case PARENT: return entity().getParent(); case GLOBAL: entitiesToSearch = ((EntityManagerInternal)entity().getManagementContext().getEntityManager()) .getAllEntitiesInApplication( entity().getApplication() ); break; case DESCENDANT: entitiesToSearch = Sets.newLinkedHashSet(); addDescendants(entity(), (Set<Entity>)entitiesToSearch); break; case SIBLING: entitiesToSearch = entity().getParent().getChildren(); break; case CHILD: entitiesToSearch = entity().getChildren(); } Optional<Entity> result = Iterables.tryFind(entitiesToSearch, EntityPredicates.configEqualTo(BrooklynCampConstants.PLAN_ID, componentId)); if (result.isPresent()) return result.get(); throw new NoSuchElementException("No entity matching id " + componentId); } }).build(); }
Source:
public void initialize() { viewModel = new CustomizeExternalFileTypesViewModel(); fileTypesTable.setItems(viewModel.getFileTypes()); fileTypesTableIconColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getIcon())); fileTypesTableNameColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getName())); fileTypesTableExtensionColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getExtension())); fileTypesTableTypeColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getMimeType())); fileTypesTableApplicationColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getOpenWithApplication())); fileTypesTableEditColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); fileTypesTableDeleteColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); new ValueTableCellFactory<ExternalFileType, JabRefIcon>() .withGraphic(JabRefIcon::getGraphicNode) .install(fileTypesTableIconColumn); new ValueTableCellFactory<ExternalFileType, Boolean>() .withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode()) .withOnMouseClickedEvent((type, none) -> event -> viewModel.edit(type, false)) .install(fileTypesTableEditColumn); new ValueTableCellFactory<ExternalFileType, Boolean>() .withGraphic(none -> IconTheme.JabRefIcons.REMOVE.getGraphicNode()) .withOnMouseClickedEvent((type, none) -> event -> viewModel.remove(type)) .install(fileTypesTableDeleteColumn); }

Target:
public void initialize() { viewModel = new CustomizeExternalFileTypesViewModel(); fileTypesTable.setItems(viewModel.getFileTypes()); fileTypesTableIconColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getIcon())); fileTypesTableNameColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getName())); fileTypesTableExtensionColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getExtension())); fileTypesTableTypeColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getMimeType())); fileTypesTableApplicationColumn.setCellValueFactory(data -> BindingsHelper.constantOf(data.getValue().getOpenWithApplication())); fileTypesTableEditColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); fileTypesTableDeleteColumn.setCellValueFactory(data -> BindingsHelper.constantOf(true)); new ValueTableCellFactory<ExternalFileType, JabRefIcon>() .withGraphic(JabRefIcon::getGraphicNode) .install(fileTypesTableIconColumn); new ValueTableCellFactory<ExternalFileType, Boolean>() .withGraphic(none -> IconTheme.JabRefIcons.EDIT.getGraphicNode()) .withOnMouseClickedEvent((type, none) -> event -> viewModel.edit(type)) .install(fileTypesTableEditColumn); new ValueTableCellFactory<ExternalFileType, Boolean>() .withGraphic(none -> IconTheme.JabRefIcons.REMOVE.getGraphicNode()) .withOnMouseClickedEvent((type, none) -> event -> viewModel.remove(type)) .install(fileTypesTableDeleteColumn); }
Source:
private static DataSchema createDataSchema( String dataSource, Interval interval, DimensionsSpec dimensionsSpec, IndexIO indexIO, ObjectMapper jsonMapper, List<TimelineObjectHolder<String, DataSegment>> timelineSegments, Map<DataSegment, File> segmentFileMap ) throws IOException, SegmentLoadingException { final List<QueryableIndex> segments = loadSegments(timelineSegments, segmentFileMap, indexIO); final boolean rollup = segments.stream().allMatch(index -> index.getMetadata().isRollup()); final List<AggregatorFactory[]> aggregatorFactories = segments.stream() .map(index -> index.getMetadata().getAggregators()) .collect(Collectors.toList()); final AggregatorFactory[] mergedAggregators = AggregatorFactory.mergeAggregators(aggregatorFactories); if (mergedAggregators == null) { throw new ISE("Failed to merge aggregators[%s]", aggregatorFactories); } final List<AggregatorFactory> combiningAggregatorList = Arrays.stream(mergedAggregators) .map(AggregatorFactory::getCombiningFactory) .collect(Collectors.toList()); final AggregatorFactory[] combiningAggregators = combiningAggregatorList.toArray( new AggregatorFactory[combiningAggregatorList.size()] ); final GranularitySpec granularitySpec = new ArbitraryGranularitySpec( new NoneGranularity(), rollup, ImmutableList.of(interval) ); return new DataSchema( dataSource, dimensionsSpec == null ? ImmutableMap.of("type", "noop") : ImmutableMap.of( "type", "noop", "parseSpec", ImmutableMap.of("type", "timeAndDims", "dimensionsSpec", dimensionsSpec) ), combiningAggregators, granularitySpec, jsonMapper ); }

Target:
private static DataSchema createDataSchema( String dataSource, Interval interval, DimensionsSpec dimensionsSpec, IndexIO indexIO, ObjectMapper jsonMapper, List<TimelineObjectHolder<String, DataSegment>> timelineSegments, Map<DataSegment, File> segmentFileMap ) throws IOException, SegmentLoadingException { final List<QueryableIndex> queryableIndices = loadSegments(timelineSegments, segmentFileMap, indexIO); final List<AggregatorFactory[]> aggregatorFactories = queryableIndices .stream() .map(index -> index.getMetadata().getAggregators()) .collect(Collectors.toList()); final AggregatorFactory[] mergedAggregators = AggregatorFactory.mergeAggregators(aggregatorFactories); if (mergedAggregators == null) { throw new ISE("Failed to merge aggregators[%s]", aggregatorFactories); } final boolean rollup = queryableIndices.stream().allMatch(index -> index.getMetadata().isRollup()); final GranularitySpec granularitySpec = new ArbitraryGranularitySpec( new NoneGranularity(), rollup, ImmutableList.of(interval) ); final DimensionsSpec finalDimensionsSpec = dimensionsSpec == null ? createDimensionsSpec(queryableIndices) : dimensionsSpec; final InputRowParser parser = new NoopInputRowParser(new TimeAndDimsParseSpec(null, finalDimensionsSpec)); return new DataSchema( dataSource, jsonMapper.convertValue(parser, JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT), mergedAggregators, granularitySpec, null, jsonMapper ); }
Source:
private List<AggregateEsBase<? extends Bucket>> buildAggregates() { ArrayList<AggregateEsBase<? extends Bucket>> ret = new ArrayList<>(getAggregateDefinitions().size()); for (AggregateDefinition def : getAggregateDefinitions()) { AggregateEsBase<? extends Bucket> agg = AggregateFactory.create(def, getSearchDocumentModel()); if (!isSkipAggregates() || !agg.getSelection().isEmpty()) { ret.add(AggregateFactory.create(def, getSearchDocumentModel())); } } return ret; }

Target:
private List<AggregateEsBase<? extends Bucket>> buildAggregates() { ArrayList<AggregateEsBase<? extends Bucket>> ret = new ArrayList<>(getAggregateDefinitions().size()); boolean skip = isSkipAggregates(); for (AggregateDefinition def : getAggregateDefinitions()) { AggregateEsBase<? extends Bucket> agg = AggregateFactory.create(def, getSearchDocumentModel()); if (!skip || !agg.getSelection().isEmpty()) { ret.add(AggregateFactory.create(def, getSearchDocumentModel())); } } return ret; }
Source:
public void onEndNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntCommon, int cntNotFound, boolean ready) throws UploadPackMayNotContinueException { for (PreUploadHook hook : hooks) { hook.onEndNegotiateRound(up, wants, cntCommon, cntNotFound, ready); } }

Target:
public void onEndNegotiateRound(UploadPack up, Collection<? extends ObjectId> wants, int cntCommon, int cntNotFound, boolean ready) throws UploadPackMayNotContinueException { for (int i = 0; i < count; i++) hooks[i].onEndNegotiateRound(up, wants, cntCommon, cntNotFound, ready); }
Source:
public void testConnectAPIMode() throws Exception { PowerMockito.doReturn(XBeeMode.API).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.connect(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } assertEquals(xbeeDevice.getOperatingMode(), XBeeMode.API); }

Target:
public void testConnectAPIMode() throws Exception { PowerMockito.doReturn(OperatingMode.API).when(xbeeDevice, "determineConnectionMode"); try { xbeeDevice.open(); } catch (XBeeException e) { fail("This exception shouldn't be thrown now."); } catch (InvalidOperatingModeException e) { fail("This exception shouldn't be thrown now."); } assertTrue(xbeeDevice.isOpen()); assertTrue(dataReader.isRunning()); assertEquals(xbeeDevice.getOperatingMode(), OperatingMode.API); }
Source:
public void sendRequest(final ITmfEventRequest request) { synchronized (fLock) { if (request.getExecType() == ExecutionType.FOREGROUND) { if ((fSignalDepth > 0) || (fRequestPendingCounter > 0)) { coalesceEventRequest(request); } else { dispatchRequest(request); } return; } boolean startTimer = getNbPendingBackgroundRequests() == 0; coalesceEventRequest(request); if (startTimer) { TimerTask task = new TimerTask() { @Override public void run() { synchronized (fLock) { fIsTimeout = true; fireRequest(); } } }; fTimer.schedule(task, DELAY); } } }

Target:
public void sendRequest(final ITmfEventRequest request) { synchronized (fLock) { if (request.getExecType() == ExecutionType.FOREGROUND) { if ((fSignalDepth > 0) || (fRequestPendingCounter > 0)) { coalesceEventRequest(request); } else { dispatchRequest(request); } return; } boolean startTimer = (getNbPendingBackgroundRequests() == 0); coalesceEventRequest(request); if (startTimer) { TimerTask task = new TimerTask() { @Override public void run() { synchronized (fLock) { fIsTimeout = true; fireRequest(); } } }; fTimer.schedule(task, DELAY); } } }
Source:
public List<ODataEntry> readTableWithKeys(String tableName, ODataEntry keys) throws ODataServiceFault { List<ODataEntry> entryList = new ArrayList<>(); ODataEntry dataEntry; for (String keyName : keys.getData().keySet()) { String keyValue = keys.getValue(keyName); String projectionResult = jongo.getCollection(tableName).findOne(new ObjectId(keyValue)).map(MongoQuery.MongoResultMapper.getInstance()); if (projectionResult == null) { throw new ODataServiceFault("Document ID: " + keyValue + " does not exist in " + "collection: " + tableName + " ."); } Iterator<?> key = new JSONObject(projectionResult).keys(); dataEntry = createDataEntryFromResult(projectionResult, key); dataEntry.addValue(ETAG, ODataUtils.generateETag(this.configId, tableName, dataEntry)); entryList.add(dataEntry); } return entryList; }

Target:
public List<ODataEntry> readTableWithKeys(String tableName, ODataEntry keys) throws ODataServiceFault { List<ODataEntry> entryList = new ArrayList<>(); ODataEntry dataEntry; for (String keyName : keys.getData().keySet()) { String keyValue = keys.getValue(keyName); String projectionResult = jongo.getCollection(tableName).findOne(new ObjectId(keyValue)). map(MongoQuery.MongoResultMapper.getInstance()); if (projectionResult == null) { throw new ODataServiceFault(DOCUMENT_ID + keyValue + " does not exist in collection: " + tableName + " ."); } Iterator<?> key = new JSONObject(projectionResult).keys(); dataEntry = createDataEntryFromResult(projectionResult, key); dataEntry.addValue(ETAG, ODataUtils.generateETag(this.configId, tableName, dataEntry)); entryList.add(dataEntry); } return entryList; }
Source:
public Iterable<StructuredRecord> call(Tuple2<LongWritable, Text> in) throws Exception { if (recordFormat == null) { schema = Schema.parseJson(schemaStr); FormatSpecification spec = new FormatSpecification(format, schema, new HashMap<String, String>()); recordFormat = RecordFormats.createInitializedFormat(spec); } StructuredRecord.Builder builder = StructuredRecord.builder(schema); StructuredRecord messageRecord = recordFormat.read(new StreamEvent(ByteBuffer.wrap(in._2().getBytes()))); for (Schema.Field messageField : messageRecord.getSchema().getFields()) { String fieldName = messageField.getName(); builder.set(fieldName, messageRecord.get(fieldName)); } List<StructuredRecord> output = new ArrayList<>(1); output.add(builder.build()); return output; }

Target:
public Iterable<StructuredRecord> call(Tuple2<LongWritable, Text> in) throws Exception { if (recordFormat == null) { schema = Schema.parseJson(schemaStr); FormatSpecification spec = new FormatSpecification(format, schema, new HashMap<String, String>()); recordFormat = RecordFormats.createInitializedFormat(spec); } StructuredRecord.Builder builder = StructuredRecord.builder(schema); StructuredRecord messageRecord = recordFormat.read(new StreamEvent(ByteBuffer.wrap(in._2().copyBytes()))); for (Schema.Field messageField : messageRecord.getSchema().getFields()) { String fieldName = messageField.getName(); builder.set(fieldName, messageRecord.get(fieldName)); } List<StructuredRecord> output = new ArrayList<>(1); output.add(builder.build()); return output; }
Source:
private static void autoIgnoreWorkspaceMetaData(java.nio.file.Path gitDir) { java.nio.file.Path workspaceRoot = ResourcesPlugin.getWorkspace() .getRoot().getLocation().toFile().toPath(); try { if (Files.isSameFile(workspaceRoot, gitDir.getParent())) { Path metaData = new Path(workspaceRoot.resolve(".metadata") .toAbsolutePath().toString()); Collection<IPath> ignore = new HashSet<IPath>(); ignore.add(metaData); JobUtil.scheduleUserJob( new IgnoreOperation(ignore), CoreText.RepositoryUtil_autoIgnoreMetaData, JobFamilies.AUTO_IGNORE); } } catch (IOException e) { Activator.logError(e.getMessage(), e); } }

Target:
private static void autoIgnoreWorkspaceMetaData(java.nio.file.Path gitDir) { java.nio.file.Path workspaceRoot = ResourcesPlugin.getWorkspace() .getRoot().getLocation().toFile().toPath(); try (Repository r = FileRepositoryBuilder.create(gitDir.toFile())) { if (workspaceRoot.startsWith(r.getWorkTree().toPath())) { Collection<IPath> ignoredPaths = buildIgnoredPathsList( workspaceRoot, ".metadata", ".recommenders"); JobUtil.scheduleUserJob( new IgnoreOperation(ignoredPaths), CoreText.RepositoryUtil_autoIgnoreMetaData, JobFamilies.AUTO_IGNORE); } } catch (IOException e) { Activator.logError(e.getMessage(), e); } }
Source:
public boolean isActive(FeatureState featureState, FeatureUser user) { HttpServletRequest request = HttpServletRequestHolder.get(); if (request != null) { Device device = DeviceUtils.getCurrentDevice(request); String suffix = device.isMobile() ? MOBILE : (device.isTablet() ? TABLET : DESKTOP); return (YES.equals(featureState.getParameter(ON+suffix))); } return false; }

Target:
public boolean isActive(FeatureState featureState, FeatureUser user) { HttpServletRequest request = HttpServletRequestHolder.get(); if (request != null) { Device device = DeviceUtils.getCurrentDevice(request); DeviceType deviceType = device.isMobile() ? MOBILE : (device.isTablet() ? TABLET : NORMAL); return (YES.equalsIgnoreCase(featureState.getParameter(deviceType.name()))); } return false; }
Source:
public DirContext bind(String principalName, String password, List<SocketInfo> ldapServers) { Hashtable<String, String> props = new Hashtable<String, String>(); props.put(Context.REFERRAL, "follow"); props.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid"); props.put("java.naming.ldap.factory.socket", TrustAllSocketFactory.class.getName()); return bind(principalName, password, ldapServers, props); }

Target:
public DirContext bind(String principalName, String password, List<SocketInfo> ldapServers) { return bind(principalName, password, ldapServers, new Hashtable<String, String>()); }
Source:
public static VdcActionParametersBase getParameters(CommandEntity commandEntity) { return commandEntity.getData() != null ? (VdcActionParametersBase) commandEntity.getData().get(PARAMETERS_KEY) : null; }

Target:
public static VdcActionParametersBase getParameters(CommandEntity commandEntity) { return (VdcActionParametersBase) commandEntity.getData().get(PARAMETERS_KEY); }
Source:
long menuForEvent (long id, long sel, long theEvent) { if (!isEnabled ()) return 0; NSPoint pt = NSEvent.mouseLocation(); pt.y = (int) (display.getPrimaryFrame().height - pt.y); int x = (int) pt.x; int y = (int) pt.y; Event event = new Event (); event.x = x; event.y = y; NSEvent nsEvent = new NSEvent(theEvent); event.detail = nsEvent.buttonNumber() > 0 ? SWT.MENU_MOUSE : SWT.MENU_KEYBOARD; int count = 0; boolean menuAlreadyHandledByDisplay = false; if (display.popups != null) { while (count < display.popups.length && display.popups[count] != null) { if (menu != null && display.popups[count] == menu) { menuAlreadyHandledByDisplay = true; } count++; } } sendEvent(SWT.MenuDetect, event); if (isDisposed ()) return 0; Menu menu = getMenu (); if (event.doit && menu != null && !menu.isDisposed () && !menuAlreadyHandledByDisplay) { if (x != event.x || y != event.y) { menu.setLocation (event.x, event.y); } return menu.nsMenu.id; } int count2 = 0; if (display.popups != null) { while (count2 < display.popups.length && display.popups[count2] != null) { count2++; } } if (count2 != count && count2 > 0) { Menu menu1 = display.popups[count2 - 1]; display.popups[count2 - 1] = null; return menu1.nsMenu.id; } if (!event.doit) return 0; return super.menuForEvent (id, sel, theEvent); }

Target:
long menuForEvent (long id, long sel, long theEvent) { if (!isEnabled ()) return 0; NSPoint pt = NSEvent.mouseLocation(); pt.y = (int) (display.getPrimaryFrame().height - pt.y); int x = (int) pt.x; int y = (int) pt.y; Event event = new Event (); event.x = x; event.y = y; NSEvent nsEvent = new NSEvent(theEvent); event.detail = nsEvent.buttonNumber() > 0 ? SWT.MENU_MOUSE : SWT.MENU_KEYBOARD; int count = 0; boolean menuAlreadyHandledByDisplay = false; if (display.popups != null) { while (count < display.popups.length && display.popups[count] != null) { if (display.popups[count] == menu) { menuAlreadyHandledByDisplay = true; } count++; } } sendEvent(SWT.MenuDetect, event); if (isDisposed ()) return 0; Menu menu = getMenu (); if (event.doit && menu != null && !menu.isDisposed () && !menuAlreadyHandledByDisplay) { if (x != event.x || y != event.y) { menu.setLocation (event.x, event.y); } return menu.nsMenu.id; } int count2 = 0; if (display.popups != null) { while (count2 < display.popups.length && display.popups[count2] != null) { count2++; } } if (count2 != count && count2 > 0) { Menu menu1 = display.popups[count2 - 1]; display.popups[count2 - 1] = null; return menu1.nsMenu.id; } if (!event.doit) return 0; return super.menuForEvent (id, sel, theEvent); }
Source:
public static synchronized void start(boolean startRecoveryService) throws InitializationException { if (initialized) { if (startRecoveryService) startRecoveryService(); return; } try { jdbcPropertyManager.getJDBCEnvironmentBean().setJndiProperties(new InitialContext().getEnvironment()); } catch (NamingException e) { throw new InitializationException("No suitable JNDI provider available", e); } registerJndiBindings(); try { DriverManager.registerDriver(new TransactionalDriver()); } catch (SQLException e) { throw new InitializationException("Cannot initialize TransactionalDriver", e); } initialized = true; if (startRecoveryService) { startRecoveryService(); } }

Target:
public static synchronized void start(boolean startRecoveryService) throws InitializationException { if (initialized) return; try { initialContext = new InitialContext(); replacedJndiProperties = jdbcPropertyManager.getJDBCEnvironmentBean().getJndiProperties().size() == 0; if (replacedJndiProperties) jdbcPropertyManager.getJDBCEnvironmentBean().setJndiProperties(initialContext.getEnvironment()); DriverManager.registerDriver(new TransactionalDriver()); } catch (NamingException e) { if (tsLogger.logger.isInfoEnabled()) tsLogger.logger.info("TransactionServiceFactory error:", e); throw new InitializationException("No suitable JNDI provider available", e); } catch (SQLException e) { if (tsLogger.logger.isInfoEnabled()) tsLogger.logger.info("TransactionServiceFactory error:", e); throw new InitializationException("Cannot initialize TransactionalDriver", e); } registerJndiBindings(initialContext); initialized = true; if (startRecoveryService) startRecoveryService(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { TransactionServiceFactory.stop(); } }); }
Source:
public boolean intersects(PointList pointList) { int len = pointList.getSize(); if (len == 0) throw new IllegalArgumentException("PointList must not be empty"); double lat = pointList.getLatitude(0); double lon = pointList.getLongitude(0); if (len == 1) return contains(lat, lon); Coordinate coords = new Coordinate(lon, lat); RectangleLineIntersector intersector = getCachedRectangleLineIntersector(); for (int pointIndex = 1; pointIndex < len; pointIndex++) { Coordinate nextCoords = new Coordinate(pointList.getLongitude(pointIndex), pointList.getLatitude(pointIndex)); if (intersector.intersects(coords, nextCoords)) return true; coords = nextCoords; } return false; }

Target:
public boolean intersects(PointList pointList) { return intersects(new RectangleLineIntersector(toEnvelope(this)), pointList); }
Source:
public static LatokenOrderStatus parse(String s) { try { return LatokenOrderStatus.valueOf(s); } catch (Exception e) { throw new RuntimeException("Unknown LatokenOrderStatus " + s + "."); } }

Target:
public static LatokenOrderStatus parse(String s) { try { return LatokenOrderStatus.valueOf(s); } catch (Exception e) { throw new ExchangeException("Unknown LatokenOrderStatus " + s + "."); } }
Source:
public String getHelp() { return new TextComponentTranslation("commands.bloodmagic.orb." + getName() + ".help", getInfo()).getFormattedText(); }

Target:
public String getHelp() { return "commands.bloodmagic.orb." + getName() + ".help"; }
Source:
public KubernetesEnvironment build() { KubernetesEnvironment kubernetesEnvironment; if (internalEnvironment == null) { kubernetesEnvironment = new KubernetesEnvironment( internalRecipe, machines, warnings, pods, services, ingresses, pvcs, secrets, configMaps); } else { kubernetesEnvironment = new KubernetesEnvironment( internalEnvironment, pods, services, ingresses, pvcs, secrets, configMaps); if (internalRecipe != null) { kubernetesEnvironment.setRecipe(internalRecipe); } if (machines != null) { kubernetesEnvironment.setMachines(machines); } if (commands != null) { kubernetesEnvironment.setCommands(commands); } if (warnings != null) { kubernetesEnvironment.setWarnings(warnings); } } kubernetesEnvironment.setType(type); return kubernetesEnvironment; }

Target:
public KubernetesEnvironment build() { return new KubernetesEnvironment( internalEnvironment, pods, services, ingresses, pvcs, secrets, configMaps); }
Source:
public Block build() { if (currentEntryOpened) { throw new IllegalStateException("Current entry must be closed before the block can be built"); } Optional<int[]> rawHashTables = hashTables.get(); verify(rawHashTables.isPresent(), "rawHashTables is null"); int hashTablesEntries = offsets[positionCount] * HASH_MULTIPLIER; return createMapBlockInternal( 0, positionCount, Optional.of(mapIsNull), offsets, keyBlockBuilder.build(), valueBlockBuilder.build(), new HashTables(Optional.of(Arrays.copyOf(rawHashTables.get(), hashTablesEntries)), hashTablesEntries), keyType, keyBlockNativeEquals, keyNativeHashCode, keyBlockHashCode); }

Target:
public Block build() { if (currentEntryOpened) { throw new IllegalStateException("Current entry must be closed before the block can be built"); } Optional<int[]> rawHashTables = hashTables.get(); verify(rawHashTables.isPresent(), "rawHashTables is empty"); int hashTablesEntries = offsets[positionCount] * HASH_MULTIPLIER; return createMapBlockInternal( 0, positionCount, Optional.of(mapIsNull), offsets, keyBlockBuilder.build(), valueBlockBuilder.build(), new HashTables(Optional.of(Arrays.copyOf(rawHashTables.get(), hashTablesEntries)), hashTablesEntries), keyType, keyBlockNativeEquals, keyNativeHashCode, keyBlockHashCode); }
Source:
public void loadNbt(CompoundTag tag) { super.loadNbt(tag); tag.readString("EntityId", name -> spawning = EntityType.fromName(name)); if (spawning == null) { spawning = DEFAULT; } if (!tag.readInt("Delay", this::setDelay)) { delay = 0; } }

Target:
public void loadNbt(CompoundTag tag) { super.loadNbt(tag); spawning = tag.tryGetString("EntityId").map(EntityType::fromName).orElse(DEFAULT); delay = tag.tryGetInt("Delay").orElse(0); }
Source:
public void withProperty(String key, String value) { if (properties == null) { properties = new HashedMap(); } properties.put(key, value); }

Target:
public void withProperty(String key, String value) { properties.put(key, value); }
Source:
private void checkIneffectiveAnnotations(Class valueCls) { for (Field f:valueCls.getDeclaredFields()) { AffinityKeyMapped[] annotations = f.getDeclaredAnnotationsByType(AffinityKeyMapped.class); if (annotations.length > 0) { LT.warn(log, "AffinityKeyMapped annotation should be used on key and not value type"); } } }

Target:
private void checkIneffectiveAnnotations(Class valueCls) { for (Field f: valueCls.getDeclaredFields()) { AffinityKeyMapped[] annotations = f.getDeclaredAnnotationsByType(AffinityKeyMapped.class); if (annotations != null && annotations.length > 0) { LT.warn(log, "AffinityKeyMapped annotation should be used on key and not value type"); } } }
Source:
public String toString() { return "DefaultSubscriptionBillingEvent{" + "type=" + type + ", plan='" + plan + '\'' + ", planPhase='" + planPhase + '\'' + ", effectiveDate=" + effectiveDate + ", totalOrdering=" + totalOrdering + ", bcdLocal=" + bcdLocal + '}'; }

Target:
public String toString() { return "DefaultSubscriptionBillingEvent{" + "type=" + type + ", plan='" + plan.getName() + '\'' + ", planPhase='" + planPhase.getName() + '\'' + ", effectiveDate=" + effectiveDate + ", totalOrdering=" + totalOrdering + ", bcdLocal=" + bcdLocal + '}'; }
Source:
public void setDns(List<String> dns) { this.dns = dns; }

Target:
public AgentConfig setDns(List<String> dns) { this.dns = dns; return this; }
Source:
public boolean isPreRelease(String version) { return PypiCanonicalVersionValidator.PRE_RELEASE_PATTERN.matcher(version).matches(); }

Target:
public boolean isPreRelease(String version) { return versionMatches.test(PypiCanonicalVersionValidator.PRE_RELEASE_PATTERN, version); }
Source:
protected void makeWrittable() { super.makeWrittable(); if (button != null && eObject instanceof ContainerMapping) { ContainerMapping containerMapping = (ContainerMapping) eObject; Option<String> experimentalStackButtons = shouldMarkCompartimentsExperimental(containerMapping); Option<String> disabledStackButtons = shouldDisableCompartiments(containerMapping); updateControls(experimentalStackButtons, disabledStackButtons); } }

Target:
protected void makeWrittable() { super.makeWrittable(); if (button != null && eObject instanceof ContainerMapping) { ContainerMapping containerMapping = (ContainerMapping) eObject; Option<String> experimentalStackButtons = shouldMarkCompartmentsExperimental(containerMapping); Option<String> disabledStackButtons = shouldDisableCompartments(containerMapping); updateControls(experimentalStackButtons, disabledStackButtons); } }
Source:
public void testKeepsOutputSymbols() { assertReorderJoins() .on(p -> p.join( INNER, p.values(new PlanNodeId("valuesA"), ImmutableList.of(p.symbol("A1"), p.symbol("A2")), TWO_ROWS), p.values(new PlanNodeId("valuesB"), ImmutableList.of(p.symbol("B1")), TWO_ROWS), ImmutableList.of(new JoinNode.EquiJoinClause(p.symbol("A1"), p.symbol("B1"))), ImmutableList.of(p.symbol("A2")), Optional.empty())) .withStats("valuesA", PlanNodeStatsEstimate.builder() .setOutputRowCount(5000) .addSymbolStatistics(ImmutableMap.of( new Symbol("A1"), new SymbolStatsEstimate(0, 100, 0, 100, 100), new Symbol("A2"), new SymbolStatsEstimate(0, 100, 0, 100, 100))) .build()) .withStats("valuesB", PlanNodeStatsEstimate.builder() .setOutputRowCount(10000) .addSymbolStatistics(ImmutableMap.of(new Symbol("B1"), new SymbolStatsEstimate(0, 100, 0, 100, 100))) .build()) .matches(join( INNER, ImmutableList.of(equiJoinClause("A1", "B1")), Optional.empty(), Optional.of(PARTITIONED), values(ImmutableMap.of("A1", 0, "A2", 1)), values(ImmutableMap.of("B1", 0))) .withExactOutputs("A2")); }

Target:
public void testKeepsOutputSymbols() { assertReorderJoins() .on(p -> p.join( INNER, p.values(new PlanNodeId("valuesA"), ImmutableList.of(p.symbol("A1"), p.symbol("A2")), TWO_ROWS), p.values(new PlanNodeId("valuesB"), ImmutableList.of(p.symbol("B1")), TWO_ROWS), ImmutableList.of(new EquiJoinClause(p.symbol("A1"), p.symbol("B1"))), ImmutableList.of(p.symbol("A2")), Optional.empty())) .overrideStats("valuesA", PlanNodeStatsEstimate.builder() .setOutputRowCount(5000) .addSymbolStatistics(ImmutableMap.of( new Symbol("A1"), new SymbolStatsEstimate(0, 100, 0, 100, 100), new Symbol("A2"), new SymbolStatsEstimate(0, 100, 0, 100, 100))) .build()) .overrideStats("valuesB", PlanNodeStatsEstimate.builder() .setOutputRowCount(10000) .addSymbolStatistics(ImmutableMap.of(new Symbol("B1"), new SymbolStatsEstimate(0, 100, 0, 100, 100))) .build()) .matches(join( INNER, ImmutableList.of(equiJoinClause("A1", "B1")), Optional.empty(), Optional.of(PARTITIONED), values(ImmutableMap.of("A1", 0, "A2", 1)), values(ImmutableMap.of("B1", 0))) .withExactOutputs("A2")); }
Source:
private boolean replace(IfStatement node, Assignment a, ITypeBinding typeBinding, Expression rightHandSide) { if (typeBinding == null) { return VISIT_SUBTREE; } final String expressionTypeName = typeBinding.getQualifiedName(); final Expression newE = maybeGetExpression(expressionTypeName, node.getExpression(), a.getRightHandSide(), rightHandSide); if (newE != null) { ctx.getRefactorings().replace(rightHandSide, newE); ctx.getRefactorings().remove(node); return DO_NOT_VISIT_SUBTREE; } return VISIT_SUBTREE; }

Target:
private boolean replace(IfStatement node, Assignment a, ITypeBinding typeBinding, Expression rightHandSide) { if (typeBinding == null) { return VISIT_SUBTREE; } final String expressionTypeName = typeBinding.getQualifiedName(); final Expression newE = newExpressionOrNull(expressionTypeName, node.getExpression(), a.getRightHandSide(), rightHandSide); if (newE != null) { ctx.getRefactorings().replace(rightHandSide, newE); ctx.getRefactorings().remove(node); return DO_NOT_VISIT_SUBTREE; } return VISIT_SUBTREE; }
Source:
protected void postBatchRequest(String postData, final IPostBatchRequestListener listener) { restClient.post(config.getEventsUrl() + SwrveBase.BATCH_EVENTS_ACTION, postData, new IRESTResponseListener() { @Override public void onResponse(RESTResponse response) { boolean deleteEvents = true; if (SwrveHelper.userErrorResponseCode(response.responseCode)) { SwrveLogger.e(LOG_TAG, "Error sending events to Swrve: " + response.responseBody); } else if (SwrveHelper.successResponseCode(response.responseCode)) { SwrveLogger.i(LOG_TAG, "Events sent to Swrve"); } else if (SwrveHelper.serverErrorResponseCode(response.responseCode)) { deleteEvents = false; SwrveLogger.e(LOG_TAG, "Error sending events to Swrve: " + response.responseBody); } listener.onResponse(deleteEvents); } @Override public void onException(Exception exp) { } }); }

Target:
protected void postBatchRequest(String postData, final IPostBatchRequestListener listener) { restClient.post(config.getEventsUrl() + SwrveBase.BATCH_EVENTS_ACTION, postData, new IRESTResponseListener() { @Override public void onResponse(RESTResponse response) { boolean deleteEvents = true; if (SwrveHelper.userErrorResponseCode(response.responseCode)) { SwrveLogger.e(LOG_TAG, "Error sending events to Swrve: " + response.responseBody); } else if (SwrveHelper.successResponseCode(response.responseCode)) { SwrveLogger.i(LOG_TAG, "Events sent to Swrve"); } else if (SwrveHelper.serverErrorResponseCode(response.responseCode)) { deleteEvents = false; SwrveLogger.e(LOG_TAG, "Error sending events to Swrve: " + response.responseBody); } listener.onResponse(deleteEvents); } @Override public void onException(Exception ex) { SwrveLogger.e(LOG_TAG, "Error posting batch of events.", ex); } }); }
Source:
private void validateZkConnectionSettings(String zkAddress, HelixManagerProperty helixManagerProperty) { if (helixManagerProperty != null && helixManagerProperty.getZkConnectionConfig() != null) { if (zkAddress != null && !zkAddress.isEmpty()) { throw new HelixException( "ZKHelixManager: cannot have both ZkAddress and ZkConnectionConfig set!"); } RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig = helixManagerProperty.getZkConnectionConfig(); if (connectionConfig.getZkRealmShardingKey() == null || connectionConfig .getZkRealmShardingKey().isEmpty()) { throw new HelixException( "ZKHelixManager::ZK path sharding key must be set for ZKHelixManager! ZKHelixManager " + "is only available on single-realm mode."); } _realmAwareZkConnectionConfig = connectionConfig; } }

Target:
private void validateZkConnectionSettings(String zkAddress, HelixManagerProperty helixManagerProperty) { if (helixManagerProperty != null && helixManagerProperty.getZkConnectionConfig() != null) { if (zkAddress != null) { throw new HelixException( "ZKHelixManager: cannot have both ZkAddress and ZkConnectionConfig set!"); } RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig = helixManagerProperty.getZkConnectionConfig(); if (connectionConfig.getZkRealmShardingKey() == null || connectionConfig .getZkRealmShardingKey().isEmpty()) { throw new HelixException( "ZKHelixManager::ZK path sharding key must be set for ZKHelixManager! ZKHelixManager " + "is only available on single-realm mode."); } _realmAwareZkConnectionConfig = connectionConfig; } }
Source:
public <T> T getAdapter(Class<T> adapter) { if (CommentService.class == adapter) { return (T) this; } else if (commentManager == null) { synchronized (this) { if (commentManager == null) { commentManager = recomputeCommentManager(); } } } return (T) commentManager; }

Target:
public <T> T getAdapter(Class<T> adapter) { if (adapter == CommentService.class) { return adapter.cast(this); } else if (commentManager == null) { synchronized (this) { if (commentManager == null) { commentManager = recomputeCommentManager(); } } } return (T) commentManager; }
Source:
public DefaultDsfExecutor(String name) { super(1, new DsfThreadFactory(name + " - " + fgInstanceCounter++)); fName = name; if(DsfDebugOptions.DEBUG_EXECUTOR || ASSERTIONS_ENABLED) { prestartAllCoreThreads(); fThreadToExecutorMap.put(((DsfThreadFactory)getThreadFactory()).fThread, DefaultDsfExecutor.this); } }

Target:
public DefaultDsfExecutor(String name) { super(1, new DsfThreadFactory(name + " - " + fgInstanceCounter++)); fName = name; if(DEBUG_EXECUTOR || ASSERTIONS_ENABLED) { prestartAllCoreThreads(); fThreadToExecutorMap.put(((DsfThreadFactory)getThreadFactory()).fThread, DefaultDsfExecutor.this); } }
Source:
public void init(Config.Scope config) { vaultDirectory = config.get("dir"); disabled = config.getBoolean("disabled", null); if (vaultDirectory == null && disabled == null) { logger.debug("PlainTextVaultProviderFactory not configured"); return; } if (disabled != null && disabled) { logger.debug("PlainTextVaultProviderFactory disabled"); return; } vaultPath = Paths.get(vaultDirectory); if (!Files.exists(vaultPath)) { throw new VaultNotFoundException("The " + vaultPath.toAbsolutePath().toString() + " directory doesn't exist"); } logger.debugf("Configured PlainTextVaultProviderFactory with directory %s", vaultPath.toString()); }

Target:
public void init(Config.Scope config) { vaultDirectory = config.get("dir"); Boolean disabledFromConfig = config.getBoolean("disabled"); if (disabledFromConfig == null) { disabled = false; } else { disabled = disabledFromConfig.booleanValue(); } if (disabled) { logger.debug("PlainTextVaultProviderFactory disabled"); return; } if (vaultDirectory == null) { logger.debug("PlainTextVaultProviderFactory not configured"); return; } vaultPath = Paths.get(vaultDirectory); if (!Files.exists(vaultPath)) { throw new VaultNotFoundException("The " + vaultPath.toAbsolutePath().toString() + " directory doesn't exist"); } logger.debugf("Configured PlainTextVaultProviderFactory with directory %s", vaultPath.toString()); }
Source:
void submitDeleteBlobOperation(String blobIdString, FutureResult<Void> futureResult, Callback<Void> callback) { try { BlobId blobId = RouterUtils.getBlobIdFromString(blobIdString, clusterMap); DeleteOperation deleteOperation = new DeleteOperation(routerConfig, routerMetrics, responseHandler, blobId, futureResult, callback, time); deleteOperations.add(deleteOperation); readyForPollCallback.onPollReady(); } catch (RouterException e) { routerMetrics.operationDequeuingRate.mark(); routerMetrics.deleteBlobErrorCount.inc(); routerMetrics.countError(e); operationCompleteCallback.completeOperation(futureResult, callback, null, e); } }

Target:
void submitDeleteBlobOperation(String blobIdString, FutureResult<Void> futureResult, Callback<Void> callback) { try { BlobId blobId = RouterUtils.getBlobIdFromString(blobIdString, clusterMap); DeleteOperation deleteOperation = new DeleteOperation(routerConfig, routerMetrics, responseHandler, blobId, futureResult, callback, time); deleteOperations.add(deleteOperation); } catch (RouterException e) { routerMetrics.operationDequeuingRate.mark(); routerMetrics.deleteBlobErrorCount.inc(); routerMetrics.countError(e); operationCompleteCallback.completeOperation(futureResult, callback, null, e); } }
Source:
public static String inflateBase64(String base64EncodedValue) throws IOException { byte[] deflatedValue = Base64.getMimeDecoder().decode(base64EncodedValue); InputStream is = new InflaterInputStream( new ByteArrayInputStream(deflatedValue), new Inflater(GZIP_COMPATIBLE)); return IOUtils.toString(is, StandardCharsets.UTF_8.name()); }

Target:
public static String inflateBase64(String base64EncodedValue) throws IOException { byte[] deflatedValue = Base64.getMimeDecoder().decode(base64EncodedValue.getBytes(StandardCharsets.UTF_8)); InputStream is = new InflaterInputStream( new ByteArrayInputStream(deflatedValue), new Inflater(GZIP_COMPATIBLE)); return IOUtils.toString(is, StandardCharsets.UTF_8.name()); }
Source:
protected void doCleanup(String psUuid) { List<ImageCacheShadowVO> shadowVOs = createShadowImageCacheVOs(psUuid); if (shadowVOs == null || shadowVOs.isEmpty()) { return; } for (final ImageCacheShadowVO vo : shadowVOs) { if (!destMaker.isManagedByUs(vo.getImageUuid())) { continue; } CacheInstallPath p = new CacheInstallPath(); p.fullPath = vo.getInstallUrl(); p.disassemble(); if (Q.New(HostVO.class).eq(HostVO_.uuid, p.hostUuid).count() == 0){ continue; } LocalStorageDeleteImageCacheOnPrimaryStorageMsg msg = new LocalStorageDeleteImageCacheOnPrimaryStorageMsg(); msg.setHostUuid(p.hostUuid); msg.setImageUuid(vo.getImageUuid()); msg.setInstallPath(p.installPath); msg.setPrimaryStorageUuid(vo.getPrimaryStorageUuid()); bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, vo.getPrimaryStorageUuid()); bus.send(msg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.warn(String.format("failed to delete the stale image cache[%s] on the primary storage[%s], %s," + "will re-try later", vo.getInstallUrl(), vo.getPrimaryStorageUuid(), reply.getError())); return; } logger.debug(String.format("successfully deleted the stale image cache[%s] on the primary storage[%s]", vo.getInstallUrl(), vo.getPrimaryStorageUuid())); dbf.remove(vo); } }); } }

Target:
protected void doCleanup(String psUuid) { List<ImageCacheShadowVO> shadowVOs = createShadowImageCacheVOs(psUuid); if (shadowVOs == null || shadowVOs.isEmpty()) { return; } for (final ImageCacheShadowVO vo : shadowVOs) { if (!destMaker.isManagedByUs(vo.getImageUuid())) { continue; } CacheInstallPath p = new CacheInstallPath(); p.fullPath = vo.getInstallUrl(); p.disassemble(); if (!dbf.isExist(p.hostUuid, HostVO.class)){ dbf.removeByPrimaryKey(vo.getId(), ImageCacheShadowVO.class); continue; } LocalStorageDeleteImageCacheOnPrimaryStorageMsg msg = new LocalStorageDeleteImageCacheOnPrimaryStorageMsg(); msg.setHostUuid(p.hostUuid); msg.setImageUuid(vo.getImageUuid()); msg.setInstallPath(p.installPath); msg.setPrimaryStorageUuid(vo.getPrimaryStorageUuid()); bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, vo.getPrimaryStorageUuid()); bus.send(msg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.warn(String.format("failed to delete the stale image cache[%s] on the primary storage[%s], %s," + "will re-try later", vo.getInstallUrl(), vo.getPrimaryStorageUuid(), reply.getError())); return; } logger.debug(String.format("successfully deleted the stale image cache[%s] on the primary storage[%s]", vo.getInstallUrl(), vo.getPrimaryStorageUuid())); dbf.remove(vo); } }); } }