auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void mkAssignments(String scratchTopoId) throws Exception { try { if (!isReadyForMKAssignments()) { return; } IStormClusterState state = stormClusterState; Map<String, StormBase> bases; Map<String, TopologyDetails> tds = new HashMap<>(); synchronized (submitLock) { bases = state.topologyBases(); for (Iterator<Entry<String, StormBase>> it = bases.entrySet().iterator(); it.hasNext(); ) { Entry<String, StormBase> entry = it.next(); String id = entry.getKey(); try { tds.put(id, readTopologyDetails(id, entry.getValue())); } catch (KeyNotFoundException e) { it.remove(); } } } List<String> assignedTopologyIds = state.assignments(null); Map<String, Assignment> existingAssignments = new HashMap<>(); for (String id : assignedTopologyIds) { if (!id.equals(scratchTopoId)) { Assignment currentAssignment = state.assignmentInfo(id, null); if (!currentAssignment.is_set_owner()) { TopologyDetails td = tds.get(id); if (td != null) { currentAssignment.set_owner(td.getTopologySubmitter()); currentAssignment.set_topology_hb_timeout_ms(getTopologyHbTimeoutMs(td.getConf())); state.setAssignment(id, currentAssignment, td.getConf()); } } existingAssignments.put(id, currentAssignment); } } lockingMkAssignments(existingAssignments, bases, scratchTopoId, assignedTopologyIds, state, tds); } catch (Exception e) { this.mkAssignmentsErrors.mark(); throw e; } }

Target:
private void mkAssignments(String scratchTopoId) throws Exception { try { if (!isReadyForMKAssignments()) { return; } IStormClusterState state = stormClusterState; Map<String, StormBase> bases; Map<String, TopologyDetails> tds = new HashMap<>(); synchronized (submitLock) { bases = state.topologyBases(); for (Iterator<Entry<String, StormBase>> it = bases.entrySet().iterator(); it.hasNext(); ) { Entry<String, StormBase> entry = it.next(); String id = entry.getKey(); try { tds.put(id, readTopologyDetails(id, entry.getValue())); } catch (KeyNotFoundException e) { it.remove(); } } } List<String> assignedTopologyIds = state.assignments(null); Map<String, Assignment> existingAssignments = new HashMap<>(); for (String id : assignedTopologyIds) { if (!id.equals(scratchTopoId)) { Assignment currentAssignment = state.assignmentInfo(id, null); if (!currentAssignment.is_set_owner()) { TopologyDetails td = tds.get(id); if (td != null) { currentAssignment.set_owner(td.getTopologySubmitter()); state.setAssignment(id, currentAssignment, td.getConf()); } } existingAssignments.put(id, currentAssignment); } } lockingMkAssignments(existingAssignments, bases, scratchTopoId, assignedTopologyIds, state, tds); } catch (Exception e) { this.mkAssignmentsErrors.mark(); throw e; } }
Source:
private void chunkGc() { cubeCache.takeOutGarbage(); }

Target:
private void chunkGc() { Iterator<Cube> cubeIt = cubeCache.cubesIterator(); while(cubeIt.hasNext()) { if(cubeCache.tryUnloadCube(cubeIt.next())) { cubeIt.remove(); } } Iterator<Column> columnIt = cubeCache.columnsIterator(); while(columnIt.hasNext()) { if(cubeCache.tryUnloadColumn(columnIt.next())) { columnIt.remove(); } } }
Source:
public void destroy() throws Exception { if (restAPIPublisher != null) { for (int j = 0; j < numberOfAPIs; j++) { String APIVersion = "1.0.0"; restAPIPublisher.deleteAPI(createdAPIs.get(j).getId()); } } super.cleanUpUsingRest(); }

Target:
public void destroy() throws Exception { if (restAPIPublisher != null) { for (int j = 0; j < numberOfAPIs; j++) { String APIVersion = "1.0.0"; restAPIPublisher.deleteAPI(createdAPIs.get(j).getId()); } } super.cleanUp(); }
Source:
public void addExecuteStatement( CodeBlock.Builder methodBuilder, String helperFieldName, ExecutableElement methodElement, Map<Name, TypeElement> typeParameters) { TypeName returnTypeName = GeneratedCodePatterns.getTypeName(methodElement.getReturnType(), typeParameters); methodBuilder.addStatement( "return ($T) producer.execute(boundStatement, context, $L)", returnTypeName, helperFieldName); }

Target:
public void addExecuteStatement( CodeBlock.Builder methodBuilder, String helperFieldName, ExecutableElement methodElement, Map<Name, TypeElement> typeParameters) { methodBuilder.addStatement("execute(boundStatement)"); }
Source:
public static final <T> T execute(@NonNull SshClientTemplate template) { SSHClient client = SshConnectionPool.getInstance().getConnection(template.url); T retval = null; if (client != null) { try { retval = Single.fromCallable((Callable<T>) () -> template.execute(client)) .subscribeOn(Schedulers.io()) .doOnError(Throwable::printStackTrace) .blockingGet(); } catch (Exception e) { Log.e(TAG, "Error executing template method", e); } finally { if (template.closeClientOnFinish) { tryDisconnect(client); } } } return retval; }

Target:
public static final <T> T execute(@NonNull SshClientTemplate template) { SSHClient client = SshConnectionPool.getInstance().getConnection(template.url); T retval = null; if (client != null) { try { retval = Single.fromCallable((Callable<T>) () -> template.execute(client)) .subscribeOn(Schedulers.io()) .blockingGet(); } catch (Exception e) { Log.e(TAG, "Error executing template method", e); } finally { if (template.closeClientOnFinish) { tryDisconnect(client); } } } return retval; }
Source:
private CreateRequest(ContentFormat format, LwM2mPath target, Integer instanceId, LwM2mResource[] resources) { super(target); if (!target.isObject() && !target.isObjectInstance()) throw new InvalidRequestException("Create request must target an object or object instance"); if (instanceId != null && instanceId == LwM2mObjectInstance.UNDEFINED) { instanceId = null; } if (target.isObjectInstance()) { if (instanceId == null) { instanceId = target.getObjectInstanceId(); } else { if (instanceId.equals(target.getObjectInstanceId())) { throw new InvalidRequestException("Conflict between path instance id and node instance id"); } } } if (instanceId != null && instanceId < 0) throw new InvalidRequestException("Invalid instance id: " + instanceId); this.instanceId = instanceId; this.resources = Collections.unmodifiableList(Arrays.asList(resources)); this.contentFormat = format != null ? format : ContentFormat.TLV; }

