auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void deliver_updates_through_several_threads() throws InterruptedException { final int threadsCount = Given.THREADS_COUNT_IN_POOL_EXECUTOR; @SuppressWarnings("LocalVariableNamingConvention") final int threadExecutionMaxAwaitSeconds = Given.AWAIT_SECONDS; final Map<String, Object> threadInvocationRegistry = new ConcurrentHashMap<>(threadsCount); final Stand stand = mock(Stand.class); doNothing().when(stand).update(ArgumentMatchers.any(), any(Any.class)); final StandFunnel standFunnel = StandFunnel.newBuilder() .setStand(stand) .build(); final ExecutorService processes = Executors.newFixedThreadPool(threadsCount); final Runnable task = new Runnable() { @Override public void run() { final String threadName = Thread.currentThread().getName(); Assert.assertFalse(threadInvocationRegistry.containsKey(threadName)); standFunnel.post(new Object(), Any.getDefaultInstance()); threadInvocationRegistry.put(threadName, new Object()); } }; for (int i = 0; i < threadsCount; i++) { processes.execute(task); } processes.awaitTermination(threadExecutionMaxAwaitSeconds, TimeUnit.SECONDS); Assert.assertEquals(threadInvocationRegistry.size(), threadsCount); }

Target:
public void deliver_updates_through_several_threads() throws InterruptedException { final int threadsCount = Given.THREADS_COUNT_IN_POOL_EXECUTOR; @SuppressWarnings("LocalVariableNamingConvention") final int threadExecutionMaxAwaitSeconds = Given.AWAIT_SECONDS; final Set<String> threadInvocationRegistry = new ConcurrentSet<>(); final Stand stand = mock(Stand.class); doNothing().when(stand).update(ArgumentMatchers.any(), any(Any.class)); final StandFunnel standFunnel = StandFunnel.newBuilder() .setStand(stand) .build(); final ExecutorService executor = Executors.newFixedThreadPool(threadsCount); final Runnable task = new Runnable() { @Override public void run() { final String threadName = Thread.currentThread().getName(); Assert.assertFalse(threadInvocationRegistry.contains(threadName)); standFunnel.post(new Object(), Any.getDefaultInstance()); threadInvocationRegistry.add(threadName); } }; for (int i = 0; i < threadsCount; i++) { executor.execute(task); } executor.awaitTermination(threadExecutionMaxAwaitSeconds, TimeUnit.SECONDS); Assert.assertEquals(threadInvocationRegistry.size(), threadsCount); }
Source:
public void testSaveAllAndFindAll() { final Mono<Void> deletedMono = repository.deleteAll(); StepVerifier.create(deletedMono).thenAwait().verifyComplete(); Flux<LongIdDomainPartition> savedAllFlux = this.repository.saveAll(Arrays.asList(DOMAIN_1, DOMAIN_2)); StepVerifier.create(savedAllFlux).thenConsumeWhile(domain -> true).expectComplete().verify(); final Flux<LongIdDomainPartition> allFlux = repository.findAll(); StepVerifier.create(allFlux).expectNextCount(2).verifyComplete(); }

Target:
public void testSaveAllAndFindAll() { final Mono<Void> deletedMono = repository.deleteAll(); StepVerifier.create(deletedMono).thenAwait().verifyComplete(); Flux<LongIdDomainPartition> savedAllFlux = this.repository.saveAll(Arrays.asList(DOMAIN_1, DOMAIN_2)); StepVerifier.create(savedAllFlux).expectNextCount(2).verifyComplete(); final Flux<LongIdDomainPartition> allFlux = repository.findAll(); StepVerifier.create(allFlux).expectNextCount(2).verifyComplete(); }
Source:
void markDependencyCancelled(final DependencyInstanceContext context) { this.executorService.submit(() -> { final DependencyInstance depInst = findDependencyInstanceByContext(context); if (depInst != null) { logger.info( String.format("setting dependency instance[id: %s, name: %s] status to cancelled", depInst.getTriggerInstance().getId(), depInst.getDepName())); if (cancelledByDependencyPlugin(depInst)) { processStatusAndCancelCauseUpdate(depInst, Status.CANCELLING, CancellationCause.FAILURE); cancelTriggerInstance(depInst.getTriggerInstance()); } else if (cancelledByAzkaban(depInst)) { processStatusUpdate(depInst, Status.CANCELLED); } else { logger.warn(String.format("OnCancel of dependency instance[id: %s, name: %s] is ignored", depInst.getTriggerInstance().getId(), depInst.getDepName())); return; } if (depInst.getTriggerInstance().getStatus() == Status.CANCELLED) { logger.info( String.format("trigger instance with execId %s is cancelled", depInst.getTriggerInstance().getId())); this.triggerProcessor.processTermination(depInst.getTriggerInstance()); removeRunningTriggerInstById(depInst.getTriggerInstance().getId()); } } else { logger.warn(String.format("unable to find trigger instance with context %s when marking " + "it cancelled", context)); } }); }

Target:
public void markDependencyCancelled(final DependencyInstanceContext context) { this.executorService.submit(() -> { final DependencyInstance depInst = findDependencyInstanceByContext(context); if (depInst != null) { logger.info( String.format("setting dependency instance[id: %s, name: %s] status to cancelled", depInst.getTriggerInstance().getId(), depInst.getDepName())); if (cancelledByDependencyPlugin(depInst)) { processStatusAndCancelCauseUpdate(depInst, Status.CANCELLING, CancellationCause.FAILURE); cancelTriggerInstance(depInst.getTriggerInstance()); } else if (cancelledByAzkaban(depInst)) { processStatusUpdate(depInst, Status.CANCELLED); } else { logger.warn(String.format("OnCancel of dependency instance[id: %s, name: %s] is ignored", depInst.getTriggerInstance().getId(), depInst.getDepName())); return; } if (depInst.getTriggerInstance().getStatus() == Status.CANCELLED) { logger.info( String.format("trigger instance with execId %s is cancelled", depInst.getTriggerInstance().getId())); this.triggerProcessor.processTermination(depInst.getTriggerInstance()); removeRunningTriggerInstById(depInst.getTriggerInstance().getId()); } } else { logger.warn(String.format("unable to find trigger instance with context %s when marking " + "it cancelled", context)); } }); }
Source:
public void aspectPotionEffect(TickEvent.PlayerTickEvent event) { SburbConnection c = SkaianetHandler.getMainConnection(IdentifierHandler.encode(event.player), true); if(c==null || !c.enteredGame() || MinestuckConfig.aspectEffects == false) return; int rung = MinestuckPlayerData.getData(IdentifierHandler.encode(event.player)).echeladder.getRung(); EnumAspect aspect = MinestuckPlayerData.getTitle(IdentifierHandler.encode(event.player)).getHeroAspect(); int potionLevel = (int) (aspectStrength[aspect.ordinal()] * rung); if(event.player.getEntityWorld().getTotalWorldTime() % 380 == IdentifierHandler.encode(event.player).hashCode() % 380) { if(rung > 22 && aspect == HOPE) { event.player.addPotionEffect(new PotionEffect(MobEffects.WATER_BREATHING, 600, 0)); } if(potionLevel > 0) { event.player.addPotionEffect(new PotionEffect(aspectEffects[aspect.ordinal()], 600, potionLevel-1)); } } }

