auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void dispose() { super.dispose(); getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); saveables.removeModelLifecycleListener(saveablesTracker); currentPart = null; currentSelection = null; pinPropertySheetAction = null; }

Target:
public void dispose() { super.dispose(); getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); if (saveables != null) { saveables.removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }
Source:
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { GoLiteralValue literal = ObjectUtils.tryCast(descriptor.getStartElement(), GoLiteralValue.class); GoStructType structType = getStructType(literal); List<GoElement> elements = structType != null ? literal.getElementList() : emptyList(); List<String> fieldDefinitionNames = structType != null ? getFieldDefinitionsNames(structType) : emptyList(); if (!areElementsNamesMatchesDefinitions(getNames(elements), fieldDefinitionNames)) return; replaceElementsByNamed(elements, fieldDefinitionNames, project); }

Target:
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = ObjectUtils.tryCast(descriptor.getStartElement(), GoElement.class); GoLiteralValue literal = element != null && element.isValid() ? PsiTreeUtil.getParentOfType(element, GoLiteralValue.class) : null; List<GoElement> elements = literal != null ? literal.getElementList() : emptyList(); List<GoNamedElement> definitions = getFieldDefinitions(getLiteralStructType(literal)); if (!areElementsKeysMatchesDefinitions(elements, definitions)) return; addKeysToElements(project, elements, definitions); }
Source:
public PinotQueryGeneratorContext visitProject(ProjectNode node, PinotQueryGeneratorContext contextIn) { PinotQueryGeneratorContext context = node.getSource().accept(this, contextIn); requireNonNull(context, "context is null"); LinkedHashMap<VariableReferenceExpression, Selection> newSelections = new LinkedHashMap<>(); node.getOutputVariables().forEach(variable -> { RowExpression expression = node.getAssignments().get(variable); PinotExpression pinotExpression = expression.accept(new PinotProjectExpressionConverter(typeManager, functionMetadataManager, session), context.getSelections()); newSelections.put( variable, new Selection(pinotExpression.getDefinition(), pinotExpression.getOrigin())); }); return context.withProject(newSelections); }

Target:
public PinotQueryGeneratorContext visitProject(ProjectNode node, PinotQueryGeneratorContext contextIn) { PinotQueryGeneratorContext context = node.getSource().accept(this, contextIn); requireNonNull(context, "context is null"); LinkedHashMap<VariableReferenceExpression, Selection> newSelections = new LinkedHashMap<>(); node.getOutputVariables().forEach(variable -> { RowExpression expression = node.getAssignments().get(variable); PinotExpression pinotExpression = expression.accept( contextIn.getVariablesInAggregation().contains(variable) ? new PinotAggregationProjectConverter(typeManager, functionMetadataManager, standardFunctionResolution, session) : pinotProjectExpressionConverter, context.getSelections()); newSelections.put( variable, new Selection(pinotExpression.getDefinition(), pinotExpression.getOrigin())); }); return context.withProject(newSelections); }
Source:
private void doUntilElementVisible(By by, Runnable f) { Boolean isElementDisplayed = false; changeImplicitWait(0, TimeUnit.MILLISECONDS); do { try { isElementDisplayed = driver.findElement(by).isDisplayed(); } catch (NoSuchElementException ignored) { f.run(); } } while(!isElementDisplayed); restoreDefaultImplicitWait(); }

Target:
private void doUntilElementVisible(By by, Runnable f) { doUntilElementVisible(by, f, 20); }
Source:
public void run() throws Exception { Runtime.getRuntime().addShutdownHook(new ShutdownHook()); server = buildServer(startServerArgs); if (Files.notExists(pidFile)) { Files.write(pidFile, Collections.singleton(Long.toString(org.wildfly.common.os.Process.getProcessId())), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); } else { log.pidFileAlreadyExists(pidFile, environment.getJBossHome()); } server.start(); }

Target:
public void run() throws Exception { Runtime.getRuntime().addShutdownHook(new ShutdownHook()); server = buildServer(startServerArgs); if (Files.notExists(pidFile)) { Files.write(pidFile, Collections.singleton(Long.toString(org.wildfly.common.os.Process.getProcessId())), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW); } else { throw log.pidFileAlreadyExists(pidFile, environment.getJBossHome()); } server.start(); }
Source:
public void setUp() { namingService.setObjectBucketName(objectBucketName); namingService.setStateBucketName(stateBucketName); namingService.setBucketPoolSize(16); namingService.setBucketKeySize(3); service.setBucketNamingService(namingService); ReflectionTestUtils.setField(service, "dataDir", dataDir); ReflectionTestUtils.setField(service, "expiration", 7); ReflectionTestUtils.setField(service, "urlGenerator", new S3URLGenerator()); ReflectionTestUtils.setField(service, "partCalculator", new SimplePartCalculator(20000)); mockService = mock(MetadataService.class); service.setMetadataService(mockService); service.setS3Client(s3Client); metadataEntity = MetadataEntity.builder() .id(objectId) .fileName("file_1") .access("open") .gnosId("an1") .projectCode("project") .build(); when(mockService.getAnalysisStateForMetadata(metadataEntity)).thenReturn("PUBLISHED"); when(mockService.getEntity(objectId)).thenReturn(metadataEntity); }

Target:
public void setUp() { namingService.setObjectBucketName(objectBucketName); namingService.setStateBucketName(stateBucketName); namingService.setBucketPoolSize(16); namingService.setBucketKeySize(3); service.setBucketNamingService(namingService); service.setS3Client(s3Client); ReflectionTestUtils.setField(service, "dataDir", dataDir); ReflectionTestUtils.setField(service, "expiration", 7); ReflectionTestUtils.setField(service, "urlGenerator", new S3URLGenerator()); ReflectionTestUtils.setField(service, "partCalculator", new SimplePartCalculator(20000)); setUpMockService(); }
Source:
public void renderSlotHighlights(IoMode mode) { SlotDefinition slotDef = tileEntity.getSlotDefinition(); for (Object object : inventorySlots.inventorySlots) { Slot invSlot = (Slot) object; if (invSlot.inventory == tileEntity) { if ((mode == IoMode.PULL || mode == IoMode.PUSH_PULL) && slotDef.isInputSlot(invSlot.getSlotIndex())) { renderSlotHighlight(invSlot, PULL_COLOR); } else if ((mode == IoMode.PUSH || mode == IoMode.PUSH_PULL) && slotDef.isOutputSlot(invSlot.getSlotIndex())) { renderSlotHighlight(invSlot, PUSH_COLOR); } } } }