Target:
private CreateRequest(ContentFormat format, LwM2mPath target, Integer instanceId, LwM2mResource[] resources) { super(target); if (!target.isObject() && !target.isObjectInstance()) throw new InvalidRequestException("Create request must target an object or object instance"); if (instanceId != null && instanceId == LwM2mObjectInstance.UNDEFINED) { instanceId = null; } if (target.isObjectInstance()) { if (instanceId == null) { instanceId = target.getObjectInstanceId(); } else { if (!instanceId.equals(target.getObjectInstanceId())) { throw new InvalidRequestException("Conflict between path instance id and node instance id"); } } } if (instanceId != null && instanceId < 0) throw new InvalidRequestException("Invalid instance id: " + instanceId); this.instanceId = instanceId; this.resources = Collections.unmodifiableList(Arrays.asList(resources)); this.contentFormat = format != null ? format : ContentFormat.TLV; }
Source:
public CommonXAxisModelBuilder addYSeries(IYSeries ySeries) { if (fXValues.length == 0) { throw new IllegalStateException("X values must be set before setting Y values"); } if (fXValues.length != ySeries.getDatapoints().length) { throw new IllegalStateException("All series in list must be of length : " + fXValues.length); } fYSeries.put(ySeries.getLabel(), ySeries); fModel = null; return this; }

Target:
public CommonXAxisModelBuilder addYSeries(IYSeries ySeries) { if (fXValues.length != ySeries.getDatapoints().length) { throw new IllegalStateException("All series in list must be of length : " + fXValues.length); } fYSeries.put(ySeries.getLabel(), ySeries); fModel = null; return this; }
Source:
public List<SourceWithKeys> splitIntoBundles( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); List<SourceWithKeys> splits = new ArrayList<>(); BigtableOptions bigtableOptions = configuration.toBigtableOptions(); try (BigtableSession session = new BigtableSession(bigtableOptions)) { BigtableClusterName clusterName = bigtableOptions.getClusterName(); BigtableTableName tableName = clusterName.toTableName(configuration.getTableId()); SampleRowKeysRequest.Builder request = SampleRowKeysRequest.newBuilder(); request.setTableName(tableName.toString()); List<SampleRowKeysResponse> sampleRowKeys = session.getDataClient().sampleRowKeys(request.build()); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : sampleRowKeys) { byte[] endKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, endKey) && startKey.length > 0) { continue; } long offset = response.getOffsetBytes(); if ((scanStartKey.length == 0 || endKey.length == 0 || Bytes.compareTo(scanStartKey, endKey) < 0) && (scanEndKey.length == 0 || Bytes.compareTo(scanEndKey, startKey) > 0)) { byte[] splitStart = scanStartKey.length == 0 || Bytes.compareTo(startKey, scanStartKey) >= 0 ? startKey : scanStartKey; byte[] splitStop = (scanEndKey.length == 0 || Bytes.compareTo(endKey, scanEndKey) <= 0) && endKey.length > 0 ? endKey : scanEndKey; split(splits, offset - lastOffset, desiredBundleSizeBytes, splitStart, splitStop); } lastOffset = offset; startKey = endKey; } byte[] endKey = HConstants.EMPTY_END_ROW; if (!Bytes.equals(startKey, endKey)) { splits.add(new SourceWithKeys(startKey, endKey, 0)); } } return splits; }

Target:
public List<SourceWithKeys> splitIntoBundles( long desiredBundleSizeBytes, PipelineOptions options) throws Exception { Scan scan = configuration.getScan(); byte[] scanStartKey = scan.getStartRow(); byte[] scanEndKey = scan.getStopRow(); List<SourceWithKeys> splits = new ArrayList<>(); byte[] startKey = HConstants.EMPTY_START_ROW; long lastOffset = 0; for (SampleRowKeysResponse response : getSampleRowKeys()) { byte[] endKey = response.getRowKey().toByteArray(); if (Bytes.equals(startKey, endKey) && startKey.length > 0) { continue; } long offset = response.getOffsetBytes(); if (isWithinRange(scanStartKey, scanEndKey, startKey, endKey)) { byte[] splitStart = null; byte[] splitStop = null; if (scanStartKey.length == 0 || Bytes.compareTo(startKey, scanStartKey) >= 0) { splitStart = startKey; } else { splitStart = scanStartKey; } if ((scanEndKey.length == 0 || Bytes.compareTo(endKey, scanEndKey) <= 0) && endKey.length > 0) { splitStop = endKey; } else { splitStop = scanEndKey; } splits.addAll(split(offset - lastOffset, desiredBundleSizeBytes, splitStart, splitStop)); } lastOffset = offset; startKey = endKey; } byte[] endKey = HConstants.EMPTY_END_ROW; if (!Bytes.equals(startKey, endKey) && scanEndKey.length == 0) { splits.add(new SourceWithKeys(startKey, endKey, 0)); } return splits; }
Source:
public void testInitialization() { SimpleIgnoreCache cache = new SimpleIgnoreCache(ignoreTestDir); File test = new File(ignoreTestDir.getAbsolutePath() + "/new/a/b1/test.stp"); assertTrue("Missing file " + test.getAbsolutePath(), test.exists()); try { cache.partiallyInitialize(test); } catch (IOException e) { fail("IOException when attempting to lazy initialize"); e.printStackTrace(); } boolean result = cache.isIgnored(test); assertFalse("Unexpected match for " + test.toString(), result); File folder = test.getParentFile(); IgnoreNode rules = null; while (!folder.getAbsolutePath().equals(ignoreTestDir.getAbsolutePath()) && folder.getAbsolutePath().length() > 0) { rules = cache.getRules(folder.getAbsolutePath()); assertNotNull("Ignore file was not initialized for " + folder.getAbsolutePath(), rules); assertEquals(1, rules.getRules().size()); folder = folder.getParentFile(); } if (rules != null) { assertEquals(1, rules.getRules().size()); } else { fail("Ignore nodes not initialized"); } }