Target:
public void aspectPotionEffect(TickEvent.PlayerTickEvent event) { IdentifierHandler.PlayerIdentifier identifier = IdentifierHandler.encode(event.player); SburbConnection c = SkaianetHandler.getMainConnection(identifier, true); if(c == null || !c.enteredGame() || MinestuckConfig.aspectEffects == false) return; int rung = MinestuckPlayerData.getData(identifier).echeladder.getRung(); EnumAspect aspect = MinestuckPlayerData.getTitle(identifier).getHeroAspect(); int potionLevel = (int) (aspectStrength[aspect.ordinal()] * rung); if(event.player.getEntityWorld().getTotalWorldTime() % 380 == identifier.hashCode() % 380) { if(rung > 18 && aspect == HOPE) { event.player.addPotionEffect(new PotionEffect(MobEffects.WATER_BREATHING, 600, 0)); } if(potionLevel > 0) { event.player.addPotionEffect(new PotionEffect(aspectEffects[aspect.ordinal()], 600, potionLevel-1)); } } }
Source:
private void setDisableP2Mirrors(TargetPlatformConfiguration result, Xpp3Dom configuration) { Xpp3Dom disableP2mirrorsDom = configuration.getChild("disableP2Mirrors"); if (disableP2mirrorsDom != null) { String message = "Unsupported target-platform-configuration <disableP2Mirrors>. Use tycho.disableP2Mirrors -D command line parameter or settings.xml property."; throw new RuntimeException(message); } }

Target:
private void setDisableP2Mirrors(TargetPlatformConfiguration result, Xpp3Dom configuration) { Xpp3Dom disableP2mirrorsDom = configuration.getChild("disableP2Mirrors"); if (disableP2mirrorsDom != null) { logger.warn("Unsupported target-platform-configuration <disableP2Mirrors>. Use tycho.disableP2Mirrors -D command line parameter or settings.xml property."); } }
Source:
public ChoiceParameterDefinition(String name, String choices, String description) { super(name, description); this.choices = Arrays.asList(choices.split(CHOICES_DELIMITER)); defaultValue = null; }

Target:
public ChoiceParameterDefinition(String name, String choices, String description) { super(name, description); setChoicesText(choices); defaultValue = null; }
Source:
public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + ", _validateQueryParams=" + _validateQueryParams + ", _validateResourceKeyParams=" + _validateResourceKeys + "}"; }

Target:
public String toString() { return "ResourceMethodConfigImpl{" + "_timeoutMs=" + _timeoutMs + ", _validateQueryParams=" + _validateQueryParams + ", _validateResourceKeys=" + _validateResourceKeys + "}"; }
Source:
public static RequestPath parse(RestRequest restRequest, List<String> prefixesToRemove, String clusterName) throws RestServiceException { String blobIdHeader = RestUtils.getHeader(restRequest.getArgs(), Headers.BLOB_ID, false); if (blobIdHeader != null) { int nextOffset = matchPathSegments(blobIdHeader, 0, clusterName, true); String blobIdStr = nextOffset >= 0 ? blobIdHeader.substring(nextOffset) : blobIdHeader; restRequest.setArg(Headers.BLOB_ID, blobIdStr); } return parse(restRequest.getPath(), restRequest.getArgs(), prefixesToRemove, clusterName); }

Target:
public static RequestPath parse(RestRequest restRequest, List<String> prefixesToRemove, String clusterName) throws RestServiceException { String blobIdHeader = RestUtils.getHeader(restRequest.getArgs(), Headers.BLOB_ID, false); if (blobIdHeader != null) { String blobIdStr = parse(blobIdHeader, Collections.emptyMap(), prefixesToRemove, clusterName).getOperationOrBlobId(false); restRequest.setArg(Headers.BLOB_ID, blobIdStr); } return parse(restRequest.getPath(), restRequest.getArgs(), prefixesToRemove, clusterName); }
Source:
public void testCreateRoute() { gateway = gwApi.createInternetGateway(TEST_REGION, InternetGatewayOptions.NONE); assertNotNull(gateway, "Gateway was not successfully created"); final Boolean attached = gwApi.attachInternetGateway(TEST_REGION, gateway.id(), vpc.id()); assertTrue(attached, "Gateway " + gateway.id() + " failed to attach to VPC " + vpc.id()); final boolean created = routeTableApi.createRoute(TEST_REGION, routeTable.id(), gatewayId(gateway.id()) .destinationCidrBlock(TEST_DESTINATION_CIDR)); assertTrue(created, "Failed to add route to table " + routeTable.id()); final ImmutableList<RouteTable> routeTables = routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList(); assertEquals(routeTables.size(), 1, "Could not find existing route table " + routeTable.id()); boolean foundRoute = false; for (Route route : routeTables.get(0).routeSet()) { if (route.gatewayId().equals(gateway.id())) { foundRoute = true; assertEquals(route.destinationCidrBlock(), TEST_DESTINATION_CIDR, "CIDR routed through " + gateway.id() + " does not match specification " + TEST_DESTINATION_CIDR); break; } } assertTrue(foundRoute, "Could not find route added to gateway " + gateway.id()); }