Target:
public void renderSlotHighlights(IoMode mode) { SlotDefinition slotDef = tileEntity.getSlotDefinition(); for (Slot invSlot : (List<Slot>) inventorySlots.inventorySlots) { if (invSlot.inventory == tileEntity) { if ((mode == IoMode.PULL || mode == IoMode.PUSH_PULL) && slotDef.isInputSlot(invSlot.getSlotIndex())) { renderSlotHighlight(invSlot, PULL_COLOR); } else if ((mode == IoMode.PUSH || mode == IoMode.PUSH_PULL) && slotDef.isOutputSlot(invSlot.getSlotIndex())) { renderSlotHighlight(invSlot, PUSH_COLOR); } } } }
Source:
public Image getColumnImage(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return getIncomingChangesImage(); case 1: try { return getReviewStateImage(Integer.parseInt(reviewContainer.getCr())); } catch (Exception e) { break; } case 2: try { return getVerifiedStateImage(Integer.parseInt(reviewContainer.getV())); } catch (Exception e) { break; } } return null; }

Target:
public Image getColumnImage(Object element, int columnIndex) { TaskReview reviewContainer = (TaskReview) element; switch (columnIndex) { case 0: return getIncomingChangesImage(); case 1: return getReviewStateImage(reviewContainer.getCr()); case 2: return getVerifiedStateImage(reviewContainer.getV()); } return null; }
Source:
private TokenIntrospectionSuccessResponse introspect(String token) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); RequestEntity<String> requestEntity = new RequestEntity<>("token=" + token, headers, HttpMethod.POST, this.introspectionUri); TokenIntrospectionSuccessResponse response = asSuccess(parse(adapt(request(requestEntity)))); if (!response.isActive()) { throw new OAuth2AuthenticationException( invalidToken("Provided token [" + token + "] isn't active")); } return response; }

Target:
private TokenIntrospectionSuccessResponse introspect(String token) { return Optional.of(token) .map(this::buildRequest) .map(this::makeRequest) .map(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) .filter(TokenIntrospectionSuccessResponse::isActive) .orElseThrow(() -> new OAuth2AuthenticationException( invalidToken("Provided token [" + token + "] isn't active"))); }
Source:
public float getFloat(ByteBuffer buf, int position) { if (isNull(buf, position)) { throw new IllegalStateException("Cannot return float for Null Value"); } return delegate.getFloat(buf, position + Byte.BYTES); }

Target:
public float getFloat(ByteBuffer buf, int position) { if (buf.get(position) == NullHandling.IS_NULL_BYTE) { throw new IllegalStateException("Cannot return float for Null Value"); } return delegate.getFloat(buf, position + Byte.BYTES); }
Source:
public String buildFullLocation(String location, String backupId, String cloudPlatform) throws URISyntaxException { URI uri = new URI(location); String fullLocation; if ("aws".equalsIgnoreCase(cloudPlatform)) { if (uri.getScheme() != null && !uri.getScheme().startsWith("s3")) { throw new UnsupportedOperationException("Incorrect URL scheme for AWS cloud platform: " + location); } fullLocation = "s3://" + uri.getSchemeSpecificPart().replaceAll("^/+", ""); } else if ("azure".equalsIgnoreCase(cloudPlatform)) { if (uri.getScheme() != null && !uri.getScheme().startsWith("abfs")) { throw new UnsupportedOperationException("Incorrect URL scheme for Azure cloud platform: " + location); } fullLocation = "abfs://" + uri.getSchemeSpecificPart().replaceAll("^/+", ""); } else { throw new UnsupportedOperationException("Cloud platform " + cloudPlatform + "not supported for backup/restore"); } return fullLocation; }

Target:
String buildFullLocation(String location, String backupId, String cloudPlatform) throws URISyntaxException { URI uri = new URI(location); String suffix = '/' + backupId + "_database_backup"; String fullLocation; if (AWS.equalsIgnoreCase(cloudPlatform)) { fullLocation = "s3://" + uri.getSchemeSpecificPart().replaceAll("^/+", ""); } else if (AZURE.equalsIgnoreCase(cloudPlatform)) { fullLocation = "abfs://" + uri.getSchemeSpecificPart().replaceAll("^/+", ""); } else { throw new UnsupportedOperationException("Cloud platform not supported for backup/restore: " + cloudPlatform); } return fullLocation + suffix; }
Source:
private boolean shouldSkip() { if (skip != null && skipTests != null && !skip.equals(skipTests)) { getLog().warn( "Both parameter 'skipTests' and 'maven.test.skip' are set, 'skipTests' has a higher priority!"); } if (skipTests != null) { return skipTests; } if (skip != null) { return skip; } return false; }

Target:
protected boolean shouldSkip() { if (skip != null && skipTests != null && !skip.equals(skipTests)) { getLog().warn( "Both parameter 'skipTests' and 'maven.test.skip' are set, 'skipTests' has a higher priority!"); } if (skipTests != null) { return skipTests; } if (skip != null) { return skip; } return skipExec; }
Source:
public void selectHeader(Headers header) { waitForElementByElement(tablePropertiesDropdownOptions.get(0)); switch(header) { case None: tablePropertiesDropdownOptions.get(0).click(); break; case FirstRow: tablePropertiesDropdownOptions.get(1).click(); break; case FirstColumn: tablePropertiesDropdownOptions.get(2).click(); break; case Both: tablePropertiesDropdownOptions.get(3).click(); break; } PageObjectLogging.log("selectHeader", header.toString() + " header selected", true, driver); }