Target:
public void testInitialization() { SimpleIgnoreCache cache = new SimpleIgnoreCache(ignoreTestDir); File test = new File(ignoreTestDir.getAbsolutePath() + "/new/a/b1/test.stp"); assertTrue("Missing file " + test.getAbsolutePath(), test.exists()); try { cache.partiallyInitialize(test); } catch (IOException e) { e.printStackTrace(); fail("IOException when attempting to lazy initialize"); } boolean result = cache.isIgnored(test); assertFalse("Unexpected match for " + test.toString(), result); File folder = test.getParentFile(); IgnoreNode rules = null; while (!folder.getAbsolutePath().equals(ignoreTestDir.getAbsolutePath()) && folder.getAbsolutePath().length() > 0) { rules = cache.getRules(folder.getAbsolutePath()); assertNotNull("Ignore file was not initialized for " + folder.getAbsolutePath(), rules); assertEquals(1, rules.getRules().size()); folder = folder.getParentFile(); } if (rules != null) { assertEquals(1, rules.getRules().size()); } else { fail("Ignore nodes not initialized"); } }
Source:
private String socketToStr(Socket socket) { if (socket == null) { return ""; } else { return socket.getLocalAddress().toString() + ":" + socket.getPort(); } }

Target:
private String socketToStr(Socket socket) { if (socket == null) { return ""; } return socket.getLocalAddress().toString() + ":" + socket.getPort(); }
Source:
public void startWithExtraStop() throws Exception { assertTrue(defaultEventLoop.isActive()); defaultEventLoop.stop(); thread.join(); assertFalse(defaultEventLoop.isActive()); try { defaultEventLoop.stop(); fail(); } catch (IllegalStateException e) { thread = defaultEventLoop.start(); assertTrue(defaultEventLoop.isActive()); defaultEventLoop.stop(); thread.join(); } }

Target:
public void startWithExtraStop() throws Exception { assertTrue(defaultEventLoop.isActive()); defaultEventLoop.stop(); thread.join(); assertFalse(defaultEventLoop.isActive()); try { defaultEventLoop.stop(); fail(); } catch (IllegalStateException e) { thread = defaultEventLoop.start(); assertTrue(defaultEventLoop.isActive()); defaultEventLoop.stop(); thread.join(); assertFalse(defaultEventLoop.isActive()); } }
Source:
public MainEventHandler() { String connectionlessProtocolList = Context.getConfig().getString("status.ignoreOffline"); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split(","))); } logEvents = Sets.newHashSet(Context.getConfig().getString("logger.events", DEFAULT_LOGGER_EVENTS).split(",")); }

Target:
public MainEventHandler() { String connectionlessProtocolList = Context.getConfig().getString("status.ignoreOffline"); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split(","))); } logEvents = new HashSet<>(Arrays.asList( Context.getConfig().getString("logger.events", DEFAULT_LOGGER_EVENTS).split(","))); }
Source:
public void init(TestInfo testInfo) throws Exception { final String repositoryId = getRepositoryName(REPOSITORY_ID, testInfo); final String centralRepositoryId = getRepositoryName(CENTRAL_REPOSITORY_ID, testInfo); artifactEntryService.delete( artifactEntryService.findArtifactList(STORAGE_ID, repositoryId, ImmutableMap.of("groupId", "org.carlspring.maven", "artifactId", "derby-maven-plugin", "version", "1.10"), true)); artifactEntryService.delete( artifactEntryService.findArtifactList(STORAGE_ID, repositoryId, ImmutableMap.of("groupId", "org.carlspring", "artifactId", "properties-injector", "version", "1.1"), true)); artifactEntryService.delete( artifactEntryService.findArtifactList(STORAGE_ID, repositoryId, ImmutableMap.of("groupId", "javax.media", "artifactId", "jai_core", "version", "1.1.3"), true)); }

Target:
public void init(TestInfo testInfo) throws Exception { final String repositoryId = getRepositoryName(REPOSITORY_ID, testInfo); artifactEntryService.delete(artifactEntryService.findArtifactList(STORAGE_ID, repositoryId, ImmutableMap.of("groupId", "org.carlspring.maven", "artifactId", "derby-maven-plugin", "version", "1.10"), true)); artifactEntryService.delete(artifactEntryService.findArtifactList(STORAGE_ID, repositoryId, ImmutableMap.of("groupId", "org.carlspring", "artifactId", "properties-injector", "version", "1.1"), true)); artifactEntryService.delete(artifactEntryService.findArtifactList(STORAGE_ID, repositoryId, ImmutableMap.of("groupId", "javax.media", "artifactId", "jai_core", "version", "1.1.3"), true)); }
Source:
private String valueFromDn(AttributeMapping mapping, final String dn) { String valueRdn = mapping.getRdn(); try { for (Rdn rdn : new LdapName(dn).getRdns()) { if (rdn.getType().equalsIgnoreCase(valueRdn)) { return rdn.getValue().toString(); } } } catch (Exception cause) { throw log.ldapRealmInvalidRdnForAttribute(mapping.getName(), dn, valueRdn); } return null; }

Target:
private String valueFromDn(AttributeMapping mapping, final String dn) { String valueRdn = mapping.getRdn(); try { for (Rdn rdn : new LdapName(dn).getRdns()) { if (rdn.getType().equalsIgnoreCase(valueRdn)) { return rdn.getValue().toString(); } } } catch (Exception cause) { throw log.ldapRealmInvalidRdnForAttribute(mapping.getName(), dn, valueRdn, cause); } return null; }
Source:
public static String encryptPassword(String password) { String result = password; String keyFile = Config.<String> GetValue(ConfigValues.keystoreUrl, Config.DefaultConfigurationVersion); String passwd = Config.<String> GetValue(ConfigValues.keystorePass, Config.DefaultConfigurationVersion); String alias = Config.<String> GetValue(ConfigValues.CertAlias, Config.DefaultConfigurationVersion); try { result = EncryptionUtils.encrypt((String) result, keyFile, passwd, alias); } catch (Exception e) { result = password; } return result; }

Target:
public static String encryptPassword(String password) { String result = password; String keyFile = Config.<String> GetValue(ConfigValues.keystoreUrl, Config.DefaultConfigurationVersion); String passwd = Config.<String> GetValue(ConfigValues.keystorePass, Config.DefaultConfigurationVersion); String alias = Config.<String> GetValue(ConfigValues.CertAlias, Config.DefaultConfigurationVersion); try { result = EncryptionUtils.encrypt((String) result, keyFile, passwd, alias); } catch (Exception e) { log.errorFormat("Failed to encrpyt password, error message: {0}", e.getMessage()); throw new SecurityException(e); } return result; }
Source:
private String escapeControl(final String input) { final Pattern pattern = Pattern.compile("[\u0000-\u001f]"); final Matcher matcher = pattern.matcher(input); final StringBuffer escaped = new StringBuffer(input.length()); while (matcher.find()) { matcher.appendReplacement( escaped, String.format("\\\\u%04X", (int) matcher.group().charAt(0)) ); } matcher.appendTail(escaped); return escaped.toString(); }