Target:
public void testCreateRoute() { gateway = gwApi.createInternetGateway(TEST_REGION, InternetGatewayOptions.NONE); assertNotNull(gateway, "Gateway was not successfully created"); final Boolean attached = gwApi.attachInternetGateway(TEST_REGION, gateway.id(), vpc.id()); assertTrue(attached, "Gateway " + gateway.id() + " failed to attach to VPC " + vpc.id()); final boolean created = routeTableApi.createRoute(TEST_REGION, routeTable.id(), gatewayId(gateway.id()) .destinationCidrBlock(TEST_DESTINATION_CIDR)); assertTrue(created, "Failed to add route to table " + routeTable.id()); final ImmutableList<RouteTable> routeTables = routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList(); assertEquals(routeTables.size(), 1, "Could not find existing route table " + routeTable.id()); Optional<Route> optRoute = Iterables.tryFind(routeTables.get(0).routeSet(), new Predicate<Route>() { @Override public boolean apply(Route route) { return route.gatewayId().equals(gateway.id()); } }); assertTrue(optRoute.isPresent(), "Could not find route added to gateway " + gateway.id()); Route route = optRoute.get(); assertEquals(route.destinationCidrBlock(), TEST_DESTINATION_CIDR, "CIDR routed through " + gateway.id() + " does not match specification " + TEST_DESTINATION_CIDR); }
Source:
public boolean isTerminated() { for (ComputationPool pool : pools) { if (!pool.isTerminated()) { return false; } } return true; }

