auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void startWorkload(Map<NodeId, Integer> poolSize) { Preconditions.checkState(progress == Progress.IDLE, "Workload should be idle to get started"); log.debug("Workload start requested"); for (NodeId nodeId : remotes.keySet()) { threads.put(nodeId, 0); delays.put(nodeId, 0); if (classesUrl != null) { RemoteExecutor executor = remotes.get(nodeId); AddUrlClassLoader addUrlClassLoaderCommand = AddUrlClassLoader.create(sessionId, classesUrl); log.info("Sending command to add a class loader with classes url to node {}", classesUrl, nodeId); executor.runSyncWithTimeout(addUrlClassLoaderCommand, Coordination.<Command>doNothing(), timeoutsConfiguration.getWorkloadStopTimeout()); log.info("Class loader with classes url has been added to node {}", classesUrl, nodeId); } } this.poolSize = poolSize; progress = Progress.STARTED; }

Target:
public void startWorkload(Map<NodeId, Integer> poolSize) { Preconditions.checkState(progress == Progress.IDLE, "Workload should be idle to get started"); log.debug("Workload start requested"); for (NodeId nodeId : remotes.keySet()) { threads.put(nodeId, 0); delays.put(nodeId, 0); if (classesUrl != null) { RemoteExecutor executor = remotes.get(nodeId); AddUrlClassLoader addUrlClassLoaderCommand = AddUrlClassLoader.create(sessionId, classesUrl); log.info("Sending command to add a class loader with classes url to node {}", classesUrl, nodeId); executor.runSyncWithTimeout(addUrlClassLoaderCommand, Coordination.<Command>doNothing(), timeoutsConfiguration.getWorkloadStartTimeout()); log.info("Class loader with classes url has been added to node {}", classesUrl, nodeId); } } this.poolSize = poolSize; progress = Progress.STARTED; }
Source:
public boolean useOnBlock(World world, BlockPos pos, IBlockState state, Vec3d hitPos, EnumFacing side, EntityPlayer player) { if (colour != null && usesLeft <= 0) { return false; } EnumActionResult result = CustomPaintHelper.INSTANCE.attemptPaintBlock(world, pos, state, hitPos, side, colour); if (result == EnumActionResult.SUCCESS) { ParticleUtil.showChangeColour(world, hitPos, colour); SoundUtil.playChangeColour(world, pos, colour); boolean isHolderCreative = player.isCreative(); if (!isHolderCreative) { usesLeft--; } if (usesLeft <= 0) { colour = null; usesLeft = 0; } return true; } return false; }

Target:
public boolean useOnBlock(World world, BlockPos pos, IBlockState state, Vec3d hitPos, EnumFacing side, EntityPlayer player) { if (colour != null && usesLeft <= 0) { return false; } EnumActionResult result = CustomPaintHelper.INSTANCE.attemptPaintBlock(world, pos, state, hitPos, side, colour); if (result == EnumActionResult.SUCCESS) { ParticleUtil.showChangeColour(world, hitPos, colour); SoundUtil.playChangeColour(world, pos, colour); if (!player.isCreative()) { usesLeft--; } if (usesLeft <= 0) { colour = null; usesLeft = 0; } return true; } return false; }
Source:
public Page getPage(Post op) { if (op == null) { return null; } Pages pages = getPages(op.board); if (pages == null) { return null; } else { for (Page page : pages.pages) { for (ThreadTime threadTime : page.threads) { if (op.no == threadTime.no) { return page; } } } } return null; }

Target:
public Page getPage(Post op) { if (op == null) { return null; } return findPage(op.board, op.no); }
Source:
public void testBigIntTypeWithNulls() throws Exception { try (TempFile tempFile = new TempFile()) { int rows = 10000; createSingleColumnFileWithNullValues(tempFile.getFile(), rows); try (OrcRecordReader reader = createCustomOrcRecordReader(tempFile, ORC, OrcPredicate.TRUE, BIGINT)) { assertEquals(reader.getReaderRowCount(), rows); assertEquals(reader.getReaderPosition(), 0); assertEquals(reader.getStreamReaderRetainedSizeInBytes(), 0); assertEquals(reader.getSystemMemoryUsage(), 0); while (true) { int batchSize = reader.nextBatch(); if (batchSize == -1) { break; } System.out.println("batchSize: " + batchSize); Block block = reader.readBlock(BIGINT, 0); System.out.println("block.getPositionCount(): " + block.getPositionCount()); assertEquals(block.getPositionCount(), batchSize); if (batchSize < MAX_BATCH_SIZE) { continue; } System.out.println("reader.getStreamReaderRetainedSizeInBytes() " + reader.getStreamReaderRetainedSizeInBytes()); System.out.println("reader.getCurrentStripeRetainedSizeInBytes() " + reader.getCurrentStripeRetainedSizeInBytes()); assertEquals(reader.getStreamReaderRetainedSizeInBytes(), batchSize * SIZE_OF_BYTE); assertBetweenInclusive(reader.getCurrentStripeRetainedSizeInBytes(), 3600L, 3700L); assertEquals(reader.getStreamReaderRetainedSizeInBytes() + reader.getCurrentStripeRetainedSizeInBytes(), reader.getSystemMemoryUsage()); } assertEquals(reader.nextBatch(), -1); assertEquals(reader.getReaderPosition(), rows); assertEquals(reader.getFilePosition(), reader.getReaderPosition()); } } }