Target:
private String escapeControl(final String input) { final Matcher matcher = CONTROL.matcher(input); final StringBuffer escaped = new StringBuffer(input.length()); while (matcher.find()) { matcher.appendReplacement( escaped, String.format("\\\\u%04X", (int) matcher.group().charAt(0)) ); } matcher.appendTail(escaped); return escaped.toString(); }
Source:
@Test public void testInsertSourceRelTypeWithNullValues() throws Exception { Planner planner = getPlanner(null, Programs.standard()); SqlNode parse = planner.parse( "insert into \"emps\" values(1, 1, null, 1, 1)"); SqlNode validate = planner.validate(parse); RelNode convert = planner.rel(validate).rel; RelDataType insertSourceType = convert.getInput(0).getRowType(); String typeString = SqlTests.getTypeString(insertSourceType); assertEquals(typeString, "RecordType(INTEGER NOT NULL empid, INTEGER NOT NULL deptno, VARCHAR name, " + "REAL NOT NULL salary, INTEGER commission) NOT NULL"); }

Target:
@Test public void testInsertSourceRelTypeWithNullValues() throws Exception { Planner planner = getPlanner(null, Programs.standard()); SqlNode parse = planner.parse( "insert into \"emps\" values(1, 1, null, 1, 1)"); SqlNode validate = planner.validate(parse); RelNode convert = planner.rel(validate).rel; RelDataType insertSourceType = convert.getInput(0).getRowType(); String typeString = SqlTests.getTypeString(insertSourceType); assertEquals("RecordType(INTEGER NOT NULL empid, INTEGER NOT NULL deptno, VARCHAR name, " + "REAL NOT NULL salary, INTEGER commission) NOT NULL", typeString); }
Source:
private CompletableFuture<Acknowledge> runApplicationAndShutdownClusterAsync(final DispatcherGateway dispatcherGateway) { return applicationCompletionFuture .handle((r, t) -> { if (t == null) { LOG.info("Application completed SUCCESSFULLY"); return dispatcherGateway.shutDownCluster(ApplicationStatus.SUCCEEDED); } final Optional<ApplicationFailureException> exception = ExceptionUtils.findThrowable(t, ApplicationFailureException.class); if (exception.isPresent()) { final ApplicationStatus applicationStatus = exception.get().getStatus(); if (applicationStatus == ApplicationStatus.CANCELED || applicationStatus == ApplicationStatus.FAILED) { LOG.info("Application {}: ", applicationStatus, t); return dispatcherGateway.shutDownCluster(applicationStatus); } } LOG.warn("Exiting with Application Status UNKNOWN: ", t); this.errorHandler.onFatalError(new FlinkException("Application failed unexpectedly.", t)); return FutureUtils.<Acknowledge>completedExceptionally(t); }) .thenCompose(Function.identity()); }

Target:
private CompletableFuture<Acknowledge> runApplicationAndShutdownClusterAsync(final DispatcherGateway dispatcherGateway) { return applicationCompletionFuture .handle((r, t) -> { if (t == null) { LOG.info("Application completed SUCCESSFULLY"); return dispatcherGateway.shutDownCluster(ApplicationStatus.SUCCEEDED); } final Optional<ApplicationFailureException> exception = ExceptionUtils.findThrowable(t, ApplicationFailureException.class); if (exception.isPresent()) { final ApplicationStatus applicationStatus = exception.get().getStatus(); if (applicationStatus == ApplicationStatus.CANCELED || applicationStatus == ApplicationStatus.FAILED) { LOG.info("Application {}: ", applicationStatus, t); return dispatcherGateway.shutDownCluster(applicationStatus); } } LOG.warn("Application failed unexpectedly: ", t); this.errorHandler.onFatalError(new FlinkException("Application failed unexpectedly.", t)); return FutureUtils.<Acknowledge>completedExceptionally(t); }) .thenCompose(Function.identity()); }
Source:
@Override public final void run() { boolean reload = false; boolean sleep = false; List<Entry> entries = null; while (isRunning()) { if (location == null) { try { if (sleep) { Thread.sleep(100); } location = locator.getRegionLocation(regionInfo.getStartKey(), regionInfo.getReplicaId(), reload) .get(); sleep = false; } catch (ExecutionException ee) { LOG.warn("Error getting location for meta region " + regionInfo + ", " + ee); reload = true; sleep = true; continue; } catch (InterruptedException ie) { LOG.warn("Interrupted while getting location for meta region " + regionInfo + ", " + ie); Thread.currentThread().interrupt(); } } try { if (entries == null) { entries = queue.poll(20000, TimeUnit.MILLISECONDS); } if (entries == null) { continue; } CompletableFuture<Long> future = replicate(entries); try { future.get(); entries = null; } catch (InterruptedException e) { Thread.currentThread().interrupt(); continue; } catch (ExecutionException e) { Throwable cause = e.getCause(); LOG.warn("Failed to replicate entries for region of meta table", entries.size()); LOG.warn("Cause: " + cause); location = null; reload = true; } } catch (InterruptedException | ReplicationRuntimeException e) { LOG.warn("Interrupted while waiting for next replication entry batch", e); Thread.currentThread().interrupt(); } } }

Target:
@Override public final void run() { List<Entry> entries = null; while (isRunning()) { try { if (entries == null) { entries = queue.poll(20000, TimeUnit.MILLISECONDS); } if (entries == null) { continue; } CompletableFuture<Long> future = replicate(entries); future.get(); entries = null; } catch (ExecutionException e) { Throwable cause = e.getCause(); LOG.warn("Failed to replicate entries for region of meta table, retry, ", entries.size(), cause); } catch (InterruptedException e) { LOG.warn("Interrupted while waiting for next replication entry batch", e); Thread.currentThread().interrupt(); } } }
Source:
public TickProducer(SiteTaskerQueue taskQueue) { m_taskQueue = taskQueue; m_logger = new VoltLogger("HOST"); m_partitionId = taskQueue.getPartitionId(); m_taskTimeThreshold = 1_000_000L * VoltDB.instance() .getCatalogContext() .getDeployment() .getSystemsettings() .getProcedure() .getWarningtimeout(); }