Target:
public boolean isTerminated() { return pools.stream().allMatch(ComputationPool::isTerminated); }
Source:
public void shutdown() throws InterruptedException { if (_periodicRebalancerFutureTasks != null) { _periodicRebalancerFutureTasks.cancel(false); } _periodicalRebalanceExecutor.shutdown(); stopPeriodRebalance(); shutdownOnDemandTimer(); logger.info("Shutting down pipeline", Pipeline.Type.DEFAULT.name()); shutdownPipeline(_eventThread, _eventQueue); logger.info("Shutting down pipeline", Pipeline.Type.TASK.name()); shutdownPipeline(_taskEventThread, _taskEventQueue); _asyncTasksThreadPool.shutdownNow(); try { _asyncTasksThreadPool.awaitTermination(EVENT_THREAD_JOIN_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Timeout when terminating async tasks. Some async tasks are still executing."); } shutdownAsyncFIFOWorkers(); enableClusterStatusMonitor(false); _rebalancerRef.closeRebalancer(); }

Target:
public void shutdown() throws InterruptedException { stopPeriodRebalance(); _periodicalRebalanceExecutor.shutdown(); if (!_periodicalRebalanceExecutor .awaitTermination(EVENT_THREAD_JOIN_TIMEOUT, TimeUnit.MILLISECONDS)) { _periodicalRebalanceExecutor.shutdownNow(); } shutdownOnDemandTimer(); logger.info("Shutting down pipeline", Pipeline.Type.DEFAULT.name()); shutdownPipeline(_eventThread, _eventQueue); logger.info("Shutting down pipeline", Pipeline.Type.TASK.name()); shutdownPipeline(_taskEventThread, _taskEventQueue); _asyncTasksThreadPool.shutdownNow(); try { _asyncTasksThreadPool.awaitTermination(EVENT_THREAD_JOIN_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { logger.warn("Timeout when terminating async tasks. Some async tasks are still executing."); } shutdownAsyncFIFOWorkers(); enableClusterStatusMonitor(false); _rebalancerRef.closeRebalancer(); }
Source:
private static void checkInitialized() { if (httpClient == null) { throw new IllegalStateException("HttpClient is not initialized."); } }

Target:
private static void checkInitialized() { if (httpClient == null) { throw new IllegalStateException("HttpCustomHeaderClient is not initialized."); } }
Source:
private void handleParameter(Symbol parameter) { Type leastSpecificType = findLeastSpecificType(parameter); if (!parameter.type().is(leastSpecificType.fullyQualifiedName()) && !leastSpecificType.is("java.lang.Object")) { String suggestedType = leastSpecificType.fullyQualifiedName().replace('$', '.'); reportIssue(parameter.declaration(), String.format("Use '%s' here; it is a more general type than '%s'.", suggestedType, parameter.type().name())); } }

Target:
private void handleParameter(Symbol parameter) { Type leastSpecificType = findLeastSpecificType(parameter); if (parameter.type() != leastSpecificType && !leastSpecificType.is("java.lang.Object")) { String suggestedType = leastSpecificType.fullyQualifiedName().replace('$', '.'); reportIssue(parameter.declaration(), String.format("Use '%s' here; it is a more general type than '%s'.", suggestedType, parameter.type().name())); } }
Source:
public void twoOperatorsStoreRetrieveWithMessageSelectorTransactionTest() { createOperator(); outputOperator.beginWindow(0L); outputOperator.endWindow(); JMSStringSinglePortOutputOperator outputOperator2 = createOperator2(); outputOperator2.beginWindow(1L); outputOperator2.endWindow(); long windowIdOp = outputOperator.getStore().getCommittedWindowId(APP_ID, OPERATOR_ID); Assert.assertEquals(0L, windowIdOp); long windowIdOp2 = outputOperator2.getStore().getCommittedWindowId(APP_ID, OPERATOR_2_ID); Assert.assertEquals(1L, windowIdOp2); deleteOperator(); outputOperator2.teardown(); }

Target:
public void twoOperatorsStoreRetrieveWithMessageSelectorTransactionTest() { JMSStringSinglePortOutputOperator jmsOutputOperator = createOperator(testOperatorContext); jmsOutputOperator.beginWindow(0L); jmsOutputOperator.endWindow(); JMSStringSinglePortOutputOperator jmsOutputOperator2 = createOperator(testOperator2Context); jmsOutputOperator2.beginWindow(1L); jmsOutputOperator2.endWindow(); long windowIdOp = jmsOutputOperator.getStore().getCommittedWindowId(APP_ID, OPERATOR_ID); Assert.assertEquals(0L, windowIdOp); long windowIdOp2 = jmsOutputOperator2.getStore().getCommittedWindowId(APP_ID, OPERATOR_2_ID); Assert.assertEquals(1L, windowIdOp2); jmsOutputOperator.teardown(); jmsOutputOperator2.teardown(); }
Source:
protected double getServoAngleRange() { return ServoSubsystem.kMaxServoAngle - ServoSubsystem.kMinServoAngle; }

Target:
protected static double getServoAngleRange() { return ServoSubsystem.MAX_SERVO_ANGLE - ServoSubsystem.MIN_SERVO_ANGLE; }
Source:
private <T extends PlanNode> void findAllRecursive(PlanNode node, ImmutableList.Builder<T> nodes) { node = lookup.resolve(node); if (where.test(node)) { nodes.add((T) node); } if (skipOnly.test(node) || where.test(node)) { for (PlanNode source : node.getSources()) { findAllRecursive(source, nodes); } } }

Target:
private <T extends PlanNode> void findAllRecursive(PlanNode node, ImmutableList.Builder<T> nodes) { node = lookup.resolve(node); if (where.test(node)) { nodes.add((T) node); } if (skipOnly.test(node)) { for (PlanNode source : node.getSources()) { findAllRecursive(source, nodes); } } }
Source:
public Expr apply(final List<Expr> args) { if (args.size() < 1 || args.size() > 3) { throw new IAE("'%s' must have 1 to 3 arguments", name()); } final Expr arg = args.get(0); final String formatString = args.size() > 1 ? (String) args.get(1).getLiteralValue() : null; final DateTimeZone timeZone = args.size() > 2 ? DateTimeZone.forID((String) args.get(2).getLiteralValue()) : DateTimeZone.UTC; final DateTimeFormatter formatter = formatString == null ? ISODateTimeFormat.dateTime() : DateTimeFormat.forPattern(formatString).withZone(timeZone); class TimestampFormatExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { return ExprEval.of(formatter.print(arg.eval(bindings).asLong())); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampFormatExpr(); }

Target:
public Expr apply(final List<Expr> args) { if (args.size() < 1 || args.size() > 3) { throw new IAE("Function[%s] must have 1 to 3 arguments", name()); } final Expr arg = args.get(0); final String formatString; final DateTimeZone timeZone; if (args.size() > 1) { Preconditions.checkArgument(args.get(1).isLiteral(), "Function[%s] format arg must be a literal", name()); formatString = (String) args.get(1).getLiteralValue(); } else { formatString = null; } if (args.size() > 2) { timeZone = ExprUtils.toTimeZone(args.get(2)); } else { timeZone = DateTimeZone.UTC; } final DateTimeFormatter formatter = formatString == null ? ISODateTimeFormat.dateTime() : DateTimeFormat.forPattern(formatString).withZone(timeZone); class TimestampFormatExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { return ExprEval.of(formatter.print(arg.eval(bindings).asLong())); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new TimestampFormatExpr(); }
Source:
protected int getMaxRampStage() { return 5; }

Target:
protected int getMaxRampStage() { return MAX_RAMP_STAGE; }
Source:
public void uninstall() { IWorkbenchPartSite site= fTextEditor.getSite(); IWorkbenchWindow window; if (site == null) { window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } else { window= site.getWorkbenchWindow(); } window.getPartService().removePartListener(fPartListener); fPartListener= null; Shell shell= window.getShell(); if (shell != null && !shell.isDisposed()) shell.removeShellListener(fActivationListener); fActivationListener= null; JavaCore.removeElementChangedListener(fJavaElementChangedListener); fJavaElementChangedListener= null; IWorkspace workspace= JavaPlugin.getWorkspace(); workspace.removeResourceChangeListener(fResourceChangeListener); fResourceChangeListener= null; JavaPlugin.getDefault().getCombinedPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; super.uninstall(); }

Target:
public void uninstall() { IWorkbenchPartSite site= fTextEditor.getSite(); IWorkbenchWindow window; if (site == null) { window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); } else { window= site.getWorkbenchWindow(); } if (window != null && !PlatformUI.getWorkbench().isClosing()) { window.getPartService().removePartListener(fPartListener); fPartListener= null; Shell shell= window.getShell(); if (shell != null && !shell.isDisposed()) shell.removeShellListener(fActivationListener); fActivationListener= null; } JavaCore.removeElementChangedListener(fJavaElementChangedListener); fJavaElementChangedListener= null; IWorkspace workspace= JavaPlugin.getWorkspace(); workspace.removeResourceChangeListener(fResourceChangeListener); fResourceChangeListener= null; JavaPlugin.getDefault().getCombinedPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; super.uninstall(); }
Source:
private boolean isNewerFormVersionAvailable(DriveListItem item) { FormsDao formsDao = new FormsDao(); Cursor cursor = formsDao.getFormsCursorForFormFilePath(new StoragePathProvider().getDirPath(StorageSubdirectory.FORMS) + File.separator + item.getName()); if (cursor != null && cursor.moveToFirst()) { Long lastModifiedLocal = new File(new StoragePathProvider().getDirPath(StorageSubdirectory.FORMS) + File.separator + item.getName()).lastModified(); Long lastModifiedServer = item.getDate().getValue(); return lastModifiedServer > lastModifiedLocal; } return false; }

Target:
private boolean isNewerFormVersionAvailable(DriveListItem item) { Long lastModifiedLocal = new File(storagePathProvider.getDirPath(StorageSubdirectory.FORMS) + File.separator + item.getName()).lastModified(); Long lastModifiedServer = item.getDate().getValue(); return lastModifiedServer > lastModifiedLocal; }
Source:
private String getItemType(Item i) { Item item = i; if(i instanceof GroupItem){ logger.debug("mySQL: Item is GroupItem, try to find ItemType by BaseItem"); item = ((GroupItem) i).getBaseItem(); if(item == null){ logger.debug("mySQL: BaseItem GroupItem:<ItemType> is not defined in *.items searching for first Member and try to use as ItemType"); item = ((GroupItem) i).getMembers().get(0); if(item == null){ logger.debug("mySQL: ItemType NOT found! Use STRINGITEM now."); return sqlTypes.get("STRINGITEM"); } logger.debug("mySQL: ItemType found by first Member!"); } } String itemType = item.getClass().toString().toUpperCase(); itemType = itemType.substring(itemType.lastIndexOf('.') + 1); if(sqlTypes.get(itemType) == null) return sqlTypes.get("STRINGITEM"); return sqlTypes.get(itemType); }

Target:
private String getItemType(Item i) { Item item = i; if(i instanceof GroupItem){ item = ((GroupItem) i).getBaseItem(); if(item == null){ logger.debug("mySQL: Cannot detect ItemType for because the GroupItems' base type isn't set in *.items File.", i.getName()); item = ((GroupItem) i).getMembers().get(0); if(item == null){ logger.debug("mySQL: No ItemType found for first Child-Member of GroupItem {}, use ItemType STRINGITEM ({}) as Fallback", i.getName(), sqlTypes.get("STRINGITEM")); return sqlTypes.get("STRINGITEM"); } } } String itemType = item.getClass().getSimpleName().toUpperCase(); if(sqlTypes.get(itemType) == null){ logger.debug("mySQL: No sqlType found for ItemType {}, use ItemType STRINGITEM ({}) as Fallback for {}", itemType, sqlTypes.get("STRINGITEM"), i.getName()); return sqlTypes.get("STRINGITEM"); } logger.debug("mySQL: Use ItemType ({}) for Item {}", itemType, sqlTypes.get(itemType), itemType, i.getName()); return sqlTypes.get(itemType); }
Source:
private void removeDeletedRows() { SortedSet<Cell> cp = (SortedSet<Cell>)((TreeSet<Cell>)dataToReturn).clone(); for (Cell element : cp) { long timestamp = element.getTimestamp(); if (timestamp == maxTombstoneTimestamp && shouldRemoveMostRecentTombstone()) dataToReturn.remove(element); else if (timestamp < maxTombstoneTimestamp) { dataToReturn.remove(element); } } }

Target:
private void removeDeletedRows() { Iterator<Cell> it = dataToReturn.iterator(); while (it.hasNext()) { Cell element = it.next(); long timestamp = element.getTimestamp(); if (timestamp == maxTombstoneTimestamp && shouldRemoveMostRecentTombstone()) it.remove(); else if (timestamp < maxTombstoneTimestamp) { it.remove(); } } }
Source:
private void setupOpenSearch() throws IOException { Map<String, Object> openSearchProperties = getOpenSearchSourceProperties( OPENSEARCH_SOURCE_ID, OPENSEARCH_PATH.getUrl(), getServiceManager()); getServiceManager().createManagedService(OPENSEARCH_FACTORY_PID, openSearchProperties).getPid(); }

Target:
private void setupOpenSearch() throws IOException { Map<String, Object> openSearchProperties = getOpenSearchSourceProperties( OPENSEARCH_SOURCE_ID, OPENSEARCH_PATH.getUrl(), getServiceManager()); getServiceManager().createManagedService(OPENSEARCH_FACTORY_PID, openSearchProperties); }
Source:
protected String getHandledTableName(DbMapComponent component, String tableName, String alias) { if (alias == null) { return replaceVariablesForExpression(component, tableName); } else { List<IConnection> inputConnections = (List<IConnection>) component.getIncomingConnections(); IConnection iconn = this.getConnectonByName(inputConnections, tableName); String handledTableName = ""; boolean inputIsELTDBMap = false; INode source = iconn.getSource(); String schemaValue = ""; String tableValue = ""; if (source != null) { inputIsELTDBMap = isELTDBMap(source); if (inputIsELTDBMap) { tableValue = iconn.getName(); } else { IElementParameter schemaParam = source.getElementParameter("ELT_SCHEMA_NAME"); IElementParameter tableParam = source.getElementParameter("ELT_TABLE_NAME"); if (schemaParam != null && schemaParam.getValue() != null) { schemaValue = schemaParam.getValue().toString(); } if (tableParam != null && tableParam.getValue() != null) { tableValue = tableParam.getValue().toString(); } } } String schemaNoQuote = TalendTextUtils.removeQuotes(schemaValue); boolean hasSchema = !"".equals(schemaNoQuote); if (hasSchema) { handledTableName = schemaValue + "+\".\"+"; } handledTableName = handledTableName + tableValue; return "\" +" + handledTableName + "+ \""; } }

Target:
protected String getHandledTableName(DbMapComponent component, String tableName, String alias) { if (alias == null) { return replaceVariablesForExpression(component, tableName); } else { List<IConnection> inputConnections = (List<IConnection>) component.getIncomingConnections(); IConnection iconn = this.getConnectonByName(inputConnections, tableName); if (iconn != null) { String handledTableName = ""; boolean inputIsELTDBMap = false; INode source = iconn.getSource(); String schemaValue = ""; String tableValue = ""; if (source != null) { inputIsELTDBMap = isELTDBMap(source); if (inputIsELTDBMap) { tableValue = iconn.getName(); } else { IElementParameter schemaParam = source.getElementParameter("ELT_SCHEMA_NAME"); IElementParameter tableParam = source.getElementParameter("ELT_TABLE_NAME"); if (schemaParam != null && schemaParam.getValue() != null) { schemaValue = schemaParam.getValue().toString(); } if (tableParam != null && tableParam.getValue() != null) { tableValue = tableParam.getValue().toString(); } } } String schemaNoQuote = TalendTextUtils.removeQuotes(schemaValue); boolean hasSchema = !"".equals(schemaNoQuote); if (hasSchema) { handledTableName = schemaValue + "+\".\"+"; } handledTableName = handledTableName + tableValue; return "\" +" + handledTableName + "+ \""; } } return tableName; }
Source:
catch (PrivilegedActionException pae) { }

Target:
catch (PrivilegedActionException pae) { LogMessages.LOGGER.error(pae); }
Source:
public EncryptionGroup(List<Integer> nodes, Optional<Slice> keyMetadata, Slice statistics) { this.nodes = ImmutableList.copyOf(nodes); this.keyMetadata = keyMetadata; this.statistics = statistics; }

Target:
public EncryptionGroup(List<Integer> nodes, Optional<Slice> keyMetadata, Slice statistics) { this.nodes = ImmutableList.copyOf(requireNonNull(nodes, "nodes is null")); this.keyMetadata = requireNonNull(keyMetadata, "keyMetadata is null"); this.statistics = requireNonNull(statistics, "statistics is null"); }
Source:
public static InputStream loadResource(String resourceFile) { InputStream stream = null; try { String file = localResourceDir + resourceFile; if (!new File(file).exists()) { logger.debug("Loading from classpath", resourceFile); stream = ResourceUtilities.class.getResourceAsStream("/"+resourceFile); } else { logger.debug("Loading from local directory", resourceFile); stream = new FileInputStream(file); } stream = checkGZipped(stream); } catch (Exception e) { logger.error("Could not load {}. Exception {}", resourceFile, e.toString()); System.exit(-1); } return stream; }

Target:
public static InputStream loadResource(String resourceFile) { InputStream stream = null; try { String file = localResourceDir + resourceFile; if (!new File(file).exists()) { logger.debug("Loading from classpath", resourceFile); List<URL> list = IOUtils.lsResources(ResourceUtilities.class, resourceFile); if (list.isEmpty()) { logger.error("Could not load " + resourceFile); System.exit(-1); } URL fileURL = list.get(0); URLConnection connection = fileURL.openConnection(); stream = connection.getInputStream(); } else { logger.debug("Loading from local directory", resourceFile); stream = new FileInputStream(file); } stream = checkGZipped(stream); } catch (Exception e) { logger.error("Could not load {}. Exception {}", resourceFile, e.toString()); System.exit(-1); } return stream; }
Source:
public void init() throws Exception { super.init(); serverConfigurationManager = new ServerConfigurationManager( new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN)); serverConfigurationManager.applyConfiguration( Paths.get(getESBResourceLocation(), "nhttp", "transport", "ESBJAVA4940", "axis2.xml").toFile()); String carbonHome = System.getProperty(ServerConstants.CARBON_HOME); File log4jProperties = Paths.get(carbonHome, "repository", "conf", "log4j.properties").toFile(); applyProperty(log4jProperties, "log4j.logger.org.apache.synapse.transport.http.wire", "DEBUG"); serverConfigurationManager.restartGracefully(); super.init(); loadESBConfigurationFromClasspath("/artifacts/ESB/nhttp/transport/ESBJAVA4940/synapseConfig.xml"); logViewer = new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie()); }

Target:
public void init() throws Exception { super.init(); serverConfigurationManager = new ServerConfigurationManager( new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN)); serverConfigurationManager.applyConfigurationWithoutRestart( Paths.get(getESBResourceLocation(), "nhttp", "transport", "ESBJAVA4940", "axis2.xml").toFile()); String carbonHome = System.getProperty(ServerConstants.CARBON_HOME); File log4jProperties = Paths.get(carbonHome, "repository", "conf", "log4j.properties").toFile(); applyProperty(log4jProperties, "log4j.logger.org.apache.synapse.transport.http.wire", "DEBUG"); serverConfigurationManager.restartGracefully(); super.init(); loadESBConfigurationFromClasspath("/artifacts/ESB/nhttp/transport/ESBJAVA4940/synapseConfig.xml"); logViewer = new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie()); }
Source:
public ListenableFuture<Void> release() { try { checkNotReleased(); } catch (IllegalStateException e) { return Futures.immediateFailedFuture(e); } if (mState == State.OPEN) { close(); } mState = State.RELEASED; mObservableState.postValue(State.RELEASED); return Futures.immediateFuture(null); }

Target:
public ListenableFuture<Void> release() { if (mState == State.OPEN) { close(); } if (mState != State.RELEASED) { mState = State.RELEASED; mObservableState.postValue(State.RELEASED); } return Futures.immediateFuture(null); }
Source:
public void putAndActivate(final InternalCacheEntry newEntry) { ((ConcurrentHashMapV8<Object, InternalCacheEntry>) entries) .compute(newEntry.getKey(), new ConcurrentHashMapV8.BiFun<Object, InternalCacheEntry, InternalCacheEntry>() { @Override public InternalCacheEntry apply(Object key, InternalCacheEntry entry) { if (entry == null && activator != null) { activator.activate(key); } return newEntry; } }); }

Target:
public void putAndActivate(final InternalCacheEntry newEntry) { ((ConcurrentHashMapV8<Object, InternalCacheEntry>) entries) .compute(newEntry.getKey(), new ConcurrentHashMapV8.BiFun<Object, InternalCacheEntry, InternalCacheEntry>() { @Override public InternalCacheEntry apply(Object key, InternalCacheEntry entry) { if (entry == null) { activator.activate(key); } return newEntry; } }); }
Source:
String getAzureContainerName(BlobId blobId) { return getAzureContainerName(new CloudBlobMetadata(blobId)); }

Target:
String getAzureContainerName(BlobId blobId) { return getAzureContainerName( new CloudBlobMetadata(blobId, 0, Utils.Infinite_Time, 0, CloudBlobMetadata.EncryptionOrigin.NONE)); }
Source:
public boolean equals(final Object obj) { boolean result = false; if (this == obj) { result = true; } else { if (obj instanceof ViewpointItemImpl) { final ViewpointItemImpl objItem = (ViewpointItemImpl) obj; result = EqualityHelper.areEquals(this.viewpoint, objItem.viewpoint); result = this.parent.equals(objItem.parent); } } return result; }

Target:
public boolean equals(final Object obj) { boolean result = false; if (this == obj) { result = true; } else { if (obj instanceof ViewpointItemImpl) { final ViewpointItemImpl objItem = (ViewpointItemImpl) obj; result = EqualityHelper.areEquals(this.viewpoint, objItem.viewpoint); result = result && this.parent.equals(objItem.parent); } } return result; }
Source:
private ProxyConfiguration constructDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = null; if (this.proxyConfiguration != null) { authentication = this.proxyConfiguration.authentication(); } authentication = authentication == null ? ProxyAuthenticationType.NONE : authentication; String proxyAddress = configuration.get(BaseConfigurations.HTTP_PROXY); String host; Integer port; Proxy proxy = null; if (proxyAddress != null) { String[] hostPort = proxyAddress.split(":"); host = hostPort[0]; port = Integer.parseInt(hostPort[1]); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); } String username = configuration.get(ProxyConfiguration.PROXY_USERNAME); String password = configuration.get(ProxyConfiguration.PROXY_PASSWORD); return new ProxyConfiguration(authentication, proxy, username, password); }