Target:
public void testBigIntTypeWithNulls() throws Exception { int rows = 10000; OrcRecordReader reader = null; try (TempFile tempFile = createSingleColumnFileWithNullValues(rows)) { reader = createCustomOrcRecordReader(tempFile, ORC, OrcPredicate.TRUE, BIGINT, INITIAL_BATCH_SIZE); assertInitialRetainedSizes(reader, rows); long stripeReaderRetainedSize = reader.getCurrentStripeRetainedSizeInBytes(); long streamReaderRetainedSize = reader.getStreamReaderRetainedSizeInBytes(); long readerRetainedSize = reader.getRetainedSizeInBytes(); long readerSystemMemoryUsage = reader.getSystemMemoryUsage(); while (true) { int batchSize = reader.nextBatch(); if (batchSize == -1) { break; } Block block = reader.readBlock(BIGINT, 0); assertEquals(block.getPositionCount(), batchSize); if (batchSize < MAX_BATCH_SIZE) { continue; } assertGreaterThan(reader.getCurrentStripeRetainedSizeInBytes(), stripeReaderRetainedSize); assertGreaterThanOrEqual(reader.getStreamReaderRetainedSizeInBytes() - streamReaderRetainedSize, 1024L); assertGreaterThan(reader.getRetainedSizeInBytes() - readerRetainedSize, 1024L); assertGreaterThan(reader.getSystemMemoryUsage() - readerSystemMemoryUsage, 1024L); } } finally { if (reader != null) { reader.close(); } } assertClosedRetainedSizes(reader); }
Source:
private static String getAbbreviation(String name, String token) { StringBuilder abbrev = new StringBuilder(); if (name != null) { List<String> nameList = new ArrayList<String>(); for (String t : name.split(token)) { nameList.add(t); } RegExp re = RegExp.compile("[A-Za-z]+"); if (!re.test(nameList.get(0))) { abbrev.append(nameList.get(0).toUpperCase()); if (nameList.size() > 1) { abbrev.append(" ("+ nameList.get(nameList.size()-1).substring(0, 1).toUpperCase()+ ")"); } } else { for (String t : nameList) { abbrev.append(t.substring(0, 1).toUpperCase()); } } } return abbrev.toString(); }

Target:
private static String getAbbreviation(String name, String token) { StringBuilder abbrev = new StringBuilder(); if (name != null) { for (String t : name.split(token)) { abbrev.append(t.substring(0, 1).toUpperCase()); } } return abbrev.toString(); }
Source:
public List<DavResource> list(String url, int depth, boolean allProp) throws IOException { if (allProp) { Propfind body = new Propfind(); body.setAllprop(new Allprop()); return list(url, depth, body); } else { return list(url, depth, new HashMap()); } }

Target:
public List<DavResource> list(String url, int depth, boolean allProp) throws IOException { if (allProp) { Propfind body = new Propfind(); body.setAllprop(new Allprop()); return list(url, depth, body); } else { return list(url, depth, Collections.<QName>emptySet()); } }
Source:
protected boolean checkDescription(final String description, final List<String> resultList) { for (final String item : resultList) { if (description != null && !description.contains(item)) { return false; } } return true; }

Target:
protected boolean checkDescription(final String description, final List<String> resultList) { if (description == null) { return true; } for (final String item : resultList) { if (!description.contains(item)) { return false; } } return true; }
Source:
public int read(int offset, int[] positions, int positionCount) { outputPositions = initializeOutputPositions(outputPositions, positions, positionCount); outputPositionCount = positionCount; return outputPositionCount; }

Target:
public int read(int offset, int[] positions, int positionCount) { outputPositions = initializeOutputPositions(outputPositions, positions, positionCount); return positionCount; }
Source:
public void testMapperParametersFromEnv() throws Exception { String authKeyUrlParam = "myAuthKeyParams"; String filterName = "testAuthKeyParams2"; AuthenticationKeyFilterConfig config = new AuthenticationKeyFilterConfig(); config.setAllowEnvParametrization(true); config.setClassName(GeoServerAuthenticationKeyFilter.class.getName()); config.setName(filterName); config.setUserGroupServiceName("ug1"); config.setAuthKeyParamName(authKeyUrlParam); config.setAuthKeyMapperName("fakeMapper"); final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class); System.setProperty("authkey_param1", "value1"); System.setProperty("authkey_param2", "value2"); try { Map<String, String> mapperParams = new HashMap<String, String>(); mapperParams.put("param1", "${authkey_param1}"); mapperParams.put("param2", "${authkey_param2}"); config.setMapperParameters(mapperParams); getSecurityManager().saveFilter(config); GeoServerAuthenticationKeyFilter filter = (GeoServerAuthenticationKeyFilter) getSecurityManager().loadFilter(filterName); assertTrue(filter.getMapper() instanceof FakeMapper); FakeMapper fakeMapper = (FakeMapper) filter.getMapper(); assertEquals("value1", fakeMapper.getMapperParameter("param1")); assertEquals("value2", fakeMapper.getMapperParameter("param2")); } finally { System.clearProperty("authkey_param1"); System.clearProperty("authkey_param2"); } }

Target:
public void testMapperParametersFromEnv() throws Exception { String authKeyUrlParam = "myAuthKeyParams"; String filterName = "testAuthKeyParams2"; AuthenticationKeyFilterConfig config = new AuthenticationKeyFilterConfig(); config.setClassName(GeoServerAuthenticationKeyFilter.class.getName()); config.setName(filterName); config.setUserGroupServiceName("ug1"); config.setAuthKeyParamName(authKeyUrlParam); config.setAuthKeyMapperName("fakeMapper"); final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class); System.setProperty("authkey_param1", "value1"); System.setProperty("authkey_param2", "value2"); try { Map<String, String> mapperParams = new HashMap<String, String>(); mapperParams.put("param1", "${authkey_param1}"); mapperParams.put("param2", "${authkey_param2}"); config.setMapperParameters(mapperParams); getSecurityManager().saveFilter(config); GeoServerAuthenticationKeyFilter filter = (GeoServerAuthenticationKeyFilter) getSecurityManager().loadFilter(filterName); assertTrue(filter.getMapper() instanceof FakeMapper); FakeMapper fakeMapper = (FakeMapper) filter.getMapper(); assertEquals("value1", fakeMapper.getMapperParameter("param1")); assertEquals("value2", fakeMapper.getMapperParameter("param2")); } finally { System.clearProperty("authkey_param1"); System.clearProperty("authkey_param2"); } }
Source:
public static void addTypesToConnection(PGConnection connection) throws SQLException { Iterator it = TYPES.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); connection.addDataType((String) pair.getValue(), (Class) pair.getKey()); } }