Target:
public void selectHeader(Headers header) { waitForElementByElement(tablePropertiesDropdownOptions.get(0)); Select headerDropdown = new Select(tablePropertiesDropdownOptions.get(0)); switch(header) { case None: headerDropdown.selectByIndex(header.ordinal()); break; case FirstRow: headerDropdown.selectByIndex(header.ordinal()); break; case FirstColumn: headerDropdown.selectByIndex(header.ordinal()); break; case Both: headerDropdown.selectByIndex(header.ordinal()); break; } PageObjectLogging.log("selectHeader", header.toString() + " header selected", true, driver); }
Source:
public Object processInvocation(InterceptorContext interceptorContext) throws Exception { final EJBComponent component = (EJBComponent) interceptorContext.getPrivateData(Component.class); if(!component.isExceptionLoggingEnabled()) { return interceptorContext.proceed(); } try { return interceptorContext.proceed(); } catch ( EJBComponentUnavailableException ex) { EjbLogger.EJB3_INVOCATION_LOGGER.warn(ex); throw ex; } catch (Throwable t) { final Method invokedMethod = interceptorContext.getMethod(); final ApplicationExceptionDetails appException = component.getApplicationException(t.getClass(), invokedMethod); if (appException == null) { EjbLogger.EJB3_INVOCATION_LOGGER.invocationFailed(component.getComponentName(), invokedMethod, t); } if (t instanceof Exception) { throw (Exception) t; } throw new Exception(t); } }

Target:
public Object processInvocation(InterceptorContext interceptorContext) throws Exception { final EJBComponent component = (EJBComponent) interceptorContext.getPrivateData(Component.class); if(!component.isExceptionLoggingEnabled()) { return interceptorContext.proceed(); } try { return interceptorContext.proceed(); } catch ( EJBComponentUnavailableException ex) { if ( EjbLogger.EJB3_INVOCATION_LOGGER.isTraceEnabled() ) EjbLogger.EJB3_INVOCATION_LOGGER.trace(ex.getMessage()); throw ex; } catch (Throwable t) { final Method invokedMethod = interceptorContext.getMethod(); final ApplicationExceptionDetails appException = component.getApplicationException(t.getClass(), invokedMethod); if (appException == null) { EjbLogger.EJB3_INVOCATION_LOGGER.invocationFailed(component.getComponentName(), invokedMethod, t); } if (t instanceof Exception) { throw (Exception) t; } throw new Exception(t); } }
Source:
public Response activate(Action action) { HotPlugUnplugVmNicParameters params = new HotPlugUnplugVmNicParameters(Guid.createGuidFromString(id), PlugAction.PLUG); BackendNicsResource parent = (BackendNicsResource) collection; params.setVmId(parent.parentId); return performAction(VdcActionType.HotPlugUnplugVmNic, params); }

Target:
public Response activate(Action action) { HotPlugUnplugVmNicParameters params = new HotPlugUnplugVmNicParameters(guid, PlugAction.PLUG); BackendNicsResource parent = (BackendNicsResource) collection; params.setVmId(parent.parentId); return performAction(VdcActionType.HotPlugUnplugVmNic, params); }
Source:
public void shouldCreateFutureFromFailedJavaCompletableFuture() { CompletableFuture<Integer> jFuture = new CompletableFuture<>(); jFuture.completeExceptionally(new RuntimeException("some")); final Future<Integer> future = Future.fromCompletableFuture(jFuture); assertFailed(future, RuntimeException.class); }

Target:
public void shouldCreateFutureFromFailedJavaCompletableFuture() { final CompletableFuture<Integer> jFuture = new CompletableFuture<>(); jFuture.completeExceptionally(new RuntimeException("some")); final Future<Integer> future = Future.fromCompletableFuture(jFuture); assertFailed(future, RuntimeException.class); }
Source:
public Option<String> getNewFragment(String uriFragment) { boolean contains = false; String newUriFragment = uriFragment; if (uriFragment.endsWith("@firstModelOperations")) { contains = true; newUriFragment = newUriFragment + ".0"; } if (uriFragment.contains("@firstModelOperations/")) { contains = true; newUriFragment = newUriFragment.replaceAll("@firstModelOperations/", "@firstModelOperations.0/"); } if (contains) { return Options.newSome(newUriFragment); } else { return super.getNewFragment(uriFragment); } }

Target:
public Option<String> getNewFragment(String uriFragment) { boolean contains = false; String newUriFragment = uriFragment; if (uriFragment.endsWith("@firstModelOperations")) { contains = true; newUriFragment = newUriFragment + ".0"; } else if (uriFragment.contains("@firstModelOperations/")) { contains = true; newUriFragment = newUriFragment.replaceAll("@firstModelOperations/", "@firstModelOperations.0/"); } if (contains) { return Options.newSome(newUriFragment); } else { return super.getNewFragment(uriFragment); } }
Source:
public JsonResourceMetadataResolver(final SamlIdPProperties samlIdPProperties, final OpenSamlConfigBean configBean) { super(samlIdPProperties, configBean); try { val inputStream = new ClassPathResource("metadata/sp-metadata-template.xml").getInputStream(); this.metadataTemplate = IOUtils.toString(inputStream, StandardCharsets.UTF_8); val md = samlIdPProperties.getMetadata(); val location = SpringExpressionLanguageValueResolver.getInstance().resolve(md.getLocation()); val normalizedLocation = location.startsWith("file:") ? location : "file:" + location; val resourceLoader = new DefaultResourceLoader(); val metadataDir = resourceLoader.getResource(normalizedLocation).getFile(); this.jsonResource = new FileSystemResource(new File(metadataDir, "saml-sp-metadata.json")); if (this.jsonResource.exists()) { this.metadataMap = readDecisionsFromJsonResource(); this.watcherService = new FileWatcherService(jsonResource.getFile(), file -> this.metadataMap = readDecisionsFromJsonResource()); this.watcherService.start(getClass().getSimpleName()); } } catch (final Exception e) { throw new IllegalArgumentException(e); } }