Target:
private ProxyConfiguration constructDefaultProxyConfiguration(Configuration configuration) { ProxyAuthenticationType authentication = ProxyAuthenticationType.NONE; if (proxyConfiguration != null) { authentication = proxyConfiguration.authentication(); } String proxyAddress = configuration.get(BaseConfigurations.HTTP_PROXY); Proxy proxy = null; if (proxyAddress != null) { String[] hostPort = proxyAddress.split(":"); if (hostPort.length < 2) { throw new IllegalArgumentException("HTTP_PROXY cannot be parsed into a proxy"); } String host = hostPort[0]; Integer port = Integer.parseInt(hostPort[1]); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); } String username = configuration.get(ProxyConfiguration.PROXY_USERNAME); String password = configuration.get(ProxyConfiguration.PROXY_PASSWORD); return new ProxyConfiguration(authentication, proxy, username, password); }
Source:
private boolean canFindVmOrTemplate() { boolean retValue = true; if (getParameters().getOperation() == ImageOperation.Copy) { VmTemplate template = getVmTemplateDAO().get(getImage().getvm_guid()); if (template == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); retValue = false; } else { setVmTemplate(template); sharedLockMap = Collections.singletonMap(LockingGroup.TEMPLATE.name(), getImage().getvm_guid()); } } else { List<VM> listVms = getVmDAO().getForImageGroup(getImage().getId()); if (!listVms.isEmpty()) { sharedLockMap = new HashMap<String, Guid>(); int vmNum = 1; for (VM vm : listVms) { sharedLockMap.put(LockingGroup.VM.name() + vmNum, vm.getId()); vmNum++; } } retValue = true; } return retValue; }