Target:
void addTypesToConnection(PGConnection connection) { types.forEach((clazz, type) -> Unchecked.<String, Class>biConsumer(connection::addDataType).accept(type, clazz)); }
Source:
public AccessResult checkAccess(final String inPkg, final String forImport) { final AccessResult result; final AccessResult returnValue = localCheckAccess(inPkg, forImport); if (returnValue != AccessResult.UNKNOWN) { result = returnValue; } else if (parent == null) { if (strategyOnMismatch != null && strategyOnMismatch.equals(ImportControlOption.ALLOWED)) { result = AccessResult.ALLOWED; } else { result = AccessResult.DISALLOWED; } } else { if (strategyOnMismatch == null) { result = parent.checkAccess(inPkg, forImport); } else { switch (strategyOnMismatch) { case ALLOWED: result = AccessResult.ALLOWED; break; case DISALLOWED: result = AccessResult.DISALLOWED; break; default: result = parent.checkAccess(inPkg, forImport); break; } } } return result; }

Target:
public AccessResult checkAccess(final String inPkg, final String forImport) { final AccessResult result; final AccessResult returnValue = localCheckAccess(inPkg, forImport); if (returnValue != AccessResult.UNKNOWN) { result = returnValue; } else if (parent == null) { if (strategyOnMismatch == MismatchStrategy.ALLOWED) { result = AccessResult.ALLOWED; } else { result = AccessResult.DISALLOWED; } } else { if (strategyOnMismatch == MismatchStrategy.ALLOWED) { result = AccessResult.ALLOWED; } else if (strategyOnMismatch == MismatchStrategy.DISALLOWED) { result = AccessResult.DISALLOWED; } else { result = parent.checkAccess(inPkg, forImport); } } return result; }
Source:
public double calculateMagicPower() { return calculateWoodMagicFactor() * calculateWoodMagicFactor() * this.getLengthInches(); }