Target:
public TickProducer(SiteTaskerQueue taskQueue) { m_taskQueue = taskQueue; m_logger = new VoltLogger("HOST"); m_partitionId = taskQueue.getPartitionId(); m_procedureLogThreshold = 1_000_000L * VoltDB.instance() .getCatalogContext() .getDeployment() .getSystemsettings() .getProcedure() .getLoginfo(); }
Source:
public List<Record> takeDeferredRecords() { List<Record> records = new ArrayList<Record>(deferredRecords); deferredRecords.clear(); for (Record record : records) { deferredRecordsSize -= record.size(); } return records; }

Target:
public List<Record> takeDeferredRecords() { List<Record> records = new ArrayList<Record>(deferredRecords); deferredRecords.clear(); for (Record record : records) { removeDeferredProcessedRecord(record); } return records; }
Source:
private ProjectState lookup(final Project.NameKey key) throws OrmException { if (key == null) { return null; } if (key.equals(wildProject) || key.get() == null || key.get().isEmpty()) { return getWildProjectState(); } final ReviewDb db = schema.open(); try { final Project project = db.projects().get(key); if (project == null) { return null; } ProjectState parentProjectState = null; Project.NameKey parentNameKey = project.getParent(); if (parentNameKey == null || parentNameKey.get() == null || parentNameKey.get().isEmpty()){ parentProjectState = getWildProjectState(); } else { parentProjectState = ProjectCacheImpl.this.get(parentNameKey); if (parentProjectState == null){ parentProjectState = lookup(parentNameKey); } } final Collection<RefRight> projectRights = Collections.unmodifiableCollection(db.refRights().byProject( project.getNameKey()).toList()); final ProjectState.InheritedRights inheritedRights = new InheritedRightsComposer(parentProjectState); return projectStateFactory .create(project, projectRights, inheritedRights); } finally { db.close(); } }

Target:
private ProjectState lookup(final Project.NameKey key) throws OrmException { final ReviewDb db = schema.open(); try { final Project p = db.projects().get(key); if (p == null) { return null; } final Collection<RefRight> rights = Collections.unmodifiableCollection(db.refRights().byProject( p.getNameKey()).toList()); return projectStateFactory.create(p, rights); } finally { db.close(); } }
Source:
public void deleteDiagramTest() throws Exception { List<Diagram> modelDiagrams = getDiagrams(); int amountBeforeDeletion = modelDiagrams.size(); selectElementInTheModelexplorer(modelDiagrams.get(0)); IHandler handler = getActiveHandler(); handler.execute((new ExecutionEvent(testedCommand, Collections.EMPTY_MAP, null, null))); modelDiagrams = getDiagrams(); Assert.assertEquals("The deletion of a diagram has no effect", amountBeforeDeletion - 1, modelDiagrams.size()); }

Target:
public void deleteDiagramTest() throws Exception { List<Diagram> modelDiagrams = getDiagrams(); int amountBeforeDeletion = modelDiagrams.size(); selectElementInTheModelexplorer(modelDiagrams.get(0)); IHandler handler = getActiveHandler(); handler.execute((new ExecutionEvent(testedCommand, Collections.EMPTY_MAP, null, null))); modelDiagrams = getDiagrams(); Assert.assertEquals("The deletion of a diagram has no effect", amountBeforeDeletion - 1, modelDiagrams.size()); TransactionalEditingDomain domain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(getRootOfTheModel()); domain.getCommandStack().undo(); modelDiagrams = getDiagrams(); Assert.assertEquals("The undo after the deletion of a diagram has no effect", amountBeforeDeletion, modelDiagrams.size()); domain.getCommandStack().redo(); modelDiagrams = getDiagrams(); Assert.assertEquals("The redo after the deletion of a diagram has no effect", amountBeforeDeletion - 1, modelDiagrams.size()); domain.getCommandStack().undo(); modelDiagrams = getDiagrams(); Assert.assertEquals("The undo after the deletion of a diagram has no effect", amountBeforeDeletion, modelDiagrams.size()); domain.getCommandStack().redo(); modelDiagrams = getDiagrams(); Assert.assertEquals("The redo after the deletion of a diagram has no effect", amountBeforeDeletion - 1, modelDiagrams.size()); }
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { if (fRequirements == null) { fRequirements = new ArrayList<>(); TmfAnalysisRequirement events = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_EVENT); events.addValue(UstMemoryStrings.MALLOC, AnalysisRequirementValueLevel.OPTIONAL); events.addValue(UstMemoryStrings.FREE, AnalysisRequirementValueLevel.OPTIONAL); events.addValue(UstMemoryStrings.CALLOC, AnalysisRequirementValueLevel.OPTIONAL); events.addValue(UstMemoryStrings.REALLOC, AnalysisRequirementValueLevel.OPTIONAL); events.addValue(UstMemoryStrings.MEMALIGN, AnalysisRequirementValueLevel.OPTIONAL); events.addValue(UstMemoryStrings.POSIX_MEMALIGN, AnalysisRequirementValueLevel.OPTIONAL); events.addInformation("The libc wrapper should be loaded in order to get the events in the trace output."); TmfAnalysisRequirement domain = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN); domain.addValue(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN_TYPE_UST, AnalysisRequirementValueLevel.MANDATORY); fRequirements.add(events); fRequirements.add(domain); } return fRequirements; }

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { List<TmfAnalysisRequirement> requirements = new ArrayList<>(); TmfAnalysisRequirement events = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_EVENT); events.addValue(UstMemoryStrings.MALLOC, AnalysisRequirementValueLevel.MANDATORY); events.addValue(UstMemoryStrings.FREE, AnalysisRequirementValueLevel.MANDATORY); events.addValue(UstMemoryStrings.CALLOC, AnalysisRequirementValueLevel.MANDATORY); events.addValue(UstMemoryStrings.REALLOC, AnalysisRequirementValueLevel.MANDATORY); events.addValue(UstMemoryStrings.MEMALIGN, AnalysisRequirementValueLevel.MANDATORY); events.addValue(UstMemoryStrings.POSIX_MEMALIGN, AnalysisRequirementValueLevel.MANDATORY); events.addInformation(Messages.UstMemoryAnalysisModule_EventsLoadingInformation); TmfAnalysisRequirement domain = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN); domain.addValue(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN_TYPE_UST, AnalysisRequirementValueLevel.MANDATORY); requirements.add(events); requirements.add(domain); return requirements; }
Source:
public Optional<Map<String, Object>> findUnRevokedAccount(TokenHash tokenHash) { Optional<Map<String, Object>> storedTokenHash = Optional.ofNullable(jdbi.withHandle(handle -> handle.createQuery("SELECT account_id, coalesce(type, 'API') as type, coalesce(token_type, 'CARD') as token_type FROM tokens WHERE token_hash = :token_hash AND revoked IS NULL") .bind("token_hash", tokenHash.getValue()) .first())); if (storedTokenHash.isPresent()) { updateLastUsedTime(tokenHash); } return storedTokenHash; }