Target:
private boolean canFindVmOrTemplate() { boolean retValue = true; if (getParameters().getOperation() == ImageOperation.Copy) { VmTemplate template = getVmTemplateDAO().get(getImage().getvm_guid()); if (template == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_DOES_NOT_EXIST); retValue = false; } else { setVmTemplate(template); sharedLockMap = Collections.singletonMap(getImage().getvm_guid(), LockingGroup.TEMPLATE.name()); } } else { List<VM> listVms = getVmsForImageGroup(); if (!listVms.isEmpty()) { sharedLockMap = new HashMap<Guid, String>(); for (VM vm : listVms) { sharedLockMap.put(vm.getId(), LockingGroup.VM.name()); } } retValue = true; } return retValue; }
Source:
void publishMessagesFromQueue() { if (connectionState == MqttManagerConnectionState.Connected && mqttMessageQueue != null) { final AWSIotMqttQueueMessage message = mqttMessageQueue.poll(); if (message != null) { try { if (message.getUserData() != null && message.getUserData().getUserCallback() != null) { mqttClient .publish(message.getTopic(), message.getMessage(), message.getQos() .asInt(), false, message.getUserData(), null); } else { mqttClient .publish(message.getTopic(), message.getMessage(), message.getQos() .asInt(), false); } } catch (final MqttException e) { userPublishCallback(message.getUserData().getUserCallback(), AWSIotMqttMessageDeliveryCallback.MessageDeliveryStatus.Fail, message.getUserData().getUserData()); } if (mReconnectHandlerThread != null && mReconnectHandler != null) { mReconnectHandler.postDelayed(new Runnable() { @Override public void run() { publishMessagesFromQueue(); } }, drainingInterval); } else { LOGGER.warn("failed to schedule publish from queue, handler thread is missing"); } } } }