Target:
public JsonResourceMetadataResolver(final SamlIdPProperties samlIdPProperties, final OpenSamlConfigBean configBean) { super(samlIdPProperties, configBean); try { val inputStream = new ClassPathResource("metadata/sp-metadata-template.xml").getInputStream(); this.metadataTemplate = IOUtils.toString(inputStream, StandardCharsets.UTF_8); val md = samlIdPProperties.getMetadata(); val location = SpringExpressionLanguageValueResolver.getInstance().resolve(md.getLocation()); val metadataDir = ResourceUtils.getRawResourceFrom(location).getFile(); this.jsonResource = new FileSystemResource(new File(metadataDir, "saml-sp-metadata.json")); if (this.jsonResource.exists()) { this.metadataMap = readDecisionsFromJsonResource(); this.watcherService = new FileWatcherService(jsonResource.getFile(), file -> this.metadataMap = readDecisionsFromJsonResource()); this.watcherService.start(getClass().getSimpleName()); } } catch (final Exception e) { throw new IllegalArgumentException(e); } }
Source:
public void init() { initMocks(this); retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new SimpleRetryPolicy()); controller = new ReadPostsController(branchService, lastReadPostService, retryTemplate); }

Target:
public void init() { initMocks(this); retryTemplate = new RetryTemplate(); retryTemplate.setRetryPolicy(new NeverRetryPolicy()); controller = new ReadPostsController(branchService, lastReadPostService, retryTemplate); }
Source:
private void iccPinChanged(boolean success, int attemptsRemaining) { if(DBG) Log.d(TAG, "iccPinChanged success: "+success); if (!success) { setRemainingAttempts(true, attemptsRemaining); createCustomTextToast(getPinPasswordErrorMessage(attemptsRemaining)).show(); } else { Toast.makeText(getContext(), mRes.getString(R.string.sim_change_succeeded), Toast.LENGTH_SHORT) .show(); } resetDialogState(); }

Target:
private void iccPinChanged(boolean success, int attemptsRemaining) { if(DBG) Log.d(TAG, "iccPinChanged success: "+success); if (!success) { showCustomTextToast(getPinPasswordErrorMessage(attemptsRemaining)); } else { Toast.makeText(getContext(), mRes.getString(R.string.sim_change_succeeded), Toast.LENGTH_SHORT) .show(); } resetDialogState(); }
Source:
default Iterator<InventoryAdaptor> adaptors() { return InventoryAdaptor.of(this) .<Iterator<InventoryAdaptor>>map(Iterators::singletonIterator) .orElseGet(Collections::emptyIterator); }

Target:
default Iterator<InventoryAdaptor> adaptors() { return InventoryAdaptor.of(this) .map(Iterators::singletonIterator) .orElseThrow(UnsupportedOperationException::new); }
Source:
public static void main(String...args) { GlentParams params = new GlentParams(); JCommander.Builder builder = JCommander.newBuilder() .addObject(params); Map<String, Function<SparkSession, Dataset<Row>>> methods = GlentMethod.methods(); for (Map.Entry<String, Function<SparkSession, Dataset<Row>>> entry : methods.entrySet()) { builder.addCommand(entry.getKey(), entry.getValue()); } JCommander jCommander = builder.build(); jCommander.parse(args); if (params.help) { jCommander.usage(); System.exit(1); } Dataset<Row> result = methods.get(jCommander.getParsedCommand()) .apply(initSpark()); writeDf(result, params.outputTable, params.outputPartition); }

Target:
public static void main(String...args) { Params params = new Params(); JCommander.Builder builder = JCommander.newBuilder() .addObject(params); Map<String, Method> methods = Method.methods(); for (Map.Entry<String, Method> entry : methods.entrySet()) { builder.addCommand(entry.getKey(), entry.getValue()); } JCommander jCommander = builder.build(); jCommander.parse(args); if (params.help) { jCommander.usage(); System.exit(1); } Dataset<Row> result = methods.get(jCommander.getParsedCommand()) .apply(initSpark()); writeDf(result, params.outputTable, params.outputPartition); }
Source:
public final void commit(final CacheEntry entry, final Metadata metadata, final Flag operation, boolean l1Invalidation) { if (trace) { log.tracef("Trying to commit. Key=%s. Operation Flag=%s, L1 invalidation=%s", entry.getKey(), operation, l1Invalidation); } if (l1Invalidation || (operation == null && !trackStateTransfer && !trackXSiteStateTransfer)) { if (trace) { log.tracef("Committing key=%s. It is a L1 invalidation or a normal put and no tracking is enabled!", entry.getKey()); } entry.commit(dataContainer, metadata); return; } if (isTrackDisabled(operation)) { if (trace) { log.tracef("Not committing key=%s. It is a state transfer key but no track is enabled!", entry.getKey()); } return; } tracker.compute(entry.getKey(), new EquivalentConcurrentHashMapV8.BiFun<Object, DiscardPolicy, DiscardPolicy>() { @Override public DiscardPolicy apply(Object o, DiscardPolicy discardPolicy) { if (discardPolicy != null && discardPolicy.ignore(operation)) { if (trace) { log.tracef("Not committing key=%s. It was already overwritten! Discard policy=%s", entry.getKey(), discardPolicy); } return discardPolicy; } entry.commit(dataContainer, metadata); DiscardPolicy newDiscardPolicy = new DiscardPolicy(trackStateTransfer, trackXSiteStateTransfer); if (newDiscardPolicy.isDiscardNothing()) { newDiscardPolicy = null; } if (trace) { log.tracef("Committed key=%s. Old discard policy=%s. New discard policy=%s", entry.getKey(), discardPolicy, newDiscardPolicy); } return newDiscardPolicy; } }); }