Target:
public Optional<Map<String, Object>> findUnRevokedAccount(TokenHash tokenHash) { Optional<Map<String, Object>> storedTokenHash = Optional.ofNullable(jdbi.withHandle(handle -> handle.createQuery("SELECT account_id, type, coalesce(token_type, 'CARD') as token_type FROM tokens WHERE token_hash = :token_hash AND revoked IS NULL") .bind("token_hash", tokenHash.getValue()) .first())); if (storedTokenHash.isPresent()) { updateLastUsedTime(tokenHash); } return storedTokenHash; }
Source:
private String matchingSpecialization(MethodSymbol method) { List<Type> methodParameters = method.parameterTypes(); Map<String, String> genericTypeMapping = genericTypes.isEmpty() ? Collections.emptyMap() : new HashMap<>(); Type actualReturnType = method.returnType().type(); String expectedReturnType = convertGenericType(returnType, actualReturnType, genericTypeMapping); if (!expectedReturnType.equals(actualReturnType.fullyQualifiedName())) { return null; } for (int i = 0; i < parameters.size(); i++) { Type actualType = methodParameters.get(i); String expectedType = convertGenericType(parameters.get(i), actualType, genericTypeMapping); if (!expectedType.equals(actualType.fullyQualifiedName())) { return null; } } return buildSpecializationName(genericTypeMapping); }

Target:
private String matchingSpecialization(MethodSymbol method) { Map<String, String> genericTypeMapping = genericTypes.isEmpty() ? Collections.emptyMap() : new HashMap<>(); Type actualReturnType = method.returnType().type(); String expectedReturnType = convertGenericType(returnType, actualReturnType, genericTypeMapping); if (!expectedReturnType.equals(actualReturnType.fullyQualifiedName())) { return null; } List<Type> methodParameters = method.parameterTypes(); for (int i = 0; i < parameters.size(); i++) { Type actualType = methodParameters.get(i); String expectedType = convertGenericType(parameters.get(i), actualType, genericTypeMapping); if (!expectedType.equals(actualType.fullyQualifiedName())) { return null; } } return buildSpecializationName(genericTypeMapping); }
Source:
public Proc start() throws IOException { if(cmds().isEmpty()){ LOGGER.log(Level.INFO, "Trying to start a process without setting a command. This might cause " + "an unexpected exception"); } return launch(this); }

Target:
public Proc start() throws IOException { if (cmds().isEmpty()) { LOGGER.log(Level.WARNING, "Trying to start a process without setting a command. This might cause " + "an ArrayIndexOutOfBounds exception"); } return launch(this); }
Source:
public void execute() { try (DbSession dbSession = dbClient.openSession(false)) { reportReader.readContextProperties().forEachRemaining( contextProperty -> { if (contextProperty.getKey().startsWith(SONAR_ANALYSIS)) { AnalysisPropertyDto analysisPropertyDto = new AnalysisPropertyDto() .setUuid(UuidFactoryFast.getInstance().create()) .setKey(contextProperty.getKey()) .setValue(contextProperty.getValue()) .setSnapshotUuid(analysisMetadataHolder.getUuid()); dbClient.analysisPropertiesDao().insert(dbSession, analysisPropertyDto); } }); dbSession.commit(); } }

Target:
public void execute() { final List<AnalysisPropertyDto> analysisPropertyDtos = new ArrayList<>(); reportReader.readContextProperties().forEachRemaining( contextProperty -> { if (contextProperty.getKey().startsWith(SONAR_ANALYSIS)) { analysisPropertyDtos.add(new AnalysisPropertyDto() .setUuid(uuidFactory.create()) .setKey(contextProperty.getKey()) .setValue(contextProperty.getValue()) .setSnapshotUuid(analysisMetadataHolder.getUuid())); } }); if (analysisPropertyDtos.isEmpty()) { return; } try (DbSession dbSession = dbClient.openSession(false)) { dbClient.analysisPropertiesDao().insert(dbSession, analysisPropertyDtos); dbSession.commit(); } }
Source:
public Connection getConnection() throws SQLException { while (true) { long start = System.currentTimeMillis(); Pair<HikariDataSource, Connection> ret; try { ret = getConnectionInternal(); } finally { long now = System.currentTimeMillis(); long elapsed = now - start; if (elapsed > 1000) { log.warn("Waited {}ms for connection", elapsed); logPoolStats(); } else { log.debug("Waited {}ms for connection", elapsed); } } HikariDataSource dataSourcePool = ret.getLeft(); Connection conn = ret.getRight(); try { testConnection(conn); } catch (SQLException e) { log.error("Dropping connection which failed validation", e); dataSourcePool.evictConnection(conn); continue; } return conn; } }

Target:
public Connection getConnection() throws SQLException { long start = System.currentTimeMillis(); try { while (true) { HikariDataSource dataSourcePool = getDataSourcePool(); Connection conn = dataSourcePool.getConnection(); try { testConnection(conn); } catch (SQLException e) { log.error("Dropping connection which failed validation", e); dataSourcePool.evictConnection(conn); if (System.currentTimeMillis() > start + connConfig.getCheckoutTimeout()) { throw e; } continue; } return conn; } } finally { long now = System.currentTimeMillis(); long elapsed = now - start; if (elapsed > 1000) { log.warn("Waited {}ms for connection", elapsed); logPoolStats(); } else { log.debug("Waited {}ms for connection", elapsed); } } }
Source:
public void initialize(ServiceConfiguration config) { if (config.port == null) { config.port = config.secure ? 8883 : 1883; } connection = service.getBrokerConnection(Constants.CLIENTID); if (connection != null) { connection.stop(); service.removeBrokerConnection(Constants.CLIENTID); } connection = new MqttBrokerConnection("127.0.0.1", config.port, config.secure, Constants.CLIENTID); connection.addConnectionObserver(this); if (config.username != null) { connection.setCredentials(config.username, config.password); } try { startEmbeddedServer(config.port, config.secure, config.username, config.password, config.persistenceFile); } catch (IOException e) { logger.debug("Could not start embedded broker", e); logger.debug(e.getLocalizedMessage()); return; } }