Target:
void publishMessagesFromQueue() { if (connectionState == MqttManagerConnectionState.Connected && mqttMessageQueue != null) { final AWSIotMqttQueueMessage message = mqttMessageQueue.poll(); if (message != null) { try { if (message.getUserData() != null && message.getUserData().getUserCallback() != null) { mqttClient .publish(message.getTopic(), message.getMessage(), message.getQos() .asInt(), false, message.getUserData(), null); } else { mqttClient .publish(message.getTopic(), message.getMessage(), message.getQos() .asInt(), false); } } catch (final MqttException e) { notifyPublishResult(message.getUserData().getUserCallback(), AWSIotMqttMessageDeliveryCallback.MessageDeliveryStatus.Fail, message.getUserData().getUserData(), new AmazonClientException("Client error while publishing.", e)); } if (mReconnectHandlerThread != null && mReconnectHandler != null) { mReconnectHandler.postDelayed(new Runnable() { @Override public void run() { publishMessagesFromQueue(); } }, drainingInterval); } else { LOGGER.warn("failed to schedule publish from queue, handler thread is missing"); } } } }
Source:
public static void enforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege( Context context, int subId, String message) { if (context.checkCallingOrSelfPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) == PERMISSION_GRANTED) { return; } if (context.checkCallingOrSelfPermission(Manifest.permission.READ_PRECISE_PHONE_STATE) == PERMISSION_GRANTED) { return; } if (DBG) { Rlog.d(LOG_TAG, "No READ_PRIVILEDED_PHONE_STATE nor READ_PRECISE_PHONE_STATE permission" + ", check carrier privilege next."); } enforceCallingOrSelfCarrierPrivilege(subId, message); }

Target:
public static void enforeceCallingOrSelfReadPrecisePhoneStatePermissionOrCarrierPrivilege( Context context, int subId, String message) { if (context.checkCallingOrSelfPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) == PERMISSION_GRANTED) { return; } if (context.checkCallingOrSelfPermission(Manifest.permission.READ_PRECISE_PHONE_STATE) == PERMISSION_GRANTED) { return; } if (DBG) { Rlog.d(LOG_TAG, "No READ_PRIVILEGED_PHONE_STATE nor READ_PRECISE_PHONE_STATE permission" + ", check carrier privilege next."); } enforceCallingOrSelfCarrierPrivilege(subId, message); }
Source:
private void resetDecoder() { if (decoder == null) { decodeBuffer = CharBuffer.allocate(stringDecoderBufferSize); decoder = MessagePack.UTF8.newDecoder() .onMalformedInput(actionOnMalformedString) .onUnmappableCharacter(actionOnUnmappableString); } else { decoder.reset(); } decodeStringBuffer = new StringBuilder(); }

Target:
private void resetDecoder() { if (decoder == null) { decodeBuffer = CharBuffer.allocate(stringDecoderBufferSize); decoder = MessagePack.UTF8.newDecoder() .onMalformedInput(actionOnMalformedString) .onUnmappableCharacter(actionOnUnmappableString); } else { decoder.reset(); } if (decodeStringBuffer == null) { decodeStringBuffer = new StringBuilder(); } else { decodeStringBuffer.setLength(0); } }
Source:
void shouldUpdateChargeToSystemCancel_IfEpdqStatusIs6AndChargeStatusIsNotRelevant() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISED_CANCELLED); charge = Charge.from(ChargeEntityFixture.aValidChargeEntity() .withStatus(CAPTURED) .build()); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); final boolean result = notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES); assertTrue(result); verifyNoInteractions(mockChargeNotificationProcessor); }