Target:
public final void commit(final CacheEntry entry, final Metadata metadata, final Flag operation, boolean l1Invalidation) { if (trace) { log.tracef("Trying to commit. Key=%s. Operation Flag=%s, L1 invalidation=%s", entry.getKey(), operation, l1Invalidation); } if (l1Invalidation || (operation == null && !trackStateTransfer && !trackXSiteStateTransfer)) { if (trace) { log.tracef("Committing key=%s. It is a L1 invalidation or a normal put and no tracking is enabled!", entry.getKey()); } entry.commit(dataContainer, metadata); return; } if (isTrackDisabled(operation)) { if (trace) { log.tracef("Not committing key=%s. It is a state transfer key but no track is enabled!", entry.getKey()); } return; } tracker.compute(entry.getKey(), new EquivalentConcurrentHashMapV8.BiFun<Object, DiscardPolicy, DiscardPolicy>() { @Override public DiscardPolicy apply(Object o, DiscardPolicy discardPolicy) { if (discardPolicy != null && discardPolicy.ignore(operation)) { if (trace) { log.tracef("Not committing key=%s. It was already overwritten! Discard policy=%s", entry.getKey(), discardPolicy); } return discardPolicy; } entry.commit(dataContainer, metadata); DiscardPolicy newDiscardPolicy = calculateDiscardPolicy(); if (trace) { log.tracef("Committed key=%s. Old discard policy=%s. New discard policy=%s", entry.getKey(), discardPolicy, newDiscardPolicy); } return newDiscardPolicy; } }); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { String urlText = event.getParameter(PARAM_ID_URL); final URL url; if (urlText == null) { url = null; } else { try { url = new URL(urlText); } catch (MalformedURLException ex) { throw new ExecutionException("malformed URL:" + urlText, ex); } } final String browserId = event.getParameter(PARAM_ID_BROWSER_ID); final String name = event.getParameter(PARAM_ID_NAME); final String tooltip = event.getParameter(PARAM_ID_TOOLTIP); final IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench() .getBrowserSupport(); Shell shell = HandlerUtil.getActiveShell(event); Display display = shell == null ? Display.getCurrent() : shell.getDisplay(); display.asyncExec(new Runnable() { @Override public void run() { try { IWebBrowser browser = browserSupport.createBrowser( IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR, browserId, name, tooltip); browser.openURL(url); } catch (PartInitException ex) { throw new RuntimeException("error opening browser", ex); } } }); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { String urlText = event.getParameter(PARAM_ID_URL); final URL url; if (urlText == null) { url = null; } else { try { url = new URL(urlText); } catch (MalformedURLException ex) { throw new ExecutionException("malformed URL:" + urlText, ex); } } final String browserId = event.getParameter(PARAM_ID_BROWSER_ID); final String name = event.getParameter(PARAM_ID_NAME); final String tooltip = event.getParameter(PARAM_ID_TOOLTIP); HandlerUtil.getActiveShellChecked(event).getDisplay().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport(); IWebBrowser browser = browserSupport.createBrowser( IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR, browserId, name, tooltip); browser.openURL(url); } catch (PartInitException ex) { WebBrowserUIPlugin.logError("error opening browser", ex); } } }); return null; }
Source:
public void testCreateNewTaskFromUnlockedTask() { Datastream stream = DatastreamTestUtils.createDatastream("dummy", "dummy", "dummy"); stream.getMetadata().put(DatastreamMetadataConstants.TASK_PREFIX, DatastreamTaskImpl.getTaskPrefix(stream)); DatastreamTaskImpl task = new DatastreamTaskImpl(Collections.singletonList(stream)); task.setPartitionsV2(ImmutableList.of("partition1")); ZkAdapter mockZkAdapter = mock(ZkAdapter.class); task.setZkAdapter(mockZkAdapter); DatastreamTaskImpl task0 = new DatastreamTaskImpl(Collections.singletonList(stream)); ZkAdapter mockZkAdapter2 = mock(ZkAdapter.class); task0.setZkAdapter(mockZkAdapter2); when(mockZkAdapter2.checkIsTaskLocked(anyString(), anyString(), anyString())).thenReturn(true); task.addDependency(task0); when(mockZkAdapter.checkIsTaskLocked(anyString(), anyString(), anyString())).thenReturn(false); DatastreamTaskImpl task2 = new DatastreamTaskImpl(task, new ArrayList<>()); }

Target:
public void testCreateNewTaskFromUnlockedTask() { Datastream stream = DatastreamTestUtils.createDatastream("dummy", "dummy", "dummy"); stream.getMetadata().put(DatastreamMetadataConstants.TASK_PREFIX, DatastreamTaskImpl.getTaskPrefix(stream)); DatastreamTaskImpl task = new DatastreamTaskImpl(Collections.singletonList(stream)); task.setPartitionsV2(ImmutableList.of("partition1")); ZkAdapter mockZkAdapter = mock(ZkAdapter.class); task.setZkAdapter(mockZkAdapter); task.addDependency(createDependencyTask(stream, true)); when(mockZkAdapter.checkIsTaskLocked(anyString(), anyString(), anyString())).thenReturn(false); Assert.assertThrows(DatastreamTransientException.class, () -> new DatastreamTaskImpl(task, new ArrayList<>())); }
Source:
private MysqlReplicator createReplicatorForBinLog(DatastreamTask task) { MysqlSource source = parseMysqlSource(task); String binlogFolder; try { binlogFolder = new File(source.getBinlogFolderName()).getCanonicalPath(); } catch (IOException e) { String msg = String.format("Unable to find the canonical path for binlogFolder: %s", source.getBinlogFolderName()); LOG.error(msg); throw new DatastreamRuntimeException(msg); } LOG.info( String.format("Creating mysql replicator for DB: %s table: %s and binlogFolder: %s", source.getDatabaseName(), source.getTableName(), binlogFolder)); MysqlSourceBinlogRowEventFilter rowEventFilter = new MysqlSourceBinlogRowEventFilter(source.getDatabaseName(), source.getTableName()); MysqlBinlogParser replicator = new MysqlBinlogParser(binlogFolder, rowEventFilter, new MysqlBinlogParserListener()); replicator.setBinlogEventListener( new MysqlBinlogEventListener(task, InMemoryTableInfoProvider.getTableInfoProvider())); return replicator; }

Target:
private MysqlReplicator createReplicatorForBinLog(DatastreamTask task) { MysqlSource source = parseMysqlSource(task); String binlogFolder; try { binlogFolder = new File(source.getBinlogFolderName()).getCanonicalPath(); } catch (IOException e) { String msg = String.format("Unable to find the canonical path for binlogFolder: %s", source.getBinlogFolderName()); LOG.error(msg, e); throw new DatastreamRuntimeException(msg, e); } LOG.info( String.format("Creating mysql replicator for DB: %s table: %s and binlogFolder: %s", source.getDatabaseName(), source.getTableName(), binlogFolder)); MysqlSourceBinlogRowEventFilter rowEventFilter = new MysqlSourceBinlogRowEventFilter(source.getDatabaseName(), source.isAllTables(), source.getTableName()); MysqlBinlogParser replicator = new MysqlBinlogParser(binlogFolder, rowEventFilter, new MysqlBinlogParserListener()); replicator.setBinlogEventListener( new MysqlBinlogEventListener(task, InMemoryTableInfoProvider.getTableInfoProvider())); return replicator; }
Source:
void noGamesPresent() { final boolean result = gameListing.keepAlive(API_KEY_0, GAME_ID_0); assertThat("Game not found, keep alive should return false", result, is(false)); assertThat(cache.asMap(), is(Map.of())); }

