auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String encrypt(String plainText, String secret) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException { Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret.getBytes(), ALGORITHM)); byte[] encrypted = cipher.doFinal(plainText.getBytes()); Base64 encoder = new Base64(32, linebreak, true); return new String(encoder.encode(encrypted)); }

Target:
public static String encrypt(String plainText, String secret) { String toReturn = ""; try { toReturn = encrypt_with_exceptions(plainText, secret); } catch (Exception ex) { throw new OseeCoreException(ex); } return toReturn; }
Source:
public void tearDown() throws Exception { CrashReporter.setIsInitialized(false); }

Target:
public void tearDown() throws Exception { CrashReporter.setIsCrashReportEnabled(false); }
Source:
protected IStateHistoryBackend getBackendForQuerying(IStateHistoryBackend backend) { if (!fReOpen) { return backend; } backend.dispose(); try { return new HistoryTreeBackend(SSID, checkNotNull(fTempFile), PROVIDER_VERSION); } catch (IOException e) { fail(e.getMessage()); return null; } }

Target:
protected IStateHistoryBackend getBackendForQuerying(IStateHistoryBackend backend) throws IOException { if (!fReOpen) { return backend; } backend.dispose(); return new HistoryTreeBackend(SSID, checkNotNull(fTempFile), PROVIDER_VERSION); }
Source:
public void notifyChanged(Notification notification) { super.notifyChanged(notification); addAdditionalListeners(); }

Target:
public void notifyChanged(Notification notification) { super.notifyChanged(notification); Object object = notification.getNotifier(); Property property = getUMLElement(); if (object.equals(property)) { switch (notification.getFeatureID(Property.class)) { case UMLPackage.PROPERTY__LOWER_VALUE: case UMLPackage.PROPERTY__UPPER_VALUE: addAdditionalListeners(); } } }
Source:
public void register(final C command) { super.register(command); registerChangedEvent.fire(new RegisterChangedEvent(session)); }

Target:
public void register(final C command) { super.register(command); registerChangedEvent.fire(new RegisterChangedEvent(session.getCanvasHandler())); }
Source:
private void validateNameValid(byte[] name) { Preconditions.checkNotNull(name, "name cannot be null"); Preconditions.checkArgument(name.length > 0, "name must be non-empty"); try { Preconditions.checkArgument( name.length <= MAX_NAME_LENGTH, "name must be no longer than {}.", MAX_NAME_LENGTH); } catch (IllegalArgumentException e) { log.error("Cell creation that was attempted was: {}; since the vast majority of people encountering this " + "problem are using unbounded Strings as components, it may aid your debugging to know the UTF-8 " + "interpretation of the bad field was: [{}]", UnsafeArg.of("cell", this), UnsafeArg.of("name", new String(name, StandardCharsets.UTF_8))); throw e; } }