Target:
public void initialize(ServiceConfiguration config) throws IOException { int port = config.port == null ? (config.port = config.secure ? 8883 : 1883) : config.port; connection = service.getBrokerConnection(Constants.CLIENTID); if (connection != null) { connection.stop(); service.removeBrokerConnection(Constants.CLIENTID); } connection = new MqttBrokerConnection("127.0.0.1", config.port, config.secure, Constants.CLIENTID); connection.addConnectionObserver(this); if (config.username != null) { connection.setCredentials(config.username, config.password); } startEmbeddedServer(port, config.secure, config.username, config.password, config.persistenceFile); }
Source:
public void printNfoldCorrssvalidationNbAcc(int classesNum, double thres, int minWordsAppearenceCount) { double acc = 0; double precision = 0; double recall = 0; double total = 0; double confusionMatrix[][] = new double[classesNum][classesNum]; for (int i = 0; i < folds.length; i++) { DocumentCollection train = getTrain(i); DocumentCollection test = getTest(i); FeatureMap map = new FeatureMap(); map.addDocs(train, minWordsAppearenceCount, false); MemoryEfficientNB nb = new MemoryEfficientNB(train, map, classesNum); acc += nb.getAcc(test) / ((double) folds.length); for (int j = 0; j < test.docs.size(); j++) { total++; Document d = test.docs.elementAt(j); int label = nb.classify(d, thres); if (label > -1) { recall++; confusionMatrix[d.classID][label]++; } if (label == d.classID) precision++; } } System.out.println("Accuracy: " + acc); System.out.println("Within " + thres + " confidence threshold:"); System.out.println("\tPrecision=" + precision / recall); System.out.println("\tRecall=" + recall / total); System.out.println("\tConfusion matrix within confidence threshold:"); for (int i = 0; i < classesNum; i++) { for (int j = 0; j < classesNum; j++) logger.info(confusionMatrix[i][j] + "\t"); System.out.println(); } }

Target:
public void printNfoldCorrssvalidationNbAcc(int classesNum, double thres, int minWordsAppearenceCount) { double acc = 0; double precision = 0; double recall = 0; double total = 0; double confusionMatrix[][] = new double[classesNum][classesNum]; for (int i = 0; i < folds.length; i++) { DocumentCollection train = getTrain(i); DocumentCollection test = getTest(i); FeatureMap map = new FeatureMap(); map.addDocs(train, minWordsAppearenceCount, false); MemoryEfficientNB nb = new MemoryEfficientNB(train, map, classesNum); acc += nb.getAcc(test) / ((double) folds.length); for (int j = 0; j < test.docs.size(); j++) { total++; Document d = test.docs.elementAt(j); int label = nb.classify(d, thres); if (label > -1) { recall++; confusionMatrix[d.classID][label]++; } if (label == d.classID) precision++; } } System.out.println("Accuracy: " + acc); System.out.println("Within " + thres + " confidence threshold:"); System.out.println("\tPrecision=" + precision / recall); System.out.println("\tRecall=" + recall / total); System.out.println("\tConfusion matrix within confidence threshold:"); for (int i = 0; i < classesNum; i++) { for (int j = 0; j < classesNum; j++) System.out.print(confusionMatrix[i][j] + "\t"); System.out.println(); } }
Source:
public synchronized boolean offer(Runnable runnable) { int poolSize = executor.getPoolSize(); boolean retval = false; if ((poolSize >= executor.getMaximumPoolSize()) || (size() < idleThreads)) retval = super.offer(runnable); return retval; }

Target:
public boolean offer(Runnable runnable) { boolean retval = false; synchronized (lock) { if ((executor.getPoolSize() >= executor.getMaximumPoolSize()) || (threadTaskDelta > 0)) { retval = super.offer(runnable); if (retval) threadTaskDelta--; } } return retval; }
Source:
protected void locateFileFromHardDiskDialog(){ FileDialog dialog = new FileDialog(getEditorSite().getShell(), SWT.NONE); dialog.setFilterNames(new String[] {SourceLookupUIMessages.CSourceNotFoundEditor_2}); CDebugUtils.FileParts missingFileParts = CDebugUtils.getFileParts(missingFile); dialog.setFilterExtensions(new String[] {"*." + missingFileParts.getExtension()}); dialog.setFilterPath(Platform.getLocation().toOSString()); locateFileFromResource(dialog.open()); }

Target:
protected void locateFileFromHardDiskDialog(){ FileDialog dialog = new FileDialog(getEditorSite().getShell(), SWT.NONE); dialog.setFilterNames(new String[] {SourceLookupUIMessages.CSourceNotFoundEditor_2}); CDebugUtils.FileParts missingFileParts = CDebugUtils.getFileParts(missingFile); dialog.setFilterExtensions(new String[] {"*." + missingFileParts.getExtension()}); dialog.setFilterPath(Platform.getLocation().toOSString()); String hardDiskDialogResult = dialog.open(); if( hardDiskDialogResult !=null ){ locateFileFromResource(dialog.open()); } }
Source:
public void oauth(String consumerKey, String consumerSecret, String token, String tokenSecret) throws InterruptedException, ControlStreamException, IOException { BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); SitestreamEndpoint endpoint = new SitestreamEndpoint(); Authentication auth = new OAuth1(consumerKey, consumerSecret, token, tokenSecret); BasicClient client = new ClientBuilder() .hosts(Constants.SITESTREAM_HOST) .endpoint(endpoint) .authentication(auth) .processor(new StringDelimitedProcessor(queue)) .build(); int numProcessingThreads = 4; ExecutorService service = Executors.newFixedThreadPool(numProcessingThreads); Twitter4jSitestreamClient t4jClient = new Twitter4jSitestreamClient( client, queue, Lists.newArrayList(listener), service); t4jClient.connect(); for (int threads = 0; threads < numProcessingThreads; threads++) { t4jClient.process(); } Thread.sleep(5000); HttpClient controllerHttpClient = new DefaultHttpClient(new PoolingClientConnectionManager()); HttpHosts sitestreamHosts = new HttpHosts(Constants.SITESTREAM_HOST); SitestreamController controller = new SitestreamController(controllerHttpClient, sitestreamHosts, auth); controller.getFriends(t4jClient.getStreamId(), 12345L); controller.addUser(t4jClient.getStreamId(), 987765L); client.stop(); }