Target:
void noGamesPresent() { final boolean result = gameListing.keepAlive(API_KEY_0, GAME_ID_0); assertThat("Game not found, keep alive should return false", result, is(false)); assertThat(cache.asMap(), is(anEmptyMap())); }
Source:
public Response msWordTemplatePublishPreview(BranchId branch, ArtifactId template, ArtifactId headArtifact) { String name = orcsApi.getQueryFactory().fromBranch(branch).andId(headArtifact).asArtifact().getName(); SimpleDateFormat format = new SimpleDateFormat("MM-dd_HH-mm-ss"); Date date = new Date(System.currentTimeMillis()); String time = format.format(date); String fileName = name + "_" + time + ".xml"; PublishingOptions publishingOptions = new PublishingOptions(); publishingOptions.branch = branch; publishingOptions.linkType = LinkType.INTERNAL_DOC_REFERENCE_USE_NAME; publishingOptions.excludeFolders = true; if (template.getId().equals(-1L)) { template = ArtifactId.SENTINEL; } StreamingOutput streamingOutput = new TemplatePublisherPreviewStreamingOutput(publishingOptions, template, headArtifact, orcsApi, logger); ResponseBuilder builder = Response.ok(streamingOutput); builder.header("Content-Disposition", "attachment; filename=" + fileName); return builder.build(); }

Target:
public Response msWordTemplatePublishPreview(BranchId branch, ArtifactId template, ArtifactId headArtifact) { String name = orcsApi.getQueryFactory().fromBranch(branch).andId(headArtifact).asArtifact().getName(); SimpleDateFormat format = new SimpleDateFormat("MM-dd_HH-mm-ss"); Date date = new Date(System.currentTimeMillis()); String time = format.format(date); String fileName = name + "_" + time + ".xml"; PublishingOptions publishingOptions = new PublishingOptions(); publishingOptions.branch = branch; publishingOptions.linkType = LinkType.INTERNAL_DOC_REFERENCE_USE_NAME; publishingOptions.excludeFolders = true; StreamingOutput streamingOutput = new TemplatePublisherPreviewStreamingOutput(publishingOptions, template, headArtifact, orcsApi, logger); ResponseBuilder builder = Response.ok(streamingOutput); builder.header("Content-Disposition", "attachment; filename=" + fileName); return builder.build(); }
Source:
public void exitWithNonzeroOnSkips() { TestNG tng = create(Issue217TestClassSample.class); tng.run(); assertEquals(tng.getStatus(), 5); }

Target:
public void exitWithNonzeroOnSkips() { TestNG tng = create(Issue217TestClassSample.class); tng.run(); assertEquals(tng.getStatus(), 2); }
Source:
public void postRun() throws Exception { db = dbFactory.open(); try { conn = ((JdbcSchema) db).getConnection(); Map<String, List<String>> corrections = findPKUpdates(); if (corrections.isEmpty()) { return; } ui.header("Database Primary Keys"); if (ui.yesno(true, "Fix primary keys column order")) { ui.message("fixing primary keys...\n"); JdbcExecutor executor = new JdbcExecutor(conn); for (Map.Entry<String, List<String>> c : corrections.entrySet()) { ui.message(" table: %s ... ", c.getKey()); recreatePK(executor, c.getKey(), c.getValue()); ui.message("done\n"); } ui.message("done\n"); } } finally { db.close(); } }

Target:
public void postRun() throws Exception { db = dbFactory.open(); try { conn = ((JdbcSchema) db).getConnection(); Map<String, List<String>> corrections = findPKUpdates(); if (corrections.isEmpty()) { return; } ui.header("Wrong Primary Key Column Order Detected"); ui.message("The following tables are affected:\n"); ui.message("%s\n", Joiner.on(", ").join(corrections.keySet())); if (ui.yesno(true, "Fix primary keys column order")) { ui.message("fixing primary keys...\n"); JdbcExecutor executor = new JdbcExecutor(conn); try { for (Map.Entry<String, List<String>> c : corrections.entrySet()) { ui.message(" table: %s ... ", c.getKey()); recreatePK(executor, c.getKey(), c.getValue()); ui.message("done\n"); } ui.message("done\n"); } finally { executor.close(); } } } finally { db.close(); } }
Source:
@Override public int hashCode() { int result = (privateSuccess ? 1 : 0); result = 31 * result + privateReasons.hashCode(); return result; }

Target:
public int hashCode() { return Objects.hash(privateSuccess, privateReasons); }
Source:
public boolean isAccountReportSpamEnabled() { try { return (mAccount != null && !mAccount.getReportSpamRecipient().isEmpty()); } catch (Exception e) { return false; } }

Target:
public boolean isAccountReportSpamEnabled() { return (mAccount != null && !TextUtils.isEmpty(mAccount.getReportSpamRecipient())); }
Source:
public List<HasMetadata> buildAccompanyingKubernetesResources() throws IOException { if (kubernetesParameters.getExistingHadoopConfigurationConfigMap().isPresent()) { return Collections.emptyList(); } final Optional<String> localHadoopConfigurationDirectory = kubernetesParameters.getLocalHadoopConfigurationDirectory(); if (!localHadoopConfigurationDirectory.isPresent()) { return Collections.emptyList(); } final List<File> hadoopConfigurationFileItems = getHadoopConfigurationFileItems(localHadoopConfigurationDirectory.get()); if (hadoopConfigurationFileItems.isEmpty()) { LOG.warn("Found 0 files in directory {}, skip to create the Hadoop Configuration ConfigMap.", localHadoopConfigurationDirectory.get()); return Collections.emptyList(); } final Map<String, String> data = new HashMap<>(); for (File file: hadoopConfigurationFileItems) { data.put(file.getName(), Files.toString(file, StandardCharsets.UTF_8)); } final ConfigMap hadoopConfigMap = new ConfigMapBuilder() .withApiVersion(Constants.API_VERSION) .withNewMetadata() .withName(getHadoopConfConfigMapName(kubernetesParameters.getClusterId())) .withLabels(kubernetesParameters.getCommonLabels()) .endMetadata() .addToData(data) .build(); return Collections.singletonList(hadoopConfigMap); }