Target:
private void validateNameValid(byte[] name) { Preconditions.checkNotNull(name, "name cannot be null"); Preconditions.checkArgument(name.length > 0, "name must be non-empty"); try { Preconditions.checkArgument( name.length <= MAX_NAME_LENGTH, "name must be no longer than {}.", MAX_NAME_LENGTH); } catch (IllegalArgumentException e) { log.error("Cell name length exceeded. Name must be no longer than {}. " + "Cell creation that was attempted was: {}; since the vast majority of people " + "encountering this problem are using unbounded Strings as components, it may aid your " + "debugging to know the UTF-8 interpretation of the bad field was: [{}]", SafeArg.of("max name length", MAX_NAME_LENGTH), UnsafeArg.of("cell", this), UnsafeArg.of("name", new String(name, StandardCharsets.UTF_8))); throw e; } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); copyFileFromAssetsToCache(getString(R.string.bristol_model)); copyFileFromAssetsToCache(getString(R.string.bristol_skin)); setupToolbar(); mSceneView = findViewById(R.id.sceneView); ArcGISScene scene = new ArcGISScene(Basemap.createImagery()); mSceneView.setScene(scene); Surface surface = new Surface(); ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource( getString(R.string.world_elevation_service_url)); surface.getElevationSources().add(elevationSource); scene.setBaseSurface(surface); mSceneOverlay = new GraphicsOverlay(); mSceneOverlay.getSceneProperties().setSurfacePlacement(LayerSceneProperties.SurfacePlacement.ABSOLUTE); mSceneView.getGraphicsOverlays().add(mSceneOverlay); Camera camera = new Camera(38.459291, -109.937576, 5500, 150.0, 20.0, 0.0); mSceneView.setViewpointCamera(camera); Point locationPoint = new Point(-109.929589, 38.437304, 1700, SpatialReferences.getWgs84()); mOrbitLocationCameraController = new OrbitLocationCameraController(locationPoint, 5000); mOrbitLocationCameraController.setCameraPitchOffset(3); mOrbitLocationCameraController.setCameraHeadingOffset(150); mModelSceneSymbol = loadModel(); mModelSceneSymbol.addDoneLoadingListener(() -> { mOrbitPlaneCameraController = new OrbitGeoElementCameraController(mPlane3D, 100.0); mOrbitPlaneCameraController.setCameraPitchOffset(30); mOrbitPlaneCameraController.setCameraHeadingOffset(150); }); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); copyFileFromAssetsToCache(getString(R.string.bristol_model)); copyFileFromAssetsToCache(getString(R.string.bristol_skin)); setupToolbar(); mSceneView = findViewById(R.id.sceneView); ArcGISScene scene = new ArcGISScene(Basemap.createImagery()); mSceneView.setScene(scene); Surface surface = new Surface(); ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource( getString(R.string.world_elevation_service_url)); surface.getElevationSources().add(elevationSource); scene.setBaseSurface(surface); mSceneOverlay = new GraphicsOverlay(); mSceneOverlay.getSceneProperties().setSurfacePlacement(LayerSceneProperties.SurfacePlacement.ABSOLUTE); mSceneView.getGraphicsOverlays().add(mSceneOverlay); Camera camera = new Camera(38.459291, -109.937576, 5500, 150.0, 20.0, 0.0); mSceneView.setViewpointCamera(camera); Point locationPoint = new Point(-109.929589, 38.437304, 1700, SpatialReferences.getWgs84()); mOrbitLocationCameraController = new OrbitLocationCameraController(locationPoint, 5000); mOrbitLocationCameraController.setCameraPitchOffset(3); mOrbitLocationCameraController.setCameraHeadingOffset(150); loadModel().addDoneLoadingListener(() -> { mOrbitPlaneCameraController = new OrbitGeoElementCameraController(mPlane3D, 100.0); mOrbitPlaneCameraController.setCameraPitchOffset(30); mOrbitPlaneCameraController.setCameraHeadingOffset(150); }); }
Source:
public CallousOppressor(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{U}{U}"); this.subtype.add(SubType.CEPHALID); this.power = new MageInt(1); this.toughness = new MageInt(2); this.addAbility(new SkipUntapOptionalAbility()); this.addAbility(new AsEntersBattlefieldAbility(new OpponentChooseCreatureTypeEffect())); FilterCreaturePermanent filter = new FilterCreaturePermanent("creature that isn't of the chosen type"); filter.add(Predicates.not(new ChosenSubtypePredicate(this.getId()))); ConditionalContinuousEffect effect = new ConditionalContinuousEffect( new GainControlTargetEffect(Duration.OneUse), SourceTappedCondition.instance, "Gain control of target creature for as long as Callous Oppressor remains tapped"); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, effect, new TapSourceCost()); ability.addTarget(new TargetCreaturePermanent(filter)); this.addAbility(ability); }

Target:
public CallousOppressor(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{1}{U}{U}"); this.subtype.add(SubType.CEPHALID); this.power = new MageInt(1); this.toughness = new MageInt(2); this.addAbility(new SkipUntapOptionalAbility()); this.addAbility(new AsEntersBattlefieldAbility(new CallousOppressorChooseCreatureTypeEffect())); ConditionalContinuousEffect effect = new ConditionalContinuousEffect( new GainControlTargetEffect(Duration.OneUse), SourceTappedCondition.instance, "Gain control of target creature for as long as {this} remains tapped"); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, effect, new TapSourceCost()); ability.addTarget(new TargetCreaturePermanent(new CallousOppressorFilter())); this.addAbility(ability); }
Source:
private static ItemStack smelt(ItemStack stack, LootContext context) { Optional<FurnaceRecipe> optional = context.getWorld().getRecipeManager().getRecipe(IRecipeType.SMELTING, new Inventory(stack), context.getWorld()); if (optional.isPresent()) { ItemStack itemstack = optional.get().getRecipeOutput(); if (!itemstack.isEmpty()) { ItemStack itemstack1 = itemstack.copy(); itemstack1.setCount(stack.getCount() * itemstack.getCount()); return itemstack1; } } return stack; }

Target:
private static ItemStack smelt(ItemStack stack, LootContext context) { return context.getWorld().getRecipeManager().getRecipe(IRecipeType.SMELTING, new Inventory(stack), context.getWorld()) .map(FurnaceRecipe::getRecipeOutput) .filter(itemStack -> !itemStack.isEmpty()) .map(itemStack -> ItemHandlerHelper.copyStackWithSize(itemStack, stack.getCount() * itemStack.getCount())) .orElse(stack); }
Source:
public static JobDescFactoryBase getFrameworkSpecificJobDescFactory(Configuration jobConf) { Framework framework = getFramework(jobConf); switch (framework) { case PIG: return new PigJobDescFactory(); case SCALDING: return new ScaldingJobDescFactory(); default: return new MRJobDescFactory(); } }

Target:
public static JobDescFactoryBase getFrameworkSpecificJobDescFactory(Configuration jobConf) { Framework framework = getFramework(jobConf); switch (framework) { case PIG: return PIG_JOB_DESC_FACTORY; case SCALDING: return SCALDING_JOB_DESC_FACTORY; default: return MR_JOB_DESC_FACTORY; } }
Source:
private LocalDate calculateSettlementDate( ResolvedCdsIndexTrade trade, CreditRatesProvider ratesProvider, ReferenceData refData) { return trade.getInfo().getSettlementDate() .orElse(trade.getProduct().getSettlementDateOffset().adjust(ratesProvider.getValuationDate(), refData)); }

Target:
private LocalDate calculateSettlementDate( ResolvedCdsIndexTrade trade, CreditRatesProvider ratesProvider, ReferenceData refData) { return trade.getInfo().getSettlementDate() .orElse(trade.getProduct().calculateSettlementDateFromValuation(ratesProvider.getValuationDate(), refData)); }
Source:
public static AbstractUIPlugin getPlugin(Bundle bundle){ final Dictionary<String, String> headers = bundle.getHeaders(); String activator = headers.get(Constants.BUNDLE_ACTIVATOR); Class<?> activatorClass; Object activatorInstance; try { activatorClass = bundle.loadClass(activator); try { Method method = activatorClass.getMethod("getDefault"); activatorInstance = method.invoke(null); } catch (NoSuchMethodException e) { throw new PluginConfigurationException("Cannot find getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (SecurityException e) { throw new PluginConfigurationException("Error accessin getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (IllegalAccessException e) { throw new PluginConfigurationException("Error accessin getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (IllegalArgumentException e) { throw new PluginConfigurationException("Error accessin getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (InvocationTargetException e) { throw new PluginConfigurationException("Error accessin getDefault method in activator of bundle "+bundle.getBundleId(),e); } return (AbstractUIPlugin) activatorInstance; } catch (ClassNotFoundException e) { throw new PluginConfigurationException("Cannot find activator for bundle "+bundle.getBundleId(),e); } }

Target:
public static AbstractUIPlugin getPlugin(Bundle bundle){ final Dictionary<String, String> headers = bundle.getHeaders(); String activator = headers.get(Constants.BUNDLE_ACTIVATOR); Class<?> activatorClass; Object activatorInstance; try { activatorClass = bundle.loadClass(activator); try { Method method = activatorClass.getMethod("getDefault"); activatorInstance = method.invoke(null); } catch (NoSuchMethodException e) { throw new PluginConfigurationException("Cannot find getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (SecurityException e) { throw new PluginConfigurationException("Error accessing getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (IllegalAccessException e) { throw new PluginConfigurationException("Error accessing getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (IllegalArgumentException e) { throw new PluginConfigurationException("Error accessing getDefault method in activator of bundle "+bundle.getBundleId(),e); } catch (InvocationTargetException e) { throw new PluginConfigurationException("Error accessing getDefault method in activator of bundle "+bundle.getBundleId(),e); } return (AbstractUIPlugin) activatorInstance; } catch (ClassNotFoundException e) { throw new PluginConfigurationException("Cannot find activator for bundle "+bundle.getBundleId(),e); } }
Source:
void hideCurrentToolTip () { checkWidget (); if (this.selectedMenuItem != null) { selectedMenuItem.hideToolTip (); } }

Target:
void hideCurrentToolTip () { if (this.selectedMenuItem != null) { selectedMenuItem.hideToolTip (); } }
Source:
protected void createAuthorizationUser() { MongoDatabase admin = mongo.getDatabase("admin"); MongoCollection<Document> usersCollection = admin.getCollection("system.users"); if (usersCollection.count() == 0) { usersCollection.insertOne(Document.parse("{\n" + " \"_id\": \"admin.test-user\",\n" + " \"user\": \"test-user\",\n" + " \"db\": \"admin\",\n" + " \"credentials\": {\n" + " \"SCRAM-SHA-1\": {\n" + " \"iterationCount\": 10000,\n" + " \"salt\": \"gmmPAoNdvFSWCV6PGnNcAw==\",\n" + " \"storedKey\": \"qE9u1Ax7Y40hisNHL2b8/LAvG7s=\",\n" + " \"serverKey\": \"RefeJcxClt9JbOP/VnrQ7YeQh6w=\"\n" + " }\n" + " },\n" + " \"roles\": [\n" + " {\n" + " \"role\": \"readWrite\",\n" + " \"db\": \"test\"\n" + " }\n" + " ]\n" + "}" + "")); } }

Target:
protected void createAuthorizationUser() { MongoDatabase admin = mongo.getDatabase("admin"); MongoCollection<Document> usersCollection = admin.getCollection("system.users"); if (usersCollection.count() == 0) { usersCollection.insertOne(Document.parse("{\n" + " \"_id\": \"admin.test-user\",\n" + " \"user\": \"test-user\",\n" + " \"db\": \"admin\",\n" + " \"credentials\": {\n" + " \"SCRAM-SHA-1\": {\n" + " \"iterationCount\": 10000,\n" + " \"salt\": \"gmmPAoNdvFSWCV6PGnNcAw==\",\n" + " \"storedKey\": \"qE9u1Ax7Y40hisNHL2b8/LAvG7s=\",\n" + " \"serverKey\": \"RefeJcxClt9JbOP/VnrQ7YeQh6w=\"\n" + " }\n" + " },\n" + " \"roles\": [\n" + " {\n" + " \"role\": \"readWrite\",\n" + " \"db\": \"test\"\n" + " }\n" + " ]\n" + "}")); } }
Source:
public Map<String, Set<String>> calculateHostGroups(Map<String, Set<String>> hostComponentMap) { return hostComponentMap.keySet().stream() .collect(toMap(host -> "hostgroup_" + host, host -> ImmutableSet.of(host))); }

Target:
public Map<String, Set<String>> calculateHostGroups(Map<String, Set<String>> hostComponentMap) { return hostComponentMap.keySet().stream() .collect(toMap(host -> "host_group_" + host, host -> ImmutableSet.of(host))); }
Source:
private void storeInitialText(Node root) { Map<Node, List<JavaToken>> tokensByNode = new IdentityHashMap<>(); List<Node> nodesDepthFirst = new LinkedList<>(); new TreeVisitor(){ @Override public void process(Node node) { if (!PhantomNodeLogic.isPhantomNode(node)) { nodesDepthFirst.add(node); } } }.visitLeavesFirst(root); for (JavaToken token : root.getTokenRange().get()) { Optional<Node> maybeOwner = nodesDepthFirst.stream().filter(n -> n.getRange().get().contains(token.getRange())).findFirst(); if (!maybeOwner.isPresent()) { throw new RuntimeException("Token without node owning it: " + token); } Node owner = maybeOwner.get(); if (!tokensByNode.containsKey(owner)) { tokensByNode.put(owner, new LinkedList<>()); } tokensByNode.get(owner).add(token); } new TreeVisitor() { @Override public void process(Node node) { if (!PhantomNodeLogic.isPhantomNode(node)) { LexicalPreservingPrinter.this.storeInitialTextForOneNode(node, tokensByNode.get(node)); } } }.visitBreadthFirst(root); }

Target:
private void storeInitialText(Node root) { Map<Node, List<JavaToken>> tokensByNode = new IdentityHashMap<>(); List<Node> nodesDepthFirst = new LinkedList<>(); new TreeVisitor(){ @Override public void process(Node node) { if (!PhantomNodeLogic.isPhantomNode(node)) { nodesDepthFirst.add(node); } } }.visitLeavesFirst(root); for (JavaToken token : root.getTokenRange().get()) { Range tokenRange = token.getRange().orElseThrow(() -> new RuntimeException("Token without range: " + token)); Node owner = nodesDepthFirst.stream() .filter(n -> n.getRange().get().contains(tokenRange)) .findFirst() .orElseThrow(() -> new RuntimeException("Token without node owning it: " + token)); if (!tokensByNode.containsKey(owner)) { tokensByNode.put(owner, new LinkedList<>()); } tokensByNode.get(owner).add(token); } new TreeVisitor() { @Override public void process(Node node) { if (!PhantomNodeLogic.isPhantomNode(node)) { LexicalPreservingPrinter.this.storeInitialTextForOneNode(node, tokensByNode.get(node)); } } }.visitBreadthFirst(root); }
Source:
public void testPutAllBatch() throws Exception { int numberOfEntries = 100; String cacheName = "testPutAllBatch"; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.read(cacheManager.getDefaultCacheConfiguration()); createCacheStoreConfig(cb.persistence(), false); cacheManager.defineConfiguration(cacheName, cb.build()); Cache<Integer, String> cache = cacheManager.getCache(cacheName); Map<Integer, String> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(Function.identity(), i -> "Val"+i)); cache.putAll(entriesMap); assertEquals(numberOfEntries, cache.size()); CacheLoader cl = TestingUtil.getCacheLoader(cache); if (cl != null) IntStream.range(0, numberOfEntries).forEach(i -> assertNotNull(cl.load(i))); }

Target:
public void testPutAllBatch() throws Exception { int numberOfEntries = 100; String cacheName = "testPutAllBatch"; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.read(cacheManager.getDefaultCacheConfiguration()); createCacheStoreConfig(cb.persistence(), false); cacheManager.defineConfiguration(cacheName, cb.build()); Cache<String, Object> cache = cacheManager.getCache(cacheName); Map<String, Object> entriesMap = IntStream.range(0, numberOfEntries).boxed() .collect(Collectors.toMap(i -> i.toString(), i -> wrap(i.toString(), "Val"+i))); cache.putAll(entriesMap); assertEquals(numberOfEntries, cache.size()); CacheLoader cl = TestingUtil.getCacheLoader(cache); if (cl != null) IntStream.range(0, numberOfEntries).forEach(i -> assertNotNull(cl.load(Integer.toString(i)))); }
Source:
protected AbstractUdpListener(TransportAddress localAddress) throws IOException { boolean bindWildcard = StackProperties.getBoolean( StackProperties.BIND_WILDCARD, false); if (bindWildcard) { this.localAddress = new TransportAddress( (InetAddress) null, localAddress.getPort(), localAddress.getTransport() ); } else { this.localAddress = localAddress; } socket = new DatagramSocket( localAddress ); int receiveBufferSize = StackProperties.getInt(SO_RCVBUF_PNAME, -1); if (receiveBufferSize > 0) { socket.setReceiveBufferSize(receiveBufferSize); } String logMessage = "Initialized AbstractUdpListener with address " + localAddress; logMessage += ". Receive buffer size " + socket.getReceiveBufferSize(); if (receiveBufferSize > 0) { logMessage += " (asked for " + receiveBufferSize + ")"; } logger.info(logMessage); thread = new Thread() { @Override public void run() { AbstractUdpListener.this.runInHarvesterThread(); } }; thread.setName(AbstractUdpListener.class.getName() + " thread for " + localAddress); thread.setDaemon(true); thread.start(); }

Target:
protected AbstractUdpListener(TransportAddress localAddress) throws IOException { boolean bindWildcard = StackProperties.getBoolean( StackProperties.BIND_WILDCARD, false); if (bindWildcard) { this.localAddress = new TransportAddress( (InetAddress) null, localAddress.getPort(), localAddress.getTransport() ); } else { this.localAddress = localAddress; } socket = new DatagramSocket( this.localAddress ); int receiveBufferSize = StackProperties.getInt(SO_RCVBUF_PNAME, -1); if (receiveBufferSize > 0) { socket.setReceiveBufferSize(receiveBufferSize); } String logMessage = "Initialized AbstractUdpListener with address " + this.localAddress; logMessage += ". Receive buffer size " + socket.getReceiveBufferSize(); if (receiveBufferSize > 0) { logMessage += " (asked for " + receiveBufferSize + ")"; } logger.info(logMessage); thread = new Thread() { @Override public void run() { AbstractUdpListener.this.runInHarvesterThread(); } }; thread.setName(AbstractUdpListener.class.getName() + " thread for " + this.localAddress); thread.setDaemon(true); thread.start(); }
Source:
private List<Course> getCourseEntities(List<String> courseIds) { if (courseIds.isEmpty()) { return new ArrayList<Course>(); } return new ArrayList<Course>(load().ids(courseIds).values()); }

Target:
private List<Course> getCourseEntities(List<String> courseIds) { if (courseIds.isEmpty()) { return new ArrayList<>(); } return new ArrayList<>( load().ids(courseIds).values()); }
Source:
public synchronized Transaction beginTransaction( String bookmark ) { if ( bookmark != null ) { this.bookmark = bookmark; } return beginTransaction(); }

Target:
public synchronized Transaction beginTransaction( String bookmark ) { if ( bookmark != null ) { setBookmark( bookmark ); } return beginTransaction(); }
Source:
public void onClick(ClickEvent event) { if (event.getSource() instanceof ListGroupItem) { PatternflyListViewItem<T> clickedItem = null; for (PatternflyListViewItem<T> item : currentState) { if (item.asListGroupItem().equals(event.getSource())) { clickedItem = item; break; } } if (clickedItem != null) { for (int i = 0; i < getWidgetCount(); i++) { IsWidget widget = getWidget(i); widget.asWidget().removeStyleName(Styles.ACTIVE); } if (!event.isControlKeyDown()) { clickedItem.asListGroupItem().addStyleName(Styles.ACTIVE); selectionModel.setSelected(clickedItem.getEntity(), true); List<T> items = getModel().getItemsAsList(); if (items != null) { selectedIndex = items.indexOf(clickedItem.getEntity()); } getModel().setSelectedItem(clickedItem.getEntity()); } else { selectionModel.setSelected(clickedItem.getEntity(), false); selectedIndex = -1; getModel().setSelectedItem(null); } } } }

Target:
public void onClick(ClickEvent event) { if (event.getSource() instanceof ListGroupItem) { PatternflyListViewItem<T> clickedItem = null; for (PatternflyListViewItem<T> item : currentState) { if (item.asListGroupItem() == event.getSource()) { clickedItem = item; break; } } if (clickedItem != null) { for (int i = 0; i < getWidgetCount(); i++) { IsWidget widget = getWidget(i); widget.asWidget().removeStyleName(Styles.ACTIVE); } if (!event.isControlKeyDown()) { clickedItem.asListGroupItem().addStyleName(Styles.ACTIVE); selectionModel.setSelected(clickedItem.getEntity(), true); List<T> items = getModel().getItemsAsList(); if (items != null) { selectedIndex = items.indexOf(clickedItem.getEntity()); } getModel().setSelectedItem(clickedItem.getEntity()); } else { selectionModel.setSelected(clickedItem.getEntity(), false); selectedIndex = -1; getModel().setSelectedItem(null); } } } }
Source:
public void getComputerNames() throws Exception { assertThat(ComputerSet.getComputerNames(), is(empty())); j.createSlave("aNode", "", null); assertThat(ComputerSet.getComputerNames(), hasSize(1)); assertThat(ComputerSet.getComputerNames(), contains("aNode")); j.createSlave("anAnotherNode", "", null); assertThat(ComputerSet.getComputerNames(), hasSize(2)); assertThat(ComputerSet.getComputerNames(), containsInAnyOrder("aNode", "anAnotherNode")); }

Target:
public void getComputerNames() throws Exception { assertThat(ComputerSet.getComputerNames(), is(empty())); j.createSlave("aNode", "", null); assertThat(ComputerSet.getComputerNames(), contains("aNode")); j.createSlave("anAnotherNode", "", null); assertThat(ComputerSet.getComputerNames(), containsInAnyOrder("aNode", "anAnotherNode")); }
Source:
public void visitNode(Tree tree) { ControlFlowGraph cfg = ControlFlowGraph.build(tree, context()); if (cfg == null) { return; } LiveVariablesAnalysis lva = LiveVariablesAnalysis.analyze(cfg, context().symbolTable()); Map<Symbol, Set<VariableUsage>> usagesInCfg = new HashMap<>(); cfg.blocks().forEach(block -> addUsages(lva.getLiveVariables(block), usagesInCfg)); Set<Symbol> readInCfg = getReadSymbols(usagesInCfg); cfg.blocks().forEach(block -> verifyBlock(block, lva.getLiveVariables(block), readInCfg)); }

Target:
public void visitNode(Tree tree) { ControlFlowGraph cfg = ControlFlowGraph.build(tree, context()); if (cfg == null) { return; } LiveVariablesAnalysis lva = LiveVariablesAnalysis.analyze(cfg, context().symbolTable()); cfg.blocks().forEach(block -> verifyBlock(block, lva.getLiveVariables(block), lva.getReadSymbols())); }
Source:
public void resendEmailConfirmation( String email ) throws BackendlessException { if( email == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "resendEmailConfirmation", new Object[]{ Backendless.getApplicationId(), Backendless.getVersion(), email } ); }

Target:
public void resendEmailConfirmation( String email ) throws BackendlessException { if( email == null || email.isEmpty() ) throw new IllegalArgumentException( ExceptionMessage.NULL_EMAIL ); Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "resendEmailConfirmation", new Object[]{ Backendless.getApplicationId(), Backendless.getVersion(), email } ); }
Source:
public void addNode(String instanceName, Node node) throws MultipleInstantiationException { if(nodes.containsKey(instanceName)){ throw new MultipleInstantiationException("node", instanceName); } nodes.put(instanceName, node); }

Target:
public void addNode(String instanceName, Node node) throws MultipleAssignmentException { if(nodes.containsKey(instanceName)){ throw new MultipleAssignmentException("node", instanceName); } nodes.put(instanceName, node); }
Source:
public static Color mixColors(Color... colors) { Validate.noNullElements(colors, "No null colors allowed!"); checkArgument(colors.length > 0, "Cannot have an empty color array!"); if (colors.length == 1) { return colors[0]; } else { int red = colors[0].getRed(); int green = colors[0].getGreen(); int blue = colors[0].getBlue(); for (int i = 1; i < colors.length; i++) { red += colors[i].getRed(); green += colors[i].getGreen(); blue += colors[i].getBlue(); } double averageRed = red / colors.length; double averageGreen = green / colors.length; double averageBlue = blue / colors.length; return ofRGB((int) Math.round(averageRed), (int) Math.round(averageGreen), (int) Math.round(averageBlue)); } }

Target:
public static Color mixColors(Color... colors) { Validate.noNullElements(colors, "No null colors allowed!"); checkArgument(colors.length > 0, "Cannot have an empty color array!"); if (colors.length == 1) { return colors[0]; } else { int red = colors[0].getRed(); int green = colors[0].getGreen(); int blue = colors[0].getBlue(); for (int i = 1; i < colors.length; i++) { red += colors[i].getRed(); green += colors[i].getGreen(); blue += colors[i].getBlue(); } int averageRed = Math.round((float) red / colors.length); int averageGreen = Math.round((float) green / colors.length); int averageBlue = Math.round((float) blue / colors.length); return ofRgb(averageRed, averageGreen, averageBlue); } }
Source:
public List<String> findExpired(long timestamp) throws ServerException { requireNonNull(timestamp, "Required non-null timestamp"); try { return doFindExpired(timestamp); } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }

Target:
public List<String> findExpired(long timestamp) throws ServerException { try { return doFindExpired(timestamp); } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }
Source:
protected String name() { return DEFAULT_NAME; }

Target:
public String name() { return DEFAULT_NAME; }
Source:
private void createUserInternal(String prefix, String userName) { int attempts = 0; while (attempts < numRetries) { if (createUserOnce(prefix, userName)) { return; } else { attempts++; } } throw new ISE("Could not create user[%s] due to concurrent update contention.", userName); }

Target:
private void createUserInternal(String prefix, String userName) { int attempts = 0; while (attempts < numRetries) { if (createUserOnce(prefix, userName)) { return; } else { attempts++; } try { Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY)); } catch (InterruptedException ie) { throw new RuntimeException(ie); } } throw new ISE("Could not create user[%s] due to concurrent update contention.", userName); }
Source:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { if (properties == null || properties.size() == 0) return; float homeLat = Float.parseFloat(getOptionalProperty(properties, "home.lat", "0")); float homeLon = Float.parseFloat(getOptionalProperty(properties, "home.lon", "0")); if (homeLat == 0 || homeLon == 0) { homeLocation = null; geoFence = 0; logger.debug("Mqttitude binding configuration updated, no 'home' location specified. All item bindings must be configured with a <region>."); } else { homeLocation = new Location(homeLat, homeLon); geoFence = Float.parseFloat(getOptionalProperty(properties, "geofence", "100")); logger.debug("Mqttitude binding configuration updated, 'home' location specified ({}) with a geofence of {}m.", homeLocation.toString(), geoFence); } maxGpsAccuracy = Integer.parseInt(getOptionalProperty(properties, "max_gps_accuracy", "-1")); if (maxGpsAccuracy < 0) { logger.debug("Mqttitude binding configuration: no limit on GPS accuracy"); } else { logger.debug("Mqttitude binding configuration: GPS accuracy limit is {}", maxGpsAccuracy); } unregisterAll(); registerAll(); }

Target:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { if (properties == null || properties.size() == 0) return; float homeLat = Float.parseFloat(getOptionalProperty(properties, "home.lat", "0")); float homeLon = Float.parseFloat(getOptionalProperty(properties, "home.lon", "0")); if (homeLat == 0 || homeLon == 0) { homeLocation = null; geoFence = 0; logger.debug("Mqttitude binding configuration updated, no 'home' location specified. All item bindings must be configured with a <region>."); } else { homeLocation = new Location(homeLat, homeLon); geoFence = Float.parseFloat(getOptionalProperty(properties, "geofence", "100")); logger.debug("Mqttitude binding configuration updated, 'home' location specified ({}) with a geofence of {}m.", homeLocation.toString(), geoFence); } maxGpsAccuracy = Float.parseFloat(getOptionalProperty(properties, "max_gps_accuracy", "NaN")); if (Float.isNaN(maxGpsAccuracy)) { logger.debug("Mqttitude binding configuration: no limit on GPS accuracy"); } else { logger.debug("Mqttitude binding configuration: GPS accuracy limit is {}", maxGpsAccuracy); } unregisterAll(); registerAll(); }
Source:
public void parapgraphWithUnknownEntityReferenceHavingEscapableChars() { assertParagraphWithEntityReference("&\\#unknown;\n\n", "#unknown"); }

Target:
public void parapgraphWithUnknownEntityReferenceHavingEscapableChars() { assertParagraphWithEntityReference("&#unknown;\n\n", "#unknown"); }
Source:
protected void executeCommand() { boolean result = true; boolean isSingleHostInDC = getVdsDAO().getAllForStoragePool(getStoragePool().getId()).size() == 1; setVdsName(_problematicVds.getName()); if (_problematicVds.getSpmStatus() == VdsSpmStatus.SPM) { result = ActivateDataCenter(); if (isSingleHostInDC) { storage_pool sp = getStoragePool(); sp.setspm_vds_id(null); getStoragePoolDAO().update(sp); result = true; } } if ((getParameters()).getClearVMs() && result) { VdsActionParameters tempVar = new VdsActionParameters(_problematicVds.getId()); tempVar.setSessionId(getParameters().getSessionId()); Backend.getInstance().runInternalAction(VdcActionType.ClearNonResponsiveVdsVms, tempVar, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); } setSucceeded(result); if (getSucceeded()) { AlertDirector.RemoveAllVdsAlerts(_problematicVds.getId(), false); } }

Target:
protected void executeCommand() { boolean result = true; setVdsName(_problematicVds.getName()); if (_problematicVds.getSpmStatus() == VdsSpmStatus.SPM) { result = ActivateDataCenter(); if (getVdsDAO().getAllForStoragePool(getStoragePool().getId()).size() == 1) { storage_pool sp = getStoragePool(); sp.setspm_vds_id(null); getStoragePoolDAO().update(sp); result = true; } } if ((getParameters()).getClearVMs() && result) { VdsActionParameters tempVar = new VdsActionParameters(_problematicVds.getId()); tempVar.setSessionId(getParameters().getSessionId()); Backend.getInstance().runInternalAction(VdcActionType.ClearNonResponsiveVdsVms, tempVar, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); } setSucceeded(result); if (getSucceeded()) { AlertDirector.RemoveAllVdsAlerts(_problematicVds.getId(), false); } }
Source:
public void setUp() { statsProvider = new TaskCountStatsProvider() { @Override public Map<String, Long> getSuccessfulTaskCount() { return null; } @Override public Map<String, Long> getFailedTaskCount() { return null; } @Override public Map<String, Long> getRunningTaskCount() { return ImmutableMap.of("d1", 1L); } @Override public Map<String, Long> getPendingTaskCount() { return null; } @Override public Map<String, Long> getWaitingTaskCount() { return null; } }; }

Target:
public void setUp() { statsProvider = new TaskCountStatsProvider() { @Override public Map<String, Long> getSuccessfulTaskCount() { return ImmutableMap.of("d1", 1L); } @Override public Map<String, Long> getFailedTaskCount() { return ImmutableMap.of("d1", 1L); } @Override public Map<String, Long> getRunningTaskCount() { return ImmutableMap.of("d1", 1L); } @Override public Map<String, Long> getPendingTaskCount() { return ImmutableMap.of("d1", 1L); } @Override public Map<String, Long> getWaitingTaskCount() { return ImmutableMap.of("d1", 1L); } }; }
Source:
static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("StartpointModule", new Version(1, 0, 0, "")); module.addSerializer(Instant.class, new CustomInstantSerializer()); module.addDeserializer(Instant.class, new CustomInstantDeserializer()); objectMapper.registerModule(module); objectMapper.registerSubtypes(StartpointSpecific.class); objectMapper.registerSubtypes(StartpointTimestamp.class); objectMapper.registerSubtypes(StartpointUpcoming.class); objectMapper.registerSubtypes(StartpointOldest.class); return objectMapper; }

Target:
static ObjectMapper getObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("StartpointModule", new Version(1, 0, 0, "")); module.addSerializer(Instant.class, new CustomInstantSerializer()); module.addDeserializer(Instant.class, new CustomInstantDeserializer()); objectMapper.registerModule(module); objectMapper.registerSubtypes(new NamedType(StartpointSpecific.class)); objectMapper.registerSubtypes(new NamedType(StartpointTimestamp.class)); objectMapper.registerSubtypes(new NamedType(StartpointUpcoming.class)); objectMapper.registerSubtypes(new NamedType(StartpointOldest.class)); return objectMapper; }
Source:
private InteractionNode spanToNode(Span span) { String endpointType = "http"; String url = span.url() != null ? span.url().toString() : null; InteractionNode node; if (span.serverSpan()) { node = new Consumer(url, endpointType); }else if (span.clientSpan()) { node = new Producer(url, endpointType); } else { node = new Component(url, endpointType); } node.setBaseTime(span.getTimestamp()); node.addInteractionId(span.getId()); return node; }

Target:
private InteractionNode spanToNode(Span span) { String endpointType = "HTTP"; String url = span.url() != null ? span.url().getPath() : null; InteractionNode node; if (span.serverSpan()) { node = new Consumer(url, endpointType); node.addInteractionId(span.getId()); }else if (span.clientSpan()) { node = new Producer(url, endpointType); node.addInteractionId(span.getId()); } else { node = new Component(url, null); } node.setBaseTime(TimeUnit.NANOSECONDS.convert(span.getTimestamp(), TimeUnit.MICROSECONDS)); node.setDuration(TimeUnit.NANOSECONDS.convert(span.getDuration(), TimeUnit.MICROSECONDS)); return node; }
Source:
public IStatus zip(String endpointURL, String mission, String runtime, String runtimeVersion, String projectName, String groupId, String artifactId, String version, OutputStream output, IProgressMonitor monitor) { if (!endpointURL.endsWith("/")) { endpointURL += "/"; } endpointURL += LAUNCHER_ZIP_PREFIX; endpointURL += '?'; endpointURL += LAUNCHER_ZIP_MISSION_PARAMETER_NAME + '=' + mission + '&'; endpointURL += LAUNCHER_ZIP_RUNTIME_PARAMETER_NAME + '=' + runtime + '&'; endpointURL += LAUNCHER_ZIP_RUNTIME_VERSION_PARAMETER_NAME + '=' + runtimeVersion + '&'; endpointURL += LAUNCHER_ZIP_PROJECT_NAME_PARAMETER_NAME + '=' + projectName + '&'; endpointURL += LAUNCHER_ZIP_GROUP_ID_PARAMETER_NAME + '=' + groupId + '&'; endpointURL += LAUNCHER_ZIP_ARTIFACT_ID_PARAMETER_NAME + '=' + artifactId + '&'; endpointURL += LAUNCHER_ZIP_VERSION_PARAMETER_NAME + '=' + version; try { return TRANSPORT_UTILITY.download(endpointURL, endpointURL, output, monitor); } catch (RuntimeException e) { return new Status(IStatus.ERROR, LauncherCorePlugin.PLUGIN_ID, e.getLocalizedMessage(), e); } }

Target:
public IStatus zip(String endpointURL, String mission, String runtime, String runtimeVersion, String projectName, String groupId, String artifactId, String version, OutputStream output, IProgressMonitor monitor) { StringBuilder builder = new StringBuilder(endpointURL); if (!endpointURL.endsWith("/")) { builder.append('/'); } builder.append(LAUNCHER_ZIP_PREFIX); builder.append('?'); builder.append(LAUNCHER_ZIP_MISSION_PARAMETER_NAME).append('=').append(mission).append('&'); builder.append(LAUNCHER_ZIP_RUNTIME_PARAMETER_NAME).append('=').append(runtime).append('&'); builder.append(LAUNCHER_ZIP_RUNTIME_VERSION_PARAMETER_NAME).append('=').append(runtimeVersion).append('&'); builder.append(LAUNCHER_ZIP_PROJECT_NAME_PARAMETER_NAME).append('=').append(projectName).append('&'); builder.append(LAUNCHER_ZIP_GROUP_ID_PARAMETER_NAME).append('=').append(groupId).append('&'); builder.append(LAUNCHER_ZIP_ARTIFACT_ID_PARAMETER_NAME).append('=').append(artifactId).append('&'); builder.append(LAUNCHER_ZIP_VERSION_PARAMETER_NAME).append('=').append(version); try { String url = builder.toString(); return TRANSPORT_UTILITY.download(url, url, output, monitor); } catch (RuntimeException e) { return new Status(IStatus.ERROR, LauncherCorePlugin.PLUGIN_ID, e.getLocalizedMessage(), e); } }
Source:
Bitmap decodeResource(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().replaceFirst("/", ""); try { return decodeResource(Integer.parseInt(path), bitmapOptions); } catch (NumberFormatException ignore) { throw new IOException("\"" + path + "\" isn't a valid resource id"); } }

Target:
Bitmap decodeResource(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().substring(1); try { return decodeResource(Integer.parseInt(path), bitmapOptions); } catch (NumberFormatException exception) { throw new IOException("\"" + path + "\" isn't a valid resource id", exception); } }
Source:
private void updateSchedules( StoredRevision revision, List<StoredWorkflowDefinition> defs, SchedulerManager srm, Instant currentTime) throws ResourceConflictException { ImmutableList.Builder<Schedule> schedules = ImmutableList.builder(); Map<Long, Scheduler> wfIdToSchedulers = new HashMap<>(); for (StoredWorkflowDefinition def : defs) { Optional<Scheduler> sr = srm.tryGetScheduler(revision, def); if (sr.isPresent()) { ScheduleTime firstTime = sr.get().getFirstScheduleTime(currentTime); Schedule schedule = Schedule.of(def.getName(), def.getId(), firstTime.getRunTime(), firstTime.getTime()); schedules.add(schedule); wfIdToSchedulers.put(schedule.getWorkflowDefinitionId(), sr.get()); } } store.updateSchedules(project.getId(), schedules.build(), (oldStatus, newSched) -> { return oldStatus.getLastScheduleTime() .transform(it -> wfIdToSchedulers.get(newSched.getWorkflowDefinitionId()).nextScheduleTime(it)) .or(() -> ScheduleTime.of(newSched.getNextScheduleTime(), newSched.getNextRunTime())); }); }

Target:
private void updateSchedules( StoredRevision revision, List<StoredWorkflowDefinition> defs, SchedulerManager srm, Instant currentTime) throws ResourceConflictException { ImmutableList.Builder<ScheduleWithScheduler> schedules = ImmutableList.builder(); for (StoredWorkflowDefinition def : defs) { Optional<Scheduler> sr = srm.tryGetScheduler(revision, def); if (sr.isPresent()) { ScheduleTime firstTime = sr.get().getFirstScheduleTime(currentTime); Schedule schedule = Schedule.of(def.getName(), def.getId(), firstTime.getRunTime(), firstTime.getTime()); schedules.add(new ScheduleWithScheduler(schedule, sr.get())); } } store.updateSchedules(project.getId(), schedules.build(), (oldStatus, newSched) -> { return oldStatus.getLastScheduleTime() .transform(it -> newSched.getScheduler().nextScheduleTime(it)) .or(() -> ScheduleTime.of(newSched.getNextScheduleTime(), newSched.getNextRunTime())); }); }
Source:
public void testEnableConfigurationsException() throws Exception { setUpListServices(); when(testMTI.getObjectClassDefinition(anyString(), anyString())).thenReturn(null); org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class); ConfigurationAdminImpl configurationAdminImpl = getConfigurationAdminImpl(testConfigAdmin, new ArrayList<>()); Configuration testConfig = mock(Configuration.class); Configuration testFactoryConfig = mock(Configuration.class); Dictionary<String, Object> testProperties = new Hashtable<>(); testProperties.put( org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, TEST_FACT_PID_DISABLED); when(testConfigAdmin.listConfigurations('(' + Constants.SERVICE_PID + '=' + TEST_PID + ')')) .thenReturn(new Configuration[] {testConfig}); when(testConfig.getProperties()).thenReturn(testProperties); when(testFactoryConfig.getPid()).thenReturn(TEST_FACTORY_PID); configurationAdminImpl.enableManagedServiceFactoryConfiguration(TEST_PID, testConfig); }

Target:
public void testEnableConfigurationsException() throws Exception { setUpListServices(); when(testMTI.getObjectClassDefinition(TEST_FACTORY_PID, Locale.getDefault().toString())) .thenReturn(null); org.osgi.service.cm.ConfigurationAdmin testConfigAdmin = mock(org.osgi.service.cm.ConfigurationAdmin.class); ConfigurationAdminImpl configurationAdminImpl = getConfigurationAdminImpl(testConfigAdmin, new ArrayList<>()); Configuration testConfig = mock(Configuration.class); Configuration testFactoryConfig = mock(Configuration.class); Dictionary<String, Object> testProperties = new Hashtable<>(); testProperties.put( org.osgi.service.cm.ConfigurationAdmin.SERVICE_FACTORYPID, TEST_FACT_PID_DISABLED); when(testConfigAdmin.listConfigurations('(' + Constants.SERVICE_PID + '=' + TEST_PID + ')')) .thenReturn(new Configuration[] {testConfig}); when(testConfig.getProperties()).thenReturn(testProperties); when(testFactoryConfig.getPid()).thenReturn(TEST_FACTORY_PID); configurationAdminImpl.enableManagedServiceFactoryConfiguration(TEST_PID, testConfig); }
Source:
public PluginFirstClassLoader() { super(); try { Field $pathComponents = AntClassLoader.class.getDeclaredField("pathComponents"); $pathComponents.setAccessible(true); pathComponents = (Vector)$pathComponents.get(this); } catch (NoSuchFieldException | IllegalAccessException e) { throw new Error(e); } }

Target:
public PluginFirstClassLoader() { super(null, false); }
Source:
public void combine(Iterator<Tuple2<K, IN>> values, Collector<Tuple2<K, IN>> out) throws Exception { if(this.wrappedFunction.getClass().getAnnotation(Combinable.class) != null && values.hasNext()) { iter.set(values); TupleWrappingCollector<K, IN> combColl = new TupleWrappingCollector<K, IN>(iter.getKey(), out); this.wrappedFunction.combine(iter, combColl); } }

Target:
public void combine(Iterator<Tuple2<K, IN>> values, Collector<Tuple2<K, IN>> out) throws Exception { iter.set(values); combineCollector.set(iter.getKey(), out); this.wrappedFunction.combine(iter, combineCollector); }
Source:
public void testRefreshDoesntHang() throws IOException, InterruptedException, ExecutionException, TimeoutException { setTime(2L); final int expiration = HeaderCacheElement.TOKEN_STALENESS_MS + 1; final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); final AtomicBoolean completed = new AtomicBoolean(false); Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); completed.set(true); return null; } }; Future<Void> future = executorService.submit(syncRefreshCallable); try { future.get(100, TimeUnit.MILLISECONDS); } catch (Exception ignored) { } synchronized(lock) { lock.notifyAll(); } future.get(1000, TimeUnit.MILLISECONDS); Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Assert.assertFalse(underTest.isRefreshing.get()); underTest.asyncRefresh(); underTest.asyncRefresh(); Thread.sleep(100); Assert.assertTrue(underTest.isRefreshing.get()); completed.set(false); future = executorService.submit(syncRefreshCallable); Thread.sleep(100); Assert.assertFalse(completed.get()); synchronized(lock) { lock.notifyAll(); } future.get(); Assert.assertTrue(completed.get()); Assert.assertFalse(underTest.isRefreshing.get()); }

Target:
public void testRefreshDoesntHang() throws Exception, TimeoutException { long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Future<Void> future = executorService.submit(syncRefreshCallable); Thread.yield(); synchronized(lock) { lock.notifyAll(); } future.get(1, TimeUnit.SECONDS); Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Assert.assertFalse(underTest.isRefreshing.get()); underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); future = executorService.submit(syncRefreshCallable); Thread.yield(); Assert.assertTrue(underTest.isRefreshing.get()); synchronized(lock) { lock.notifyAll(); } future.get(1, TimeUnit.SECONDS); Assert.assertFalse(underTest.isRefreshing.get()); }