Target:
public void oauth(String consumerKey, String consumerSecret, String token, String tokenSecret) throws InterruptedException, ControlStreamException, IOException { BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); SitestreamEndpoint endpoint = new SitestreamEndpoint(); Authentication auth = new OAuth1(consumerKey, consumerSecret, token, tokenSecret); BasicClient client = new ClientBuilder() .hosts(Constants.SITESTREAM_HOST) .endpoint(endpoint) .authentication(auth) .processor(new StringDelimitedProcessor(queue)) .build(); int numProcessingThreads = 4; ExecutorService service = Executors.newFixedThreadPool(numProcessingThreads); Twitter4jSitestreamClient t4jClient = new Twitter4jSitestreamClient( client, queue, Lists.newArrayList(listener), service); t4jClient.connect(); for (int threads = 0; threads < numProcessingThreads; threads++) { t4jClient.process(); } Thread.sleep(5000); SitestreamController controller = new SitestreamController(auth); controller.getFriends(t4jClient.getStreamId(), 12345L); controller.addUser(t4jClient.getStreamId(), 987765L); client.stop(); }
Source:
public String getUrlForPathWithoutWiki(String wikiName, String wikiPath) { String url = getUrlForWiki(wikiName); url = url + wikiPath; return url; }

Target:
public String getUrlForPathWithoutWiki(String wikiName, String wikiPath) { return getUrlForWiki(wikiName) + wikiPath; }
Source:
public void submittedMessageShowsInTheChat() throws Exception { givenChatUpdatesAfterEveryMessage(); launchChatActivityWithAccess(Access.PRIVATE); submitMessage("test message"); assertThatMessageFromUserIsShownInChat(AUTHENTICATED_USER.getName(), "test message"); }

Target:
public void submittedMessageShowsInTheChat() throws Exception { givenChatUpdatesAfterEveryMessage(); launchChatActivityWithAccess(Access.PRIVATE); String message = "test message"; submitMessage(message); assertThatMessageFromUserIsShownInChat(AUTHENTICATED_USER.getName(), message); }
Source:
private Map<String, List<Pair<VDS, Integer>>> getDeviceListAllVds(List<String> lunsToResize) { Map<String, List<Pair<VDS, Integer>>> lunToVds = new HashMap<>(); for (VDS vds : getAllRunningVdssInPool()) { GetDeviceListVDSCommandParameters parameters = new GetDeviceListVDSCommandParameters(vds.getId(), getStorageDomain().getStorageType(), lunsToResize); List<LUNs> luns = (List<LUNs>) runVdsCommand(VDSCommandType.GetDeviceList, parameters).getReturnValue(); for (LUNs lun : luns) { List<Pair<VDS, Integer>> vdsSizePairs = lunToVds.get(lun.getLUN_id()); if (vdsSizePairs == null) { vdsSizePairs = new ArrayList<>(); lunToVds.put(lun.getLUN_id(), vdsSizePairs); } vdsSizePairs.add(new Pair<VDS, Integer>(vds, lun.getDeviceSize())); } } return lunToVds; }

Target:
private Map<String, List<Pair<VDS, Integer>>> getDeviceListAllVds(List<String> lunsToResize) { Map<String, List<Pair<VDS, Integer>>> lunToVds = new HashMap<>(); for (VDS vds : getAllRunningVdssInPool()) { GetDeviceListVDSCommandParameters parameters = new GetDeviceListVDSCommandParameters(vds.getId(), getStorageDomain().getStorageType(), lunsToResize); List<LUNs> luns = (List<LUNs>) runVdsCommand(VDSCommandType.GetDeviceList, parameters).getReturnValue(); for (LUNs lun : luns) { MultiValueMapUtils.addToMap(lun.getLUN_id(), new Pair<>(vds, lun.getDeviceSize()), lunToVds); } } return lunToVds; }
Source:
public void forceAdd(final VmNetworkInterface iface, CompensationContext compensationContext, boolean allocateMac) { if (allocateMac) { iface.setMacAddress(getMacPoolManager().allocateNewMac()); } else { if (!getMacPoolManager().addMac(iface.getMacAddress())) { iface.setPlugged(false); getMacPoolManager().forceAddMac(iface.getMacAddress()); auditLogMacInUse(iface); log.infoFormat("VmInterfaceManager::Network Interface {0}'s MAC address is in use, " + "therefore it is being unplugged from VM.", iface.getName()); } } getVmNetworkInterfaceDao().save(iface); getVmNetworkStatisticsDao().save(iface.getStatistics()); compensationContext.snapshotNewEntity(iface); compensationContext.snapshotNewEntity(iface.getStatistics()); }

Target:
public void forceAdd(final VmNetworkInterface iface, CompensationContext compensationContext, boolean allocateMac) { if (allocateMac) { iface.setMacAddress(getMacPoolManager().allocateNewMac()); } else { getMacPoolManager().forceAddMac(iface.getMacAddress()); } getVmNetworkInterfaceDao().save(iface); getVmNetworkStatisticsDao().save(iface.getStatistics()); compensationContext.snapshotNewEntity(iface); compensationContext.snapshotNewEntity(iface.getStatistics()); }
Source:
private String getOriginConfigTypeName(String confItemType) { ServiceConfigTypeAmbariToOriginalPattern pattern = ServiceConfigTypeAmbariToOriginalPattern.findByAmbariConfType(confItemType); if (pattern != null) { return pattern.originConfType(); } return confItemType; }

Target:
private String getOriginConfigTypeName(String confItemType) { if (confItemType == null) { throw new IllegalArgumentException("confItemType can't be null"); } Optional<ServiceConfigTypeAmbariToOriginalPattern> pattern = ServiceConfigTypeAmbariToOriginalPattern.findByAmbariConfType(confItemType); return pattern.map(p -> p.originConfType()).orElse(confItemType); }
Source:
public void visit(DataChartTimestampDescriptor<?> desc) { setType(EnumSet.of(DescriptorType.NUMERICAL, DescriptorType.TIMESTAMP)); }

Target:
public void visit(DataChartTimestampDescriptor<?> desc) { fType.add(DescriptorType.TIMESTAMP); }