Target:
void shouldUpdateChargeToSystemCancel_IfEpdqStatusIs6AndChargeStatusIsNotRelevant() { final String payload = notificationPayloadForTransaction(payId, EPDQ_AUTHORISED_CANCELLED); charge = Charge.from(ChargeEntityFixture.aValidChargeEntity() .withStatus(CAPTURED) .build()); setUpGatewayAccountToReturnGatewayAccountEntity(Optional.of(gatewayAccountEntity)); setUpChargeServiceToReturnCharge(Optional.of(charge)); assertTrue(notificationService.handleNotificationFor(payload, FORWARDED_IP_ADDRESSES)); verifyNoInteractions(mockChargeNotificationProcessor); }
Source:
private static Name combineAlternatives(MemberInvolvementTree attribute) { Name name1 = attribute.shallowToString(); Name name2 = attribute.getAlternative().shallowToString(); if (name1.toString().compareTo(name2.toString()) < 0) { name1.addWords(name2.getWords()); return name1; } else { name2.addWords(name1.getWords()); return name2; } }

Target:
private Name combineAlternatives(MemberInvolvementTree attribute) { Name name1 = attribute.shallowToString(); Name name2 = attribute.getAlternative().shallowToString(); if (name1.compareTo(name2) < 0) { return names.concatenate(name1, name2); } else { return names.concatenate(name2, name1); } }
Source:
public void testAdjacentParallel(Routing routing1, Routing routing2) throws Exception { checkUdpSupported(); List<String> stringList = getListOfUniqueStrings(800); String stringArray[] = new String[800]; stringArray = stringList.toArray(stringArray); Topology topology = newTopology("testAdj"); TStream<String> out0 = topology.strings(stringArray).parallel(of(20), routing1); out0 = out0.transform(randomStringProducer("region1")).endParallel(); TStream<String> out2 = out0.parallel(of(5), routing2); out2 = out2.transform(randomStringProducer("region2")).endParallel(); TStream<String> numRegions = out2.flatMap(uniqueStringCounter(800, "region")); Tester tester = topology.getTester(); Condition<List<String>> assertFinished = tester.stringContentsUnordered(numRegions, "20", "5"); Condition<Long> expectedCount = tester.tupleCount(out2, 800); complete(tester, allConditions(assertFinished, expectedCount), 60, TimeUnit.SECONDS); assertTrue(expectedCount.valid()); assertTrue(assertFinished.valid()); }

Target:
private void testAdjacentParallel(Routing routing1, Routing routing2) throws Exception { checkUdpSupported(); List<String> stringList = getListOfUniqueStrings(800); String stringArray[] = new String[800]; stringArray = stringList.toArray(stringArray); Topology topology = newTopology("testAdj"); TStream<String> out0 = topology.strings(stringArray).parallel(of(20), routing1); out0 = out0.transform(randomStringProducer("region1")).endParallel(); TStream<String> out2 = out0.parallel(of(5), routing2); out2 = out2.transform(randomStringProducer("region2")).endParallel(); TStream<String> numRegions = out2.flatMap(uniqueStringCounter(800, "region")); Tester tester = topology.getTester(); Condition<List<String>> assertFinished = tester.stringContentsUnordered(numRegions, "20", "5"); Condition<Long> expectedCount = tester.tupleCount(out2, 800); complete(tester, allConditions(assertFinished, expectedCount), 60, TimeUnit.SECONDS); assertTrue(expectedCount.valid()); assertTrue(assertFinished.valid()); }
Source:
public void setUp() { orderedExecutor = Executors.newSingleThreadExecutor(); unorderedExecutor = Executors.newCachedThreadPool(); store = mock(Store.class); TestTimeSource timeSource = new TestTimeSource(); eventService = new CacheEventNotificationServiceImpl<Number, String>(orderedExecutor, unorderedExecutor, store, timeSource); listener = mock(CacheEventListener.class); }

Target:
public void setUp() { orderedExecutor = Executors.newSingleThreadExecutor(); unorderedExecutor = Executors.newCachedThreadPool(); store = mock(Store.class); TimeSource timeSource = SystemTimeSource.INSTANCE; eventService = new CacheEventNotificationServiceImpl<Number, String>(orderedExecutor, unorderedExecutor, store, timeSource); listener = mock(CacheEventListener.class); }
Source:
public ActionResult execute() { Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); InstructorAttributes instructorAttributes; InstructorData instructorData; String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); switch (intent) { case INSTRUCTOR_SUBMISSION: instructorAttributes = getInstructorOfCourseFromRequest(courseId); if (instructorAttributes == null) { return new JsonResult("Instructor could not be found for this course", HttpStatus.SC_NOT_FOUND); } instructorData = new InstructorData(instructorAttributes); break; case FULL_DETAIL: instructorAttributes = logic.getInstructorForGoogleId(courseId, userInfo.getId()); if (instructorAttributes == null) { return new JsonResult("Instructor could not be found for this course", HttpStatus.SC_NOT_FOUND); } instructorData = new InstructorData(instructorAttributes); instructorData.setGoogleId(instructorAttributes.googleId); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } return new JsonResult(instructorData); }

Target:
public ActionResult execute() { Intent intent = Intent.valueOf(getNonNullRequestParamValue(Const.ParamsNames.INTENT)); InstructorAttributes instructorAttributes; String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); switch (intent) { case INSTRUCTOR_SUBMISSION: instructorAttributes = getInstructorOfCourseFromRequest(courseId); break; case FULL_DETAIL: instructorAttributes = logic.getInstructorForGoogleId(courseId, userInfo.getId()); break; default: throw new InvalidHttpParameterException("Unknown intent " + intent); } if (instructorAttributes == null) { return new JsonResult("Instructor could not be found for this course", HttpStatus.SC_NOT_FOUND); } InstructorData instructorData = new InstructorData(instructorAttributes); if (intent == Intent.FULL_DETAIL) { instructorData.setGoogleId(instructorAttributes.googleId); } return new JsonResult(instructorData); }