Target:
public List<HasMetadata> buildAccompanyingKubernetesResources() throws IOException { if (kubernetesParameters.getExistingHadoopConfigurationConfigMap().isPresent()) { return Collections.emptyList(); } final Optional<String> localHadoopConfigurationDirectory = kubernetesParameters.getLocalHadoopConfigurationDirectory(); if (!localHadoopConfigurationDirectory.isPresent()) { return Collections.emptyList(); } final List<File> hadoopConfigurationFileItems = getHadoopConfigurationFileItems(localHadoopConfigurationDirectory.get()); if (hadoopConfigurationFileItems.isEmpty()) { LOG.warn("Found 0 files in directory {}, skip to create the Hadoop Configuration ConfigMap.", localHadoopConfigurationDirectory.get()); return Collections.emptyList(); } final Map<String, String> data = new HashMap<>(); for (File file: hadoopConfigurationFileItems) { data.put(file.getName(), FileUtils.readFileUtf8(file)); } final ConfigMap hadoopConfigMap = new ConfigMapBuilder() .withApiVersion(Constants.API_VERSION) .withNewMetadata() .withName(getHadoopConfConfigMapName(kubernetesParameters.getClusterId())) .withLabels(kubernetesParameters.getCommonLabels()) .endMetadata() .addToData(data) .build(); return Collections.singletonList(hadoopConfigMap); }
Source:
protected void startEntity() { schedule(this, startTime, POWER_MEASUREMENT); }

Target:
protected void startEntity() { schedule(POWER_MEASUREMENT); }
Source:
public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!testPermission(sender)) return false; BanList.Type banType; if (args.length > 0) { final String parameter = args[0]; switch (parameter) { case "ips" : banType = BanList.Type.IP; break; case "players" : banType = BanList.Type.NAME; break; default: sender.sendMessage(ChatColor.RED + "Invalid parameter '" + parameter + "'. Usage : " + usageMessage); return false; } } else { banType = BanList.Type.NAME; } final Set<BanEntry> banEntries = Bukkit.getBanList(banType).getBanEntries(); if (banEntries.isEmpty()) { sender.sendMessage("There are no banned players"); } else { int index = 0, size = banEntries.size(); final StringBuilder banList = new StringBuilder(200); for (final BanEntry banEntry : banEntries) { banList.append(banEntry.getTarget()); if (index != size - 1) { if (index == size - 2) { banList.append(" and "); } else { banList.append(", "); } } ++index; } sender.sendMessage("There are " + size + " banned players : "); sender.sendMessage(banList.toString()); } return true; }

Target:
public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!testPermission(sender)) return false; BanList.Type banType; if (args.length > 0) { if ("ips".equalsIgnoreCase(args[0])) { banType = BanList.Type.IP; } else if ("players".equalsIgnoreCase(args[0])) { banType = BanList.Type.NAME; } else { sender.sendMessage(ChatColor.RED + "Invalid parameter '" + args[0] + "'. Usage: " + usageMessage); return false; } } else { banType = BanList.Type.NAME; } final Set<BanEntry> banEntries = Bukkit.getBanList(banType).getBanEntries(); if (banEntries.isEmpty()) { sender.sendMessage("There are no banned players"); } else { final List<String> targets = banEntries.stream().map(BanEntry::getTarget).collect(Collectors.toList()); sender.sendMessage("There are " + banEntries.size() + " banned players: "); sender.sendMessage(CommandUtils.prettyPrint(targets.toArray(new String[targets.size()]))); } return true; }
Source:
public EventValidator materialize(final EventType eventType, final ValidationStrategyConfiguration vsc) { JSONObject effectiveSchema = EventValidation.effectiveSchema(eventType); final JSONSchemaValidator defaultSchemaValidator = new JSONSchemaValidator(effectiveSchema); if (vsc.getAdditionalConfiguration() == null) { return defaultSchemaValidator; } final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule()); final Function<OverrideDefinition, OverrideDefinition> enhanceWithQualifiedSchema = definition -> { final JSONObject schema = new JSONObject(eventType.getSchema().getSchema()); final JSONObject copy = new JSONObject(schema, JSONObject.getNames(schema)); definition.getIgnoredProperties().forEach(name -> { copy.getJSONObject("properties").remove(name); final JSONArray array = copy.getJSONArray("required"); final int idx = findElement(array, name); if (idx > -1) { array.remove(idx); } }); definition.setEffectiveSchema(copy); return definition; }; final List<QualifiedJSONSchemaValidator> qualifiedValidators = mapper.convertValue( vsc.getAdditionalConfiguration(), SchemaValidationOverrides.class) .getOverrides().stream() .map(enhanceWithQualifiedSchema) .map(toQualifiedJSONSchemaValidator) .collect(Collectors.toList()); return new QualifiedJSONSchemaValidationChain(qualifiedValidators, defaultSchemaValidator); }