Target:
public double calculateMagicPower() { return calculateWoodMagicFactor() * calculateWoodMagicFactor() * getLengthInches(); }
Source:
public void load() { OptionBuilder<DatasetRepository> builder = new URIBuilder(); Registration.register( new URIPattern("file:/*path?absolute=true"), new URIPattern("file:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("file:*path"), new URIPattern("file:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("hdfs:/*path?absolute=true"), new URIPattern("hdfs:/*path/:namespace/:dataset?absolute=true"), builder ); Registration.register( new URIPattern("hdfs:*path"), new URIPattern("hdfs:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("webhdfs:/*path?absolute=true"), new URIPattern("webhdfs:/*path/:namespace/:dataset?absolute=true"), builder ); Registration.register( new URIPattern("webhdfs:*path"), new URIPattern("webhdfs:*path/:namespace/:dataset"), builder); }

Target:
public void load() { OptionBuilder<DatasetRepository> builder = new URIBuilder(); Registration.register( new URIPattern("file:/*path?absolute=true"), new URIPattern("file:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("file:*path"), new URIPattern("file:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("hdfs:/*path?absolute=true"), new URIPattern("hdfs:/*path/:namespace/:dataset?absolute=true"), builder ); Registration.register( new URIPattern("hdfs:*path"), new URIPattern("hdfs:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("webhdfs:/*path?absolute=true"), new URIPattern("webhdfs:/*path/:namespace/:dataset?absolute=true"), builder ); }
Source:
public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) { final BindList bindList = (BindList) annotation; final String name = ParameterUtil.findParameterName(bindList.value(), param) .orElseThrow(() -> new UnsupportedOperationException("A @BindList parameter was not given a name, " + "and parameter name data is not present in the class file, for: " + param.getDeclaringExecutable() + "::" + param)); return (stmt, arg) -> { if (arg == null || IterableLike.isEmpty(arg)) { switch (bindList.onEmpty()) { case VOID: stmt.define(name, ""); return; case NULL: stmt.define(name, "null"); return; case JAVA_NULL: stmt.define(name, null); return; case THROW: String msg = arg == null ? "argument is null; null was explicitly forbidden on this instance of BindList" : "argument is empty; emptiness was explicitly forbidden on this instance of BindList"; throw new IllegalArgumentException(msg); default: throw new IllegalStateException(VALUE_NOT_HANDLED_MESSAGE); } } stmt.bindList(name, IterableLike.toList(arg)); }; }

Target:
public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) { final BindList bindList = (BindList) annotation; final String name = ParameterUtil.findParameterName(bindList.value(), param) .orElseThrow(() -> new UnsupportedOperationException("A @BindList parameter was not given a name, " + "and parameter name data is not present in the class file, for: " + param.getDeclaringExecutable() + "::" + param)); return (stmt, arg) -> { if (arg == null || IterableLike.isEmpty(arg)) { bindList.onEmpty().define(stmt, name); } else { stmt.bindList(name, IterableLike.toList(arg)); } }; }
Source:
private static String parseOrcSchema(String configuredSchema) { try { co.cask.cdap.api.data.schema.Schema schemaObj = co.cask.cdap.api.data.schema.Schema.parseJson(configuredSchema); StringBuilder builder = new StringBuilder(); HiveSchemaConverter.appendType(builder, schemaObj); return builder.toString(); } catch (IOException e) { LOG.debug("{} is not a valid schema", configuredSchema, e); throw new IllegalArgumentException(String.format("%s is not a valid schema", configuredSchema), e); } catch (UnsupportedTypeException e) { throw new IllegalArgumentException(String.format("Could not create hive schema from %s", configuredSchema), e); } }

Target:
private static String parseOrcSchema(String configuredSchema) { try { co.cask.cdap.api.data.schema.Schema schemaObj = co.cask.cdap.api.data.schema.Schema.parseJson(configuredSchema); StringBuilder builder = new StringBuilder(); HiveSchemaConverter.appendType(builder, schemaObj); return builder.toString(); } catch (IOException e) { throw new IllegalArgumentException(String.format("%s is not a valid schema", configuredSchema), e); } catch (UnsupportedTypeException e) { throw new IllegalArgumentException(String.format("Could not create hive schema from %s", configuredSchema), e); } }
Source:
private void testShhAuthenticationSuccessfull(String username, String host) throws IOException, UserAuthException { String sanitizedUserName = SanitizerUtil.sanitizeWorkloadUsername(username); SSHClient client = getSshClient(host); client.authPassword(sanitizedUserName, MOCK_UMS_PASSWORD); client.close(); }

Target:
private void testShhAuthenticationSuccessfull(String username, String host) throws IOException, UserAuthException { SSHClient client = getSshClient(host); client.authPassword(username, MOCK_UMS_PASSWORD); client.close(); }
Source:
private synchronized void scheduleRefresh(long delay, Runnable uiTask) { refreshUiJob.cancel(); refreshUiJob.uiTask.compareAndSet(null, uiTask); refreshUiJob.schedule(delay); }

Target:
private synchronized void scheduleRefresh(long delay, Runnable uiTask) { System.out.println( "t=" + System.currentTimeMillis() + " scheduling " + delay); refreshUiJob.uiTask.compareAndSet(null, uiTask); refreshUiJob.schedule(delay); }
Source:
public void handle(StateContext state, RootCollectionRelationshipContext ctx) { EntityDictionary dictionary = state.getRequestScope().getDictionary(); String entityName = ctx.entity().term().getText(); String id = ctx.entity().id().getText(); Class<?> entityClass = dictionary.getEntityClass(entityName); if (entityClass == null || !dictionary.isRoot(entityClass)) { throw new ForbiddenEntityException(); } PersistentResource record = PersistentResource.loadRecord(entityClass, id, state.getRequestScope()); String relationName = ctx.relationship().term().getText(); try { Optional<FilterExpression> filterExpression = state.getRequestScope().getExpressionForRelation(record, relationName); record.getRelationCheckedFiltered(relationName, filterExpression, Optional.empty(), Optional.empty()); } catch (InvalidAttributeException e) { throw new InvalidCollectionException(relationName); } state.setState(new RelationshipTerminalState(record, relationName)); }

Target:
public void handle(StateContext state, RootCollectionRelationshipContext ctx) { EntityDictionary dictionary = state.getRequestScope().getDictionary(); String entityName = ctx.entity().term().getText(); String id = ctx.entity().id().getText(); Class<?> entityClass = dictionary.getEntityClass(entityName); if (entityClass == null || !dictionary.isRoot(entityClass)) { throw new ForbiddenAccessException(entityName); } PersistentResource record = PersistentResource.loadRecord(entityClass, id, state.getRequestScope()); String relationName = ctx.relationship().term().getText(); try { Optional<FilterExpression> filterExpression = state.getRequestScope().getExpressionForRelation(record, relationName); record.getRelationCheckedFiltered(relationName, filterExpression, Optional.empty(), Optional.empty()); } catch (InvalidAttributeException e) { throw new ForbiddenAccessException(entityName); } state.setState(new RelationshipTerminalState(record, relationName)); }
Source:
Pair<Long, NavigableMap<String, Long>> getValidDataSizeByLogSegment(TimeRange timeRange) throws StoreException { ScanResults currentScanResults = scanResults.get(); Pair<Long, NavigableMap<String, Long>> retValue = null; long deleteAndExpirationRefTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (deleteAndExpirationRefTimeInMs != -1) { retValue = currentScanResults.getValidSizePerLogSegment(deleteAndExpirationRefTimeInMs); } if (retValue == null) { if (isScanning) { deleteAndExpirationRefTimeInMs = getLogSegmentRefTimeMs(indexScanner.newScanResults, timeRange); if (deleteAndExpirationRefTimeInMs != -1) { synchronized (scanningLock) { while (isScanning) { try { scanningLock.wait(); } catch (InterruptedException e) { } } } retValue = getValidDataSizeByLogSegment(timeRange); } } if (retValue == null) { deleteAndExpirationRefTimeInMs = timeRange.getEndTimeInMs(); retValue = new Pair<>(deleteAndExpirationRefTimeInMs, collectValidDataSizeByLogSegment(deleteAndExpirationRefTimeInMs)); } } return retValue; }

Target:
Pair<Long, NavigableMap<String, Long>> getValidDataSizeByLogSegment(TimeRange timeRange) throws StoreException { if (!enabled.get()) { throw new StoreException(String.format("BlobStoreStats is not enabled or closing for store %s", storeId), StoreErrorCodes.Store_Shutting_Down); } ScanResults currentScanResults = scanResults.get(); Pair<Long, NavigableMap<String, Long>> retValue = null; long referenceTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (referenceTimeInMs != REF_TIME_OUT_OF_BOUNDS) { retValue = currentScanResults.getValidSizePerLogSegment(referenceTimeInMs); } else { if (isScanning && getLogSegmentRefTimeMs(indexScanner.newScanResults, timeRange) != REF_TIME_OUT_OF_BOUNDS) { scanLock.lock(); try { if (isScanning) { if (waitCondition.await(waitTimeoutInSecs, TimeUnit.SECONDS)) { currentScanResults = scanResults.get(); referenceTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (referenceTimeInMs != REF_TIME_OUT_OF_BOUNDS) { retValue = currentScanResults.getValidSizePerLogSegment(referenceTimeInMs); } } else { metrics.blobStoreStatsIndexScannerErrorCount.inc(); logger.error("Timed out while waiting for BlobStoreStats index scan to complete for store {}", storeId); } } else { currentScanResults = scanResults.get(); referenceTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (referenceTimeInMs != REF_TIME_OUT_OF_BOUNDS) { retValue = currentScanResults.getValidSizePerLogSegment(referenceTimeInMs); } } } catch (InterruptedException e) { metrics.blobStoreStatsIndexScannerErrorCount.inc(); throw new IllegalStateException( String.format("Illegal state, wait for scan to complete is interrupted for store %s", storeId), e); } finally { scanLock.unlock(); } } if (retValue == null) { referenceTimeInMs = timeRange.getEndTimeInMs(); retValue = new Pair<>(referenceTimeInMs, collectValidDataSizeByLogSegment(referenceTimeInMs)); } } return retValue; }
Source:
public CoverageOverlay(final Context aContext, final String coverageUrl, MapView mapView) { super(aContext); final ITileSource coverageTileSource = new XYTileSource("Mozilla Location Service Coverage Map", null, 12, 13, AbstractMapOverlay.TILE_PIXEL_SIZE, ".png", new String[] { coverageUrl }); this.setLoadingBackgroundColor(Color.TRANSPARENT); mTileProvider.setTileRequestCompleteHandler(new SimpleInvalidationHandler(mapView)); mTileProvider.setTileSource(coverageTileSource); }

Target:
public CoverageOverlay(final Context aContext, final String coverageUrl, MapView mapView) { super(aContext); final ITileSource coverageTileSource = new XYTileSource("Mozilla Location Service Coverage Map", null, MIN_ZOOM_LEVEL_OF_MAP, MIN_ZOOM_LEVEL_OF_MAP, AbstractMapOverlay.TILE_PIXEL_SIZE, ".png", new String[] { coverageUrl }); this.setLoadingBackgroundColor(Color.TRANSPARENT); mTileProvider.setTileRequestCompleteHandler(new SimpleInvalidationHandler(mapView)); mTileProvider.setTileSource(coverageTileSource); }
Source:
public void onNeutralClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_QUICK_START_DIALOG: AppPrefs.setQuickStartDisabled(true); AnalyticsTracker.track(AnalyticsTracker.Stat.QUICK_START_REQUEST_NEUTRAL_TAPPED); break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }

Target:
public void onNeutralClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_QUICK_START_DIALOG: AppPrefs.setQuickStartDisabled(true); AnalyticsTracker.track(Stat.QUICK_START_REQUEST_DIALOG_NEUTRAL_TAPPED); break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }
Source:
public LogCSVWriter(String filename, String dirname) throws FileNotFoundException, RuntimeException { try{ File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + File.separator + dirname); if (!dir.exists()) dir.mkdirs(); Log.d(TAG, "Path is " + sdCard.getAbsolutePath() + File.separator + dirname); File file = new File(dir, filename); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); this.buf = new BufferedWriter(osw); this.isFirstLine = true; Log.d(TAG, "Constructed the LogCSVWriter"); } catch (Exception e) { e.printStackTrace(); } }

Target:
public LogCSVWriter(String filename, String dirname) throws FileNotFoundException, RuntimeException { try{ File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + File.separator + dirname); if (!dir.exists()) dir.mkdirs(); Log.d(TAG, "Path is " + sdCard.getAbsolutePath() + File.separator + dirname); File file = new File(dir, filename); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); this.buf = new BufferedWriter(osw); this.isFirstLine = true; Log.d(TAG, "Constructed the LogCSVWriter"); } catch (Exception e) { Log.e(TAG, "LogCSVWriter constructor failed"); } }
Source:
private boolean addImageTicketToDaemon(Guid imagedTicketId, String imagePath) { if (getParameters().getTransferType() == TransferType.Upload && !setVolumeLegalityInStorage(ILLEGAL_IMAGE)) { return false; } ImageTicket imageTicket = buildImageTicket(imagedTicketId, imagePath); AddImageTicketVDSCommandParameters transferCommandParams = new AddImageTicketVDSCommandParameters(getVdsId(), imageTicket); VDSReturnValue vdsRetVal; try { vdsRetVal = vdsBroker.runVdsCommand(VDSCommandType.AddImageTicket, transferCommandParams); } catch (RuntimeException e) { log.error("Failed to start image transfer session: {}", e.getMessage(), e); return false; } if (!vdsRetVal.getSucceeded()) { log.error("Failed to start image transfer session"); return false; } log.info("Started transfer session with ticket id {}, timeout seconds", imagedTicketId.toString(), imageTicket.getTimeout()); return true; }

Target:
private boolean addImageTicketToDaemon(Guid imagedTicketId, String imagePath) { if (getParameters().getTransferType() == TransferType.Upload && !setVolumeLegalityInStorage(ILLEGAL_IMAGE)) { return false; } ImageTicket ticket = buildImageTicket(imagedTicketId, imagePath); AddImageTicketVDSCommandParameters transferCommandParams = new AddImageTicketVDSCommandParameters(getVdsId(), ticket); VDSReturnValue vdsRetVal; try { vdsRetVal = vdsBroker.runVdsCommand(VDSCommandType.AddImageTicket, transferCommandParams); } catch (RuntimeException e) { log.error("Failed to start image transfer session: {}", e.getMessage(), e); return false; } if (!vdsRetVal.getSucceeded()) { log.error("Failed to start image transfer session"); return false; } log.info("Started transfer session with ticket id {}, timeout seconds", imagedTicketId.toString(), ticket.getTimeout()); return true; }
Source:
private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); WidgetFactory.label(SWT.NONE).text(UrlHandlerPreferencePage_Handler_Label).create(handlerComposite); handlerLocation = WidgetFactory.text(SWT.READ_ONLY | SWT.BORDER) .supplyLayoutData(() -> new GridData(SWT.FILL, SWT.CENTER, true, false)).create(handlerComposite); handlerComposite.setVisible(false); }

Target:
private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); WidgetFactory.label(SWT.NONE).text(UrlHandlerPreferencePage_Handler_Label).create(handlerComposite); handlerLocation = WidgetFactory.text(SWT.READ_ONLY | SWT.BORDER) .layoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)).create(handlerComposite); handlerComposite.setVisible(false); }
Source:
public void start() throws XAException, SystemException, InvalidTransactionException, IllegalStateException, NamingException { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(new InitialContext()).resume(tx); }

Target:
public void start() throws XAException, SystemException, InvalidTransactionException { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(ctx).resume(tx); }
Source:
public void assertAll() { if (!m_errors.isEmpty()) { StringBuilder sb = new StringBuilder("The following asserts failed:"); boolean first = true; for (AssertionError error : m_errors.keySet()) { if (first) { first = false; } else { sb.append(","); } sb.append("\n\t"); sb.append(error.getMessage()); Throwable cause = error.getCause(); while (cause != null) { sb.append(" ").append(cause.getMessage()); cause = cause.getCause(); } sb.append(StackTraceTools.formatByStackTrace(error.getStackTrace()[4])); } throw new AssertionError(sb.toString()); } }

Target:
public void assertAll() { if (!m_errors.isEmpty()) { StringBuilder sb = new StringBuilder("The following asserts failed:"); boolean first = true; for (AssertionError error : m_errors.keySet()) { if (first) { first = false; } else { sb.append(","); } sb.append("\n\t"); sb.append(getErrorDetails(error)); } throw new AssertionError(sb.toString()); } }
Source:
public static final AbstractTextColumn<Disk> getLogicalNameColumn(String sortBy) { AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() { @Override public String getValue(Disk object) { if (object.getDiskVmElements().size() == 1) { return object.getDiskVmElements().iterator().next().getLogicalName(); } return null; } }; return makeSortable(column, sortBy); }

Target:
public static AbstractTextColumn<Disk> getLogicalNameColumn(String sortBy) { AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() { @Override public String getValue(Disk object) { if (object.getDiskVmElements().size() == 1) { return object.getDiskVmElements().iterator().next().getLogicalName(); } return null; } }; return makeSortable(column, sortBy); }
Source:
private Font makeFont(Font font, String boldKey, String italicKey) { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); boolean bold = store.getBoolean(boldKey); boolean italic = store.getBoolean(italicKey); int style = SWT.NONE; if(bold) style |= SWT.BOLD; if(italic) style |= SWT.ITALIC; if(style == SWT.NONE) return font; Font modified = fonts.get(style); if(modified == null) { FontData fontData = font.getFontData()[0]; modified = new Font(font.getDevice(), fontData.getName(), fontData.getHeight(), fontData.getStyle() | style); fonts.put(style, modified); } return modified; }

Target:
private Font makeFont(Font font, String boldKey, String italicKey) { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); int style = SWT.NONE; if (store.getBoolean(boldKey)) style |= SWT.BOLD; if (store.getBoolean(italicKey)) style |= SWT.ITALIC; if (style == SWT.NONE) return font; Font modified = fonts.get(style); if (modified == null) { FontData fontData = font.getFontData()[0]; modified = new Font(font.getDevice(), fontData.getName(), fontData.getHeight(), fontData.getStyle() | style); fonts.put(style, modified); } return modified; }
Source:
public void execute(Context context) throws SQLException { context.execute(new AddColumnsBuilder(getDialect(), "users") .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_type") .setIsNullable(true) .setLimit(40) .build()) .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_key") .setIsNullable(true) .setLimit(64) .build()) .build()); }

Target:
public void execute(Context context) throws SQLException { context.execute(new AddColumnsBuilder(getDialect(), "users") .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_type") .setIsNullable(true) .setLimit(40) .build()) .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_value") .setIsNullable(true) .setLimit(40) .build()) .build()); }
Source:
public boolean shouldInline(PushAttachmentsInline inlinePreference) { if (inlinePreference == PushAttachmentsInline.False || inlinePreference == PushAttachmentsInline.Small && this.isLarge()) { logger.info("inline false"); return false; } else { logger.info("inline true"); return true; } }

Target:
public boolean shouldInline(PushAttachmentsInline inlinePreference) { if (inlinePreference == PushAttachmentsInline.False || inlinePreference == PushAttachmentsInline.Small && this.isLarge()) { logger.finer("inline false"); return false; } else { logger.finer("inline true"); return true; } }
Source:
public void EditAccount_001_closeAccount() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); EditAccount editAccount = new EditAccount(driver, testedWiki, credentials.userNameClosedAccount); editAccount.closeAccount(PageContent.caption); }

Target:
public void EditAccount_001_closeAccount() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); EditAccount editAccount = new EditAccount(driver, testedWiki, credentials.userNameClosedAccount); editAccount.closeAccount(PageContent.caption); editAccount.verifyAccountClosedMessage(); }
Source:
public void testWriteAndReadAsyncVCFHeaderless() throws IOException { final File fakeVCFFile = VariantBaseTest.createTempFile("testWriteAndReadAsyncVCFHeaderless.", ".vcf"); Tribble.indexFile(fakeVCFFile).deleteOnExit(); Set<VCFHeaderLine> metaData = new HashSet<VCFHeaderLine>(); Set<String> additionalColumns = new HashSet<String>(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile).setReferenceDictionary(sequenceDict) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY, Options.USE_ASYNC_IO)) .build()) { writer.setVCFHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } final VCFCodec codec = new VCFCodec(); codec.setVCFHeader(header, VCFHeaderVersion.VCF4_2); try (FileInputStream fis = new FileInputStream(fakeVCFFile)) { AsciiLineReaderIterator iterator; iterator = new AsciiLineReaderIterator(new AsciiLineReader(fis)); int counter = 0; while (iterator.hasNext()) { VariantContext context = codec.decode(iterator.next()); counter++; } Assert.assertEquals(counter, 2); } }

Target:
public void testWriteAndReadAsyncVCFHeaderless() throws IOException { final File fakeVCFFile = VariantBaseTest.createTempFile("testWriteAndReadAsyncVCFHeaderless.", ".vcf"); fakeVCFFile.deleteOnExit(); Tribble.indexFile(fakeVCFFile).deleteOnExit(); final Set<VCFHeaderLine> metaData = new HashSet<>(); final Set<String> additionalColumns = new HashSet<>(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile).setReferenceDictionary(sequenceDict) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY, Options.USE_ASYNC_IO)) .build()) { writer.setVCFHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } final VCFCodec codec = new VCFCodec(); codec.setVCFHeader(header, VCFHeaderVersion.VCF4_2); try (final FileInputStream fis = new FileInputStream(fakeVCFFile)) { final AsciiLineReaderIterator iterator = new AsciiLineReaderIterator(new AsciiLineReader(fis)); int counter = 0; while (iterator.hasNext()) { VariantContext context = codec.decode(iterator.next()); counter++; } Assert.assertEquals(counter, 2); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DirectoryV3DevicesPostResponse)) return false; DirectoryV3DevicesPostResponse that = (DirectoryV3DevicesPostResponse) o; return Objects.equals(getCode(), that.getCode()) && Objects.equals(qrcode, that.qrcode) && Objects.equals(getDeviceId(), that.getDeviceId()); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DirectoryV3DevicesPostResponse)) return false; DirectoryV3DevicesPostResponse that = (DirectoryV3DevicesPostResponse) o; return Objects.equals(getCode(), that.getCode()) && Objects.equals(getQRCode(), that.getQRCode()) && Objects.equals(getDeviceId(), that.getDeviceId()); }
Source:
public void testConnectingToRM() throws Exception { conf.set(YarnConfiguration.CLIENT_FAILOVER_NO_HA_PROXY_PROVIDER, AutoRefreshNoHARMFailoverProxyProvider.class.getName()); MiniYARNCluster cluster = new MiniYARNCluster( "testRestartedRMNegative", NODE_MANAGER_COUNT, 1, 1); YarnClient rmClient = null; try { cluster.init(conf); cluster.start(); final Configuration yarnConf = cluster.getConfig(); rmClient = YarnClient.createYarnClient(); rmClient.init(yarnConf); rmClient.start(); List<NodeReport> nodeReports = rmClient.getNodeReports(); Assert.assertEquals( "The proxy didn't get expected number of node reports", NODE_MANAGER_COUNT, nodeReports.size()); } finally { if (rmClient != null) { rmClient.stop(); } cluster.stop(); } }

Target:
public void testConnectingToRM() throws Exception { conf.setClass(YarnConfiguration.CLIENT_FAILOVER_NO_HA_PROXY_PROVIDER, AutoRefreshNoHARMFailoverProxyProvider.class, RMFailoverProxyProvider.class); MiniYARNCluster cluster = new MiniYARNCluster("testRestartedRMNegative", NUMNODEMANAGERS, 1, 1); YarnClient rmClient = null; try { cluster.init(conf); cluster.start(); final Configuration yarnConf = cluster.getConfig(); rmClient = YarnClient.createYarnClient(); rmClient.init(yarnConf); rmClient.start(); List <NodeReport> nodeReports = rmClient.getNodeReports(); assertEquals( "The proxy didn't get expected number of node reports", NUMNODEMANAGERS, nodeReports.size()); } finally { if (rmClient != null) { rmClient.stop(); } cluster.stop(); } }
Source:
private void mockRequestBody(String json) throws IOException { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(json.getBytes()); when(mockServletInputStream.read(Matchers.any(), anyInt(), anyInt())).thenAnswer(invocationOnMock -> { Object[] args = invocationOnMock.getArguments(); byte[] output = (byte[]) args[0]; int offset = (int) args[1]; int length = (int) args[2]; return byteArrayInputStream.read(output, offset, length); }); when(request.getInputStream()).thenReturn(mockServletInputStream); }

Target:
private void mockRequestBody(String json) throws IOException { try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(json.getBytes())) { when(mockServletInputStream.read(Matchers.any(), anyInt(), anyInt())).thenAnswer(invocationOnMock -> { Object[] args = invocationOnMock.getArguments(); byte[] output = (byte[]) args[0]; int offset = (int) args[1]; int length = (int) args[2]; return byteArrayInputStream.read(output, offset, length); }); when(request.getInputStream()).thenReturn(mockServletInputStream); } }
Source:
private int getStatusCode(HttpURLConnection connection) throws IOException { int statusCode = HttpURLConnection.HTTP_BAD_REQUEST; try { statusCode = connection.getResponseCode(); } catch (IOException ex) { if (Build.VERSION.SDK_INT < 16) { if (ex.getMessage().equals(UNAUTHORIZED_ERROR_MESSAGE_PRE18)) { statusCode = HttpURLConnection.HTTP_UNAUTHORIZED; } } else { statusCode = connection.getResponseCode(); } if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_UNAUTHORIZED) { throw ex; } } Logger.v(TAG, "Status code:" + statusCode); return statusCode; }

Target:
private static int getStatusCode(HttpURLConnection connection) throws IOException { int statusCode = HttpURLConnection.HTTP_BAD_REQUEST; try { statusCode = connection.getResponseCode(); } catch (IOException ex) { if (Build.VERSION.SDK_INT < 16) { if (ex.getMessage().equals(UNAUTHORIZED_ERROR_MESSAGE_PRE18)) { statusCode = HttpURLConnection.HTTP_UNAUTHORIZED; } } else { statusCode = connection.getResponseCode(); } if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_UNAUTHORIZED) { throw ex; } } Logger.v(TAG, "Status code:" + statusCode); return statusCode; }
Source:
private PersonFunction getDelegateFunction(ExecutionYear executionYear, final Person person) { PersonFunction delegateFunction = null; if (person.hasStudent()) { final Student student = person.getStudent(); List<Registration> activeRegistrations = new ArrayList<Registration>(student.getActiveRegistrations()); Collections.sort(activeRegistrations, Registration.COMPARATOR_BY_START_DATE); for (Registration registration : activeRegistrations) { delegateFunction = registration.getDegree().getMostSignificantDelegateFunctionForStudent(student, executionYear); if (delegateFunction != null && delegateFunction.isActive()) { break; } delegateFunction = null; } } else { delegateFunction = person.getActiveGGAEDelegatePersonFunction(); } return delegateFunction; }

Target:
private PersonFunction getDelegateFunction(ExecutionYear executionYear, final Person person) { PersonFunction delegateFunction = null; if (person.hasStudent()) { final Student student = person.getStudent(); List<Registration> activeRegistrations = new ArrayList<Registration>(student.getActiveRegistrations()); Collections.sort(activeRegistrations, Registration.COMPARATOR_BY_START_DATE); for (Registration registration : activeRegistrations) { delegateFunction = registration.getDegree().getMostSignificantDelegateFunctionForStudent(student, executionYear); if (delegateFunction != null && delegateFunction.isActive()) { return delegateFunction; } } } else { return person.getActiveGGAEDelegatePersonFunction(); } return null; }
Source:
public void testDefaultJobName() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromCollection(new DummySplittableIterator<>(), BasicTypeInfo.INT_TYPE_INFO).addSink(new DiscardingSink<>()); StreamGraph streamGraph = env.getStreamGraph(); assertEquals(StreamExecutionEnvironment.DEFAULT_JOB_NAME, streamGraph.getJobName()); }

Target:
public void testDefaultJobName() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); testJobName(StreamExecutionEnvironment.DEFAULT_JOB_NAME, env); }
Source:
public void testSerializeVersionHeader() throws IOException, ClassNotFoundException { VersionHeader versionHeader = new VersionHeader(); versionHeader.setVersionedItem("SomeThing"); versionHeader.setVersionString("1.0.1"); VersionHeader deserialized = TestUtil.serializeAndDeserialize(versionHeader); Assert.assertEquals(deserialized, versionHeader); }

Target:
public void testSerializeVersionHeader() throws IOException, ClassNotFoundException { final VersionHeader versionHeader = new VersionHeader(); versionHeader.setVersionedItem("SomeThing"); versionHeader.setVersionString("1.0.1"); final VersionHeader deserialized = TestUtil.serializeAndDeserialize(versionHeader); Assert.assertEquals(deserialized, versionHeader); }
Source:
protected DataContainer waitUntilDataContainerWillBeIteratedOn(final Cache<?, ?> cache, final CheckPoint checkPoint) { DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer); DataContainer mocaContainer = mock(DataContainer.class, withSettings().defaultAnswer(forwardedAnswer)); final AtomicInteger invocationCount = new AtomicInteger(); doAnswer(invocation -> { boolean waiting = false; if (invocationCount.getAndIncrement() == 0) { waiting = true; checkPoint.trigger("pre_iterator_invoked"); checkPoint.awaitStrict("pre_iterator_released", 10, TimeUnit.SECONDS); } try { return forwardedAnswer.answer(invocation); } finally { invocationCount.getAndDecrement(); if (waiting) { checkPoint.trigger("post_iterator_invoked"); checkPoint.awaitStrict("post_iterator_released", 10, TimeUnit.SECONDS); } } }).when(mocaContainer).iterator(); TestingUtil.replaceComponent(cache, DataContainer.class, mocaContainer, true); return dataContainer; }

Target:
protected void waitUntilDataContainerWillBeIteratedOn(final Cache<?, ?> cache, final CheckPoint checkPoint) { DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer); DataContainer mocaContainer = mock(DataContainer.class, withSettings().defaultAnswer(forwardedAnswer)); final AtomicInteger invocationCount = new AtomicInteger(); doAnswer(invocation -> { boolean waiting = false; if (invocationCount.getAndIncrement() == 0) { waiting = true; checkPoint.trigger("pre_iterator_invoked"); checkPoint.awaitStrict("pre_iterator_released", 10, TimeUnit.SECONDS); } try { return forwardedAnswer.answer(invocation); } finally { invocationCount.getAndDecrement(); if (waiting) { checkPoint.trigger("post_iterator_invoked"); checkPoint.awaitStrict("post_iterator_released", 10, TimeUnit.SECONDS); } } }).when(mocaContainer).iterator(); TestingUtil.replaceComponent(cache, DataContainer.class, mocaContainer, true); }
Source:
private NetworkVO getDefaultNetwork (long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null ) return _networkDao.findById(_nicDao.findById(defaultNic.getId()).getNetworkId()); return null; }

Target:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) { return defaultNic.getNetworkId(); } return null; }