Target:
public EventValidator materialize(final EventType eventType, final ValidationStrategyConfiguration vsc) { final JSONObject effectiveSchema = EventValidation.effectiveSchema(eventType); final JSONSchemaValidator defaultSchemaValidator = new JSONSchemaValidator(effectiveSchema); if (vsc.getAdditionalConfiguration() == null) { return defaultSchemaValidator; } final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonOrgModule()); final Function<OverrideDefinition, OverrideDefinition> enhanceWithQualifiedSchema = definition -> { final JSONObject schema = new JSONObject(eventType.getSchema().getSchema()); final JSONObject copy = new JSONObject(schema, JSONObject.getNames(schema)); definition.getIgnoredProperties().forEach(name -> { copy.getJSONObject("properties").remove(name); final JSONArray array = copy.getJSONArray("required"); final int idx = findElement(array, name); if (idx > -1) { array.remove(idx); } }); definition.setEffectiveSchema(copy); return definition; }; final List<QualifiedJSONSchemaValidator> qualifiedValidators = mapper.convertValue( vsc.getAdditionalConfiguration(), SchemaValidationOverrides.class) .getOverrides().stream() .map(enhanceWithQualifiedSchema) .map(toQualifiedJSONSchemaValidator) .collect(Collectors.toList()); return new QualifiedJSONSchemaValidationChain(qualifiedValidators, defaultSchemaValidator); }
Source:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { checkNotNull(request, "request"); checkNotNull(paramName, "Initialize 'paramName' in constructor"); Object obj = checkNotNull(postParams.get(paramName), format("Param '%s' cannot be null.", paramName)); T payload = (T) obj; return createRequest(request, createPayload(payload)); }

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { checkNotNull(request, "request"); Object obj = checkNotNull(postParams.get(paramName), "Param '%s' cannot be null.", paramName); T payload = (T) obj; return createRequest(request, createPayload(payload)); }
Source:
public Response update(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID, @ApiParam(value = "thing", required = true) ThingDTO thingBean) throws IOException { final Locale locale = LocaleUtil.getLocale(language); ThingUID thingUIDObject = new ThingUID(thingUID); Thing thing = thingRegistry.get(thingUIDObject); if (null == thing) { logger.info("Received HTTP PUT request for update at '{}' for the unknown thing '{}'.", uriInfo.getPath(), thingUID); return getThingNotFoundResponse(thingUID); } Thing managed = managedThingProvider.get(thingUIDObject); if (null == managed) { logger.info("Received HTTP PUT request for update at '{}' for an unmanaged thing '{}'.", uriInfo.getPath(), thingUID); return getThingResponse(Status.CONFLICT, thing, locale, "Cannot update Thing " + thingUID + " as it is not editable."); } thingBean.configuration = normalizeConfiguration(thingBean.configuration, thing.getThingTypeUID(), thing.getUID()); if (thingBean.channels != null) { for (ChannelDTO channelBean : thingBean.channels) { if (channelBean.channelTypeUID != null) { channelBean.configuration = normalizeConfiguration(channelBean.configuration, new ChannelTypeUID(channelBean.channelTypeUID), new ChannelUID(thing.getUID(), channelBean.id)); } } } thing = ThingHelper.merge(thing, thingBean); Thing oldthing = managedThingProvider.update(thing); if (null == oldthing) { return getThingNotFoundResponse(thingUID); } return getThingResponse(Status.OK, thing, locale, null); }

Target:
public Response update(@HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language, @PathParam("thingUID") @ApiParam(value = "thingUID") String thingUID, @ApiParam(value = "thing", required = true) ThingDTO thingBean) throws IOException { final Locale locale = LocaleUtil.getLocale(language); ThingUID thingUIDObject = new ThingUID(thingUID); Thing thing = thingRegistry.get(thingUIDObject); if (null == thing) { logger.info("Received HTTP PUT request for update at '{}' for the unknown thing '{}'.", uriInfo.getPath(), thingUID); return getThingNotFoundResponse(thingUID); } Thing managed = managedThingProvider.get(thingUIDObject); if (null == managed) { logger.info("Received HTTP PUT request for update at '{}' for an unmanaged thing '{}'.", uriInfo.getPath(), thingUID); return getThingResponse(Status.CONFLICT, thing, locale, "Cannot update Thing " + thingUID + " as it is not editable."); } thingBean.configuration = normalizeConfiguration(thingBean.configuration, thing.getThingTypeUID(), thing.getUID()); normalizeChannels(thingBean, thing.getUID()); thing = ThingHelper.merge(thing, thingBean); Thing oldthing = managedThingProvider.update(thing); if (null == oldthing) { return getThingNotFoundResponse(thingUID); } return getThingResponse(Status.OK, thing, locale, null); }
Source:
protected boolean equivalent(Constraint constraint) { if (constraint == this || constraint instanceof IsTreeTableConstraint) { return true; } return false; }

Target:
protected boolean equivalent(Constraint constraint) { return constraint == this || constraint instanceof IsTreeTableConstraint; }
Source:
public void refreshSupplementaryFolder(IProgressMonitor monitor) { IFolder supplFolder = createSupplementaryFolder(monitor); try { supplFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor); } catch (CoreException e) { Activator.getDefault().logError("Error refreshing supplementary folder " + supplFolder, e); } }

Target:
public void refreshSupplementaryFolder(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 2); IFolder supplFolder = createSupplementaryFolder(subMonitor.split(1)); try { supplFolder.refreshLocal(IResource.DEPTH_INFINITE, subMonitor.split(1)); } catch (CoreException e) { Activator.getDefault().logError("Error refreshing supplementary folder " + supplFolder, e); } }
Source:
public void getNettyServerTest() { Properties properties = new Properties(); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); RestRequestHandler restRequestHandler = new MockRestRequestResponseHandler(); NettyServerFactory nioServerFactory = new NettyServerFactory(verifiableProperties, new MetricRegistry(), restRequestHandler); NioServer nioServer = nioServerFactory.getNioServer(); assertNotNull("No NioServer returned", nioServer); assertEquals("Did not receive a NettyServer instance", NettyServer.class.getCanonicalName(), nioServer.getClass().getCanonicalName()); }

Target:
public void getNettyServerTest() { Properties properties = new Properties(); VerifiableProperties verifiableProperties = new VerifiableProperties(properties); RestRequestHandler restRequestHandler = new MockRestRequestResponseHandler(); NettyServerFactory nettyServerFactory = new NettyServerFactory(verifiableProperties, new MetricRegistry(), restRequestHandler); NioServer nioServer = nettyServerFactory.getNioServer(); assertNotNull("No NioServer returned", nioServer); assertEquals("Did not receive a NettyServer instance", NettyServer.class.getCanonicalName(), nioServer.getClass().getCanonicalName()); }