auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testDoubleSequence() throws Exception { tester.testRoundTrip(DOUBLE, doubleSequence(0, 0.1, 30_000, false)); tester.testRoundTrip(DOUBLE, doubleSequence(0, 0.1, 30_000, true)); List<Map<Integer, TupleDomainFilter>> filters = ImmutableList.of( ImmutableMap.of(0, DoubleRange.of(0, false, false, Double.MAX_VALUE / 2000, false, false, false)), ImmutableMap.of(0, DoubleRange.of(-1, true, false, 1, false, false, false)), ImmutableMap.of(0, DoubleRange.of(-1, true, true, 2, false, false, false)), ImmutableMap.of(0, DoubleRange.of(1, true, true, 2, true, false, false)), ImmutableMap.of(0, DoubleRange.of(1, false, false, 4, false, true, true)), ImmutableMap.of(0, DoubleRange.of(0, false, false, 40, false, false, true))); tester.testRoundTrip(DOUBLE, doubleSequence(0, 0.1, 30_000, false), filters); tester.testRoundTrip(DOUBLE, doubleSequence(0, 0.1, 30_000, true), filters); }

Target:
public void testDoubleSequence() throws Exception { List<Map<Integer, TupleDomainFilter>> filters = ImmutableList.of( ImmutableMap.of(0, DoubleRange.of(0, false, false, 1_000, false, false, false)), ImmutableMap.of(0, IS_NULL), ImmutableMap.of(0, IS_NOT_NULL)); tester.testRoundTrip(DOUBLE, doubleSequence(0, 0.1, 30_000), filters); tester.testRoundTripTypes( ImmutableList.of(DOUBLE, DOUBLE), ImmutableList.of( doubleSequence(0, 0.1, 10_000), doubleSequence(0, 0.1, 10_000)), ImmutableList.of( ImmutableMap.of( 0, DoubleRange.of(1.0, false, true, 7.0, false, true, true), 1, DoubleRange.of(3.0, false, true, 9.0, false, true, false)))); }
Source:
public static boolean waitProcess(int pid, long poll, long timeout) { boolean exists = false; try { final long startTime = System.currentTimeMillis(); long now; do { Thread.sleep(poll); exists = (getPid(pid) >= 0) ? true : false; now = System.currentTimeMillis(); } while (exists && (now - startTime) < timeout); } catch (Exception e) { Thread.currentThread().interrupt(); s_logger.warn("Failed waiting for pid to exit - {}", pid, e); } return exists; }

Target:
private static boolean waitProcess(int pid, long poll, long timeout) { boolean exists = false; try { final long startTime = System.currentTimeMillis(); long now; do { Thread.sleep(poll); exists = isProcessRunning(pid); now = System.currentTimeMillis(); } while (exists && now - startTime < timeout); } catch (Exception e) { Thread.currentThread().interrupt(); logger.warn("Failed waiting for pid to exit - {}", pid, e); } return exists; }
Source:
private boolean syncFlags(LocalMessage localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null || localMessage.isSet(Flag.DELETED)) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { if (localMessage.getFolder().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } } else { for (Flag flag : SYNC_FLAGS) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } } return messageChanged; }

Target:
private boolean syncFlags(LocalMessage localMessage, Message remoteMessage) throws MessagingException { boolean messageChanged = false; if (localMessage == null) { return false; } if (remoteMessage.isSet(Flag.DELETED)) { if (localMessage.getFolder().syncRemoteDeletions()) { localMessage.setFlag(Flag.DELETED, true); messageChanged = true; } } else { for (Flag flag : SYNC_FLAGS) { if (remoteMessage.isSet(flag) != localMessage.isSet(flag)) { localMessage.setFlag(flag, remoteMessage.isSet(flag)); messageChanged = true; } } } return messageChanged; }
Source:
public void init() { if (fileBackup != null) { for (FileBackup.SavedBuffer savedBuffer : fileBackup.getSavedFiles()) { savedBuffer.open(new FileBackup.SavedBuffer.Callback() { @Override public void process(List<String> params, FileChannel channel) { LOG.debug("Loading buffer: params={}, buffer={}", params, channel); loadBufferFromFile(params, channel); } }); } } }

Target:
public void init() { if (fileBackup != null) { for (FileBackup.SavedBuffer savedBuffer : fileBackup.getSavedFiles()) { savedBuffer.open(new FileBackup.SavedBuffer.Callback() { @Override public void process(List<String> params, FileChannel channel) { LOG.info("Loading buffer: params={}, buffer={}", params, channel); loadBufferFromFile(params, channel); } }); } } }
Source:
public static @Nullable ITmfStateInterval queryUntilNonNullValue(ITmfStateSystem ss, int attributeQuark, long t1, long t2) { if (t2 < t1) { throw new TimeRangeException(ss.getSSID() + " Start:" + t1 + ", End:" + t2); } Iterator<ITmfStateInterval> iter = new QuarkIterator(ss, attributeQuark, t1); while (iter.hasNext()) { ITmfStateInterval interval = iter.next(); if (interval.getStartTime() > t2) { return null; } if (!interval.getStateValue().isNull()) { return interval; } } return null; }

Target:
public static @Nullable ITmfStateInterval queryUntilNonNullValue(ITmfStateSystem ss, int attributeQuark, long t1, long t2) { if (t2 < t1) { throw new TimeRangeException(ss.getSSID() + " Start:" + t1 + ", End:" + t2); } Iterator<ITmfStateInterval> iter = new QuarkIterator(ss, attributeQuark, t1); return Iterators .tryFind(iter, interval -> (!interval.getStateValue().isNull() && interval.getStartTime() <= t2)) .orNull(); }
Source:
private void addToolbarActions(IToolBarManager toolbarManager) { Action collapseAction = new Action(UIText.UIUtils_CollapseAll, PlatformUI.getWorkbench().getSharedImages().getImageDescriptor( ISharedImages.IMG_ELCL_COLLAPSEALL)) { @Override public void run() { getTreeViewer().collapseAll(); } }; toolbarManager.add(collapseAction); }

Target:
private void addToolbarActions(IToolBarManager toolbarManager) { Action collapseAction = new Action(UIText.UIUtils_CollapseAll, PlatformUI.getWorkbench().getSharedImages().getImageDescriptor( ISharedImages.IMG_ELCL_COLLAPSEALL)) { @Override public void run() { getTreeViewer().collapseAll(); } }; collapseAction.setActionDefinitionId(CollapseAllHandler.COMMAND_ID); collapseHandler = new CollapseAllHandler(getTreeViewer()); IHandlerService handlerService = getSite() .getService(IHandlerService.class); handlerService.activateHandler(CollapseAllHandler.COMMAND_ID, collapseHandler); toolbarManager.add(collapseAction); }
Source:
public FormValidation doCheckRemoteFS(@QueryParameter String value) throws IOException, ServletException { if(Util.fixEmptyAndTrim(value)==null) return FormValidation.error(Messages.Slave_Remote_Director_Mandatory()); if(value.startsWith("\\\\") || value.startsWith("/net/")) return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning()); if (!value.contains("\\") && !value.startsWith("/")) { return FormValidation.error(Messages.Slave_Remote_Relative_Path_Warning()); } return FormValidation.ok(); }

Target:
public FormValidation doCheckRemoteFS(@QueryParameter String value) throws IOException, ServletException { if(Util.fixEmptyAndTrim(value)==null) return FormValidation.error(Messages.Slave_Remote_Director_Mandatory()); if(value.startsWith("\\\\") || value.startsWith("/net/")) return FormValidation.warning(Messages.Slave_Network_Mounted_File_System_Warning()); if (Util.isRelativePath(value)) { return FormValidation.warning(Messages.Slave_Remote_Relative_Path_Warning()); } return FormValidation.ok(); }
Source:
public static void writeToDisk(boolean generatePackagesStructure, String outputPath, String relativeFileName, ClassFile classFile) throws IOException { FileOutputStream file = getFileOutputStream(generatePackagesStructure, outputPath, relativeFileName); try (BufferedOutputStream output = new BufferedOutputStream(file, DEFAULT_WRITING_SIZE)) { output.write(classFile.header, 0, classFile.headerOffset); output.write(classFile.contents, 0, classFile.contentsOffset); output.flush(); } catch(IOException e) { throw e; } }

Target:
public static void writeToDisk(boolean generatePackagesStructure, String outputPath, String relativeFileName, ClassFile classFile) throws IOException { FileOutputStream file = getFileOutputStream(generatePackagesStructure, outputPath, relativeFileName); try (BufferedOutputStream output = new BufferedOutputStream(file, DEFAULT_WRITING_SIZE)) { output.write(classFile.header, 0, classFile.headerOffset); output.write(classFile.contents, 0, classFile.contentsOffset); output.flush(); } }
Source:
@Test public void dragNDropByCoordinatesAndDurationTest() throws Exception { Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo"); driver.startActivity(activity); AndroidElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1")); AndroidElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3")); WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text")); assertEquals("Drag text not empty", "", dragText.getText()); Point center1 = dragDot1.getCenter(); Point center2 = dragDot3.getCenter(); TouchAction dragNDrop = new TouchAction(driver) .longPress(longPressOptions() .withPosition(coordinates(center1.x, center1.y)) .withDuration(ofSeconds(2))) .moveTo(position() .withPosition(coordinates(center2.x, center2.y))) .release(); dragNDrop.perform(); assertNotEquals("Drag text empty", "", dragText.getText()); }

Target:
@Test public void dragNDropByCoordinatesAndDurationTest() throws Exception { Activity activity = new Activity("io.appium.android.apis", ".view.DragAndDropDemo"); driver.startActivity(activity); AndroidElement dragDot1 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_1")); AndroidElement dragDot3 = driver.findElement(By.id("io.appium.android.apis:id/drag_dot_3")); WebElement dragText = driver.findElement(By.id("io.appium.android.apis:id/drag_text")); assertEquals("Drag text not empty", "", dragText.getText()); Point center1 = dragDot1.getCenter(); Point center2 = dragDot3.getCenter(); TouchAction dragNDrop = new TouchAction(driver) .longPress(longPressOptions() .withPosition(point(center1.x, center1.y)) .withDuration(ofSeconds(2))) .moveTo(point(center2.x, center2.y)) .release(); dragNDrop.perform(); assertNotEquals("Drag text empty", "", dragText.getText()); }
Source:
public void onCancel() { errorCallback.onError(new RequestCanceledException("Canceled request")); }

Target:
public void onCancel() { errorCallback.onError(new RequestCanceledException()); }
Source:
public void startConflictResolution(ConsistentHash conflictCH, List<Address> mergeMembers) { topology = new CacheTopology(topology.getTopologyId() + 1, topology.getRebalanceId() + 1, conflictCH, conflictCH, conflictCH, CacheTopology.Phase.CONFLICT_RESOLUTION, mergeMembers, persistentUUIDs(mergeMembers)); }

Target:
public void startConflictResolution(ConsistentHash conflictCH, List<Address> mergeMembers) { topology = new CacheTopology(topology.getTopologyId() + 1, topology.getRebalanceId() + 1, conflictCH, null, CacheTopology.Phase.CONFLICT_RESOLUTION, mergeMembers, persistentUUIDs(mergeMembers)); }
Source:
public <T2 extends ModelClass, U2 extends ModelClass> boolean matches(Message<T2, U2> expected) { if (expected == this) { return true; } if (expected == null) { return false; } if (fromActor.isPresent() && !fromActor.equals(expected.fromActor)) { return false; } if (sender != null && expected.sender != null && expected.sender.hasParticipant() && sender.getParticipant().get() != expected.sender.getParticipant().get()) { return false; } if (target != null && expected.target != null && expected.target.hasParticipant() && target.getParticipant().get() != expected.target.getParticipant().get()) { return false; } boolean areSignalsEqual; try { areSignalsEqual = BasedOnFields.equal(getWrapped(), expected.getWrapped()); } catch (IllegalAccessException e) { return false; } if (areSignalsEqual) { if (sender != null && expected.sender != null && !expected.sender.hasParticipant()) { expected.sender.bindTo(sender.getParticipant().get()); } if (!expected.target.hasParticipant()) { expected.target.bindTo(target.getParticipant().get()); } } return areSignalsEqual; }

Target:
public <T2 extends ModelClass, U2 extends ModelClass> boolean matches(Message<T2, U2> expected) { if (expected == this) { return true; } if (expected == null) { return false; } if (fromActor.isPresent() && !fromActor.equals(expected.fromActor)) { return false; } if (sender != null && expected.sender != null && expected.sender.hasParticipant() && sender.getParticipant().get() != expected.sender.getParticipant().get()) { return false; } if (target != null && expected.target != null && expected.target.hasParticipant() && target.getParticipant().get() != expected.target.getParticipant().get()) { return false; } boolean areSignalsEqual; try { areSignalsEqual = BasedOnFields.equal(getWrapped(), expected.getWrapped()); } catch (IllegalAccessException e) { return false; } if (areSignalsEqual) { if (sender != null && expected.sender != null && !expected.sender.hasParticipant() && sender.getParticipantType().equals(expected.sender.getParticipantType())) { expected.sender.bindTo(sender.getParticipant().get()); } if (!expected.target.hasParticipant() && target.getParticipantType().equals(expected.target.getParticipantType())) { expected.target.bindTo(target.getParticipant().get()); } } return areSignalsEqual; }
Source:
public void getSupportedOutputSizes_ImageCapture_withDefaultConfig() { setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); SupportedSurfaceCombination supportedSurfaceCombination = new SupportedSurfaceCombination( mContext, CAMERA_ID, mMockCamcorderProfileHelper); ImageCapture imageCapture = new ImageCapture.Builder().build(); List<Size> resultList = supportedSurfaceCombination.getSupportedOutputSizes(imageCapture); List<Size> expectedList = Arrays.asList(new Size[]{ new Size(4032, 3024), new Size(1920, 1440), new Size(1280, 960), new Size(640, 480), new Size(3840, 2160), new Size(1920, 1080), new Size(1280, 720), new Size(1280, 720), new Size(960, 544), new Size(800, 450) }); assertEquals(expectedList, resultList); }

Target:
public void getSupportedOutputSizes_ImageCapture_withDefaultConfig() { setupCamera(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY); SupportedSurfaceCombination supportedSurfaceCombination = new SupportedSurfaceCombination( mContext, CAMERA_ID, mMockCamcorderProfileHelper); ImageCapture imageCapture = new ImageCapture.Builder().build(); FakeLifecycleOwner fakeLifecycle = new FakeLifecycleOwner(); CameraX.bindToLifecycle(fakeLifecycle, CameraSelector.DEFAULT_BACK_CAMERA, imageCapture); List<Size> resultList = supportedSurfaceCombination.getSupportedOutputSizes(imageCapture); List<Size> expectedList = Arrays.asList(new Size[]{ new Size(4032, 3024), new Size(1920, 1440), new Size(1280, 960), new Size(640, 480), new Size(3840, 2160), new Size(1920, 1080), new Size(1280, 720), new Size(960, 544), new Size(800, 450) }); assertEquals(expectedList, resultList); }
Source:
public EEFSelectLifecycleManager(EEFSelectDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(description, variableManager, interpreter, editingDomain); this.description = description; }

Target:
public EEFSelectLifecycleManager(EEFSelectDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(variableManager, interpreter, editingDomain); this.description = description; }
Source:
ConfigurationParser() throws IOException, SAXException, JAXBException, ParserConfigurationException, TransformerConfigurationException { serviceCreationConfigurationParser = ConfigurationParser.<CacheManagerServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheManagerServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheManagerServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceCreationConfigurationParser::new)); serviceConfigurationParser = ConfigurationParser.<CacheServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceConfigurationParser::new)); resourceConfigurationParser = stream(libraryServiceLoaderFor(CacheResourceConfigurationParser.class)) .flatMap(p -> p.getResourceTypes().stream().map(t -> new AbstractMap.SimpleImmutableEntry<>(t, p))) .collect(collectingAndThen(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a.getClass().isInstance(b) ? b : a), m -> new ResourceConfigurationParser(new HashSet<>(m.values())))); schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream())); documentBuilder = documentBuilder(schema); }

Target:
ConfigurationParser() throws IOException, SAXException, JAXBException, ParserConfigurationException { serviceCreationConfigurationParser = ConfigurationParser.<CacheManagerServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheManagerServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheManagerServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceCreationConfigurationParser::new)); serviceConfigurationParser = ConfigurationParser.<CacheServiceConfigurationParser<?>>stream( libraryServiceLoaderFor(CacheServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceConfigurationParser::new)); resourceConfigurationParser = stream(libraryServiceLoaderFor(CacheResourceConfigurationParser.class)) .flatMap(p -> p.getResourceTypes().stream().map(t -> new AbstractMap.SimpleImmutableEntry<>(t, p))) .collect(collectingAndThen(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a.getClass().isInstance(b) ? b : a), m -> new ResourceConfigurationParser(new HashSet<>(m.values())))); schema = discoverSchema(new StreamSource(CORE_SCHEMA_URL.openStream())); documentBuilder = documentBuilder(schema); }
Source:
public final SPromise toFarRefWithResultPromise(final Object[] args) { Actor owner = EventualMessage.getActorCurrentMessageIsExecutionOn(); SPromise result = SPromise.createPromise(owner, false, false, false); SResolver resolver = SPromise.createResolver(result, "eventualSend:", selector); sendDirectMessage(args, owner, resolver); return result; }

Target:
public final SPromise toFarRefWithResultPromise(final Object[] args) { Actor owner = EventualMessage.getActorCurrentMessageIsExecutionOn(); SPromise result = SPromise.createPromise(owner, promiseResolutionBreakpoint.executeCheckIsSetAndEnabled(), false, false); SResolver resolver = SPromise.createResolver(result); sendDirectMessage(args, owner, resolver); return result; }
Source:
public void hopperOnBrew(InventoryMoveItemEvent e) { if (e.getDestination().getType().equals(InventoryType.BREWING)) { if (isUnallowed(SlimefunItem.getByItem(e.getItem()))) { e.setCancelled(true); } } }

Target:
public void hopperOnBrew(InventoryMoveItemEvent e) { if (e.getDestination().getType() == InventoryType.BREWING && isUnallowed(e.getItem())) { e.setCancelled(true); } }
Source:
public void adminUserCanDeleteBoard() { ForumBoardPage forumBoard = new ForumBoardPage(); first = forumBoard.createNew(User.USER_ADMIN_FORUM); second = forumBoard.createNew(User.USER_ADMIN_FORUM); ForumPage forumMainPage = new ForumPage(); forumMainPage.openForumMainPage(wikiURL); ForumManageBoardsPageObject manageForum = forumMainPage.clickManageBoardsButton(); description = PageContent.FORUM_DESCRIPTION_PREFIX + manageForum.getTimeStamp(); manageForum.verifyForumExists(first, wikiURL); manageForum.verifyForumExists(second, wikiURL); manageForum.deleteForum(second, first); manageForum.verifyForumNotExists(second, wikiURL); }

Target:
public void adminUserCanDeleteBoard() { ForumBoardPage forumBoard = new ForumBoardPage(); first = forumBoard.createNew(User.USER_ADMIN_FORUM); second = forumBoard.createNew(User.USER_ADMIN_FORUM); ForumPage forumMainPage = new ForumPage(); forumMainPage.openForumMainPage(wikiURL); ForumManageBoardsPageObject manageForum = forumMainPage.clickManageBoardsButton(); description = PageContent.FORUM_DESCRIPTION_PREFIX + manageForum.getTimeStamp(); Assert.assertTrue(manageForum.verifyForumExists(first, wikiURL)); Assert.assertTrue(manageForum.verifyForumExists(second, wikiURL)); manageForum.deleteForum(second, first); Assert.assertTrue(manageForum.verifyForumNotExists(second, wikiURL)); }
Source:
public SlidingUpPanelLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (attrs != null) { TypedArray defAttrs = context.obtainStyledAttributes(attrs, ATTRS); if (defAttrs != null) { mIsSlidingUp = defAttrs.getInt(0, Gravity.BOTTOM) == Gravity.BOTTOM; } defAttrs.recycle(); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingUpPanelLayout); if (ta != null) { mPanelHeight = ta.getDimensionPixelSize(R.styleable.SlidingUpPanelLayout_collapsedHeight, -1); mShadowHeight = ta.getDimensionPixelSize(R.styleable.SlidingUpPanelLayout_shadowHeight, -1); mMinFlingVelocity = ta.getInt(R.styleable.SlidingUpPanelLayout_flingVelocity, DEFAULT_MIN_FLING_VELOCITY); mCoveredFadeColor = ta.getColor(R.styleable.SlidingUpPanelLayout_fadeColor, DEFAULT_FADE_COLOR); mDragViewResId = ta.getResourceId(R.styleable.SlidingUpPanelLayout_dragView, -1); } ta.recycle(); } final float density = context.getResources().getDisplayMetrics().density; if (mPanelHeight == -1) { mPanelHeight = (int) (DEFAULT_PANEL_HEIGHT * density + 0.5f); } if (mShadowHeight == -1) { mShadowHeight = (int) (DEFAULT_SHADOW_HEIGHT * density + 0.5f); } setWillNotDraw(false); mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback()); mDragHelper.setMinVelocity(mMinFlingVelocity * density); mCanSlide = true; mIsSlidingEnabled = true; ViewConfiguration vc = ViewConfiguration.get(context); mScrollTouchSlop = vc.getScaledTouchSlop(); }

Target:
public SlidingUpPanelLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (attrs != null) { TypedArray defAttrs = context.obtainStyledAttributes(attrs, DEFAULT_ATTRS); if (defAttrs != null) { int gravity = defAttrs.getInt(0, Gravity.NO_GRAVITY); if (gravity != Gravity.TOP && gravity != Gravity.BOTTOM) { throw new IllegalArgumentException("layout_gravity must be set to either top or bottom"); } mIsSlidingUp = gravity == Gravity.BOTTOM; } defAttrs.recycle(); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingUpPanelLayout); if (ta != null) { mPanelHeight = ta.getDimensionPixelSize(R.styleable.SlidingUpPanelLayout_collapsedHeight, -1); mShadowHeight = ta.getDimensionPixelSize(R.styleable.SlidingUpPanelLayout_shadowHeight, -1); mMinFlingVelocity = ta.getInt(R.styleable.SlidingUpPanelLayout_flingVelocity, DEFAULT_MIN_FLING_VELOCITY); mCoveredFadeColor = ta.getColor(R.styleable.SlidingUpPanelLayout_fadeColor, DEFAULT_FADE_COLOR); mDragViewResId = ta.getResourceId(R.styleable.SlidingUpPanelLayout_dragView, -1); } ta.recycle(); } final float density = context.getResources().getDisplayMetrics().density; if (mPanelHeight == -1) { mPanelHeight = (int) (DEFAULT_PANEL_HEIGHT * density + 0.5f); } if (mShadowHeight == -1) { mShadowHeight = (int) (DEFAULT_SHADOW_HEIGHT * density + 0.5f); } setWillNotDraw(false); mDragHelper = ViewDragHelper.create(this, 0.5f, new DragHelperCallback()); mDragHelper.setMinVelocity(mMinFlingVelocity * density); mCanSlide = true; mIsSlidingEnabled = true; ViewConfiguration vc = ViewConfiguration.get(context); mScrollTouchSlop = vc.getScaledTouchSlop(); }
Source:
public SuccessfulCompilationClause generatesSources(JavaFileObject first, JavaFileObject... rest) { ImmutableList<JavaFileObject> generatedSources = result.generatedSources(); Iterable<? extends CompilationUnitTree> actualCompilationUnits = Compilation.parse(generatedSources); final EqualityScanner scanner = new EqualityScanner(); for (final CompilationUnitTree expected : Compilation.parse(Lists.asList(first, rest))) { Optional<? extends CompilationUnitTree> found = Iterables.tryFind(actualCompilationUnits, new Predicate<CompilationUnitTree>() { @Override public boolean apply(CompilationUnitTree input) { return scanner.visitCompilationUnit(expected, input); } }); if (!found.isPresent()) { ImmutableMap<String, JavaFileObject> p = FluentIterable.from(generatedSources) .uniqueIndex(new Function<JavaFileObject, String>() { @Override @Nullable public String apply(@Nullable JavaFileObject input) { String path = input.toUri().getPath(); return path.substring(StandardLocation.SOURCE_OUTPUT.name().length() + 2); } }); JavaFileObject actual = p.get(expected.getSourceFile().toUri().getPath()); String expectedPath = expected.getSourceFile().getName(); if (actual != null) { CharSequence actualSource = null; try { actualSource = actual.getCharContent(true); } catch (IOException ignored) failureStrategy.fail("Generated file " + expectedPath + " did not match expectation. Found:\n" + (actualSource == null ? "no source found" : actualSource)); } else { failureStrategy.fail("Did not find a source file coresponding to " + expectedPath); } } } return this; }

Target:
public SuccessfulCompilationClause generatesSources(JavaFileObject first, JavaFileObject... rest) { ImmutableList<JavaFileObject> generatedSources = result.generatedSources(); Iterable<? extends CompilationUnitTree> actualCompilationUnits = Compilation.parse(generatedSources); final EqualityScanner scanner = new EqualityScanner(); for (final CompilationUnitTree expectedTree : Compilation.parse(Lists.asList(first, rest))) { Optional<? extends CompilationUnitTree> found = Iterables.tryFind(actualCompilationUnits, new Predicate<CompilationUnitTree>() { @Override public boolean apply(CompilationUnitTree actualTree) { return scanner.visitCompilationUnit(expectedTree, actualTree); } }); if (!found.isPresent()) { final JavaFileObject expected = expectedTree.getSourceFile(); Optional<JavaFileObject> actual = FluentIterable.from(generatedSources).firstMatch(new Predicate<JavaFileObject>() { @Override public boolean apply(JavaFileObject generatedFile) { return generatedFile.toUri().getPath().endsWith(expected.toUri().getPath()); } }); if (actual.isPresent()) { CharSequence actualSource = null; try { actualSource = actual.get().getCharContent(false); } catch (IOException e) { throw new RuntimeException("Exception reading source content.", e); } failureStrategy.fail("Generated file " + expected.getName() + " did not match expectation. Found:\n" + (actualSource == null ? "no source found" : actualSource)); } else { failureStrategy.fail("Did not find a source file named " + expected.getName()); } } } return this; }
Source:
public static Literal toLiteral(Object value) { if (value instanceof Boolean) { return new BooleanLiteral(((Boolean) value).booleanValue()); } else if (value instanceof Calendar) { return new DateLiteral(toZonedDateTime((Calendar) value)); } else if (value instanceof Date) { return new DateLiteral(toZonedDateTime((Date) value)); } else if (value instanceof Temporal) { return new DateLiteral(ZonedDateTime.from((Temporal) value)); } else if (value instanceof ZonedDateTime) { return new DateLiteral((ZonedDateTime) value); } else if (value instanceof Double) { return new DoubleLiteral((Double) value); } else if (value instanceof Float) { return new DoubleLiteral((Float) value); } else if (value instanceof Integer) { return new IntegerLiteral((Integer) value); } else if (value instanceof Long) { return new IntegerLiteral((Long) value); } else if (value instanceof String) { return new StringLiteral((String) value); } throw new NuxeoException("Unknown type to convert to literal, value=" + value); }

Target:
public static Literal toLiteral(Object value) { if (value instanceof Boolean) { return new BooleanLiteral(((Boolean) value).booleanValue()); } else if (value instanceof Calendar) { return new DateLiteral(toZonedDateTime((Calendar) value)); } else if (value instanceof Date) { return new DateLiteral(toZonedDateTime((Date) value)); } else if (value instanceof ZonedDateTime) { return new DateLiteral((ZonedDateTime) value); } else if (value instanceof Temporal) { return new DateLiteral(ZonedDateTime.from((Temporal) value)); } else if (value instanceof Double) { return new DoubleLiteral((Double) value); } else if (value instanceof Float) { return new DoubleLiteral((Float) value); } else if (value instanceof Integer) { return new IntegerLiteral((Integer) value); } else if (value instanceof Long) { return new IntegerLiteral((Long) value); } else if (value instanceof String) { return new StringLiteral((String) value); } throw new NuxeoException("Unknown type to convert to literal, value=" + value); }
Source:
public TableRegistry(CorfuRuntime runtime) { this.runtime = runtime; this.classMap = new ConcurrentHashMap<>(); this.tableMap = new ConcurrentHashMap<>(); this.protobufSerializer = new ProtobufSerializer((byte) 25, classMap); Serializers.registerSerializer(this.protobufSerializer); this.registryTable = this.runtime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<TableName, CorfuRecord<TableDescriptors, Message>>>() { }) .setStreamName(getFullyQualifiedTableName(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME)) .setSerializer(this.protobufSerializer) .open(); addTypeToClassMap(TableName.getDefaultInstance()); addTypeToClassMap(TableDescriptors.getDefaultInstance()); registerTable(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME, TableName.getDescriptor().toProto(), TableDescriptors.getDescriptor().toProto()); }

Target:
public TableRegistry(CorfuRuntime runtime) { this.runtime = runtime; this.classMap = new ConcurrentHashMap<>(); this.tableMap = new ConcurrentHashMap<>(); this.protobufSerializer = new ProtobufSerializer(PROTOBUF_SERIALIZER_CODE, classMap); Serializers.registerSerializer(this.protobufSerializer); this.registryTable = this.runtime.getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<TableName, CorfuRecord<TableDescriptors, Message>>>() { }) .setStreamName(getFullyQualifiedTableName(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME)) .setSerializer(this.protobufSerializer) .open(); addTypeToClassMap(TableName.getDefaultInstance()); addTypeToClassMap(TableDescriptors.getDefaultInstance()); try { registerTable(CORFU_SYSTEM_NAMESPACE, REGISTRY_TABLE_NAME, TableName.class, TableDescriptors.class, null); } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
public PsAll(final List<Pass> pass, final int identity) { super(); this.all = pass; this.index = identity; }

Target:
public PsAll(final List<Pass> pass, final int identity) { this.all = pass; this.index = identity; }
Source:
private void markExpiredCommandsAsFailure() { long maxTime = DateTime.getNow() .addMinutes((-1) * Config.<Integer>getValue(ConfigValues.CoCoCommandLifeInMinutes)).getTime(); Iterator<Entry<Guid, CommandContainer>> iterator = cmdCallbackMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<Guid, CommandContainer> entry = iterator.next(); List<Guid> childCmdIds = coco.getChildCommandIds(entry.getKey()); if (childCmdIds.isEmpty()) { markExpiredCommandAsFailure(entry.getKey(), maxTime); } else { for (Guid childId : childCmdIds) { markExpiredCommandAsFailure(childId, maxTime); } } } }

Target:
private void markExpiredCommandsAsFailure() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, (-1) * Config.<Integer>getValue(ConfigValues.CoCoCommandLifeInMinutes)); long maxTime = cal.getTime().getTime(); for (Entry<Guid, CommandContainer> entry : cmdCallbackMap.entrySet()) { List<Guid> childCmdIds = coco.getChildCommandIds(entry.getKey()); if (childCmdIds.isEmpty()) { markExpiredCommandAsFailure(entry.getKey(), maxTime); } else { for (Guid childId : childCmdIds) { markExpiredCommandAsFailure(childId, maxTime); } } } }
Source:
public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? AuditLogType.NETWORK_UPDATE_NETWORK : AuditLogType.NETWORK_UPDATE_NETWORK_FAILED; }

Target:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: return getSucceeded() ? AuditLogType.NETWORK_UPDATE_NETWORK_STARTED : AuditLogType.NETWORK_UPDATE_NETWORK_FAILED; case END_FAILURE: return hasChildCommands() ? AuditLogType.UPDATE_NETWORK_ON_HOSTS_FAILED : super.getAuditLogTypeValue(); case END_SUCCESS: return AuditLogType.NETWORK_UPDATE_NETWORK_FINISHED; } return super.getAuditLogTypeValue(); }
Source:
private List<QueryStateInfo> getAggregatedRunningQueriesInfo() { synchronized (root) { if (!subGroups.isEmpty()) { return subGroups.values().stream() .map(InternalResourceGroup::getAggregatedRunningQueriesInfo) .flatMap(List::stream) .collect(toImmutableList()); } List<ResourceGroupInfo> pathToRoot = getPathToRoot(); return runningQueries.stream() .map(QueryExecution::getQueryInfo) .map(queryInfo -> createQueryStateInfo(queryInfo, Optional.of(id), Optional.of(pathToRoot))) .collect(toImmutableList()); } }

Target:
private List<QueryStateInfo> getAggregatedRunningQueriesInfo() { synchronized (root) { if (subGroups.isEmpty()) { List<ResourceGroupInfo> pathToRoot = getPathToRoot(); return runningQueries.stream() .map(QueryExecution::getQueryInfo) .map(queryInfo -> createQueryStateInfo(queryInfo, Optional.of(id), Optional.of(pathToRoot))) .collect(toImmutableList()); } return subGroups.values().stream() .map(InternalResourceGroup::getAggregatedRunningQueriesInfo) .flatMap(List::stream) .collect(toImmutableList()); } }
Source:
public void setUidHash(String uidHash) { throw new UnsupportedOperationException("Do not support set UidHash for SinkTransformation."); }

Target:
public void setUidHash(String uidHash) { throw new UnsupportedOperationException("Setting a UidHash is not supported for SinkTransformation."); }
Source:
private static void saveMetacards(CatalogFramework framework, List<Metacard> metacards) { Subject userSubject = SECURITY.getSubject("dummyUser", "dummyPassword"); userSubject.execute( () -> { try { framework.create(new CreateRequestImpl(metacards)).getCreatedMetacards(); } catch (IngestException e) { LOGGER.warn("Unable to create metacard under this user", e); } catch (SourceUnavailableException e) { LOGGER.warn("Unable to create metacard under this user", e); } }); }

Target:
private static void saveMetacards(CatalogFramework framework, List<Metacard> metacards) { SECURITY.runAsAdmin( () -> { try { return SECURITY.runWithSubjectOrElevate( () -> framework.create(new CreateRequestImpl(metacards)).getCreatedMetacards()); } catch (SecurityServiceException | InvocationTargetException e) { LOGGER.warn( "Can't create metacard for system search template, was unable to elevate privileges", e); } return null; }); }
Source:
static public void main(String[] args) throws IOException { if (args.length < 3) { System.err.println("This executable requires four arguments:\n" + " OntonotesTreebankReader <OntoNotes Directory> <language> <output_directory>"); System.exit(-1); } String topdir = args[0]; String outputdir = args[2]; OntonotesNamedEntityReader otr = new OntonotesNamedEntityReader(topdir, args[1]); int count = 0; final boolean producejson = false; while (otr.hasNext()) { XmlTextAnnotation xta = otr.next(); String path = otr.currentfile; if (producejson) { try { String json = SerializationHelper.serializeToJson(xta.getTextAnnotation()); String outfile = otr.currentfile.replace(topdir, args[2]); File outputfile = new File(outfile); outputfile.getParentFile().mkdirs(); try (PrintWriter out = new PrintWriter(outputfile)) { out.print(json); } } catch (Throwable t) { System.out.println(otr.currentfile+" produced the incorrect offset."); } } else { TextAnnotation ta = xta.getTextAnnotation(); path = outputdir+path.substring(topdir.length()); path += ".conll"; System.out.println(count+":"+path); CoNLL2002Writer.writeViewInCoNLL2003Format(ta.getView(ViewNames.NER_ONTONOTES), ta, path); } count++; if ((count % 10) == 0) System.out.println("Completed "+count+" of "+otr.filelist.size()); } System.out.println("Processed a total of "+count+" of "+otr.filelist.size()+" treebanks."); }

Target:
static public void main(String[] args) throws IOException { if (args.length < 3) { System.err.println("This executable requires three arguments:\n" + " OntonotesTreebankReader <OntoNotes Directory> <language> <output_directory>"); System.exit(-1); } String topdir = args[0]; String outputdir = args[2]; OntonotesNamedEntityReader otr = new OntonotesNamedEntityReader(topdir, args[1]); int count = 0; final boolean producejson = false; while (otr.hasNext()) { XmlTextAnnotation xta = otr.next(); String path = otr.currentfile; if (producejson) { try { String json = SerializationHelper.serializeToJson(xta.getTextAnnotation()); String outfile = otr.currentfile.replace(topdir, args[2]); File outputfile = new File(outfile); outputfile.getParentFile().mkdirs(); try (PrintWriter out = new PrintWriter(outputfile)) { out.print(json); } } catch (Throwable t) { System.out.println(otr.currentfile+" produced the incorrect offset."); } } else { TextAnnotation ta = xta.getTextAnnotation(); path = outputdir+path.substring(topdir.length()); path += ".conll"; System.out.println(count+":"+path); CoNLL2002Writer.writeViewInCoNLL2003Format(ta.getView(ViewNames.NER_ONTONOTES), ta, path); } count++; if ((count % 10) == 0) System.out.println("Completed "+count+" of "+otr.filelist.size()); } System.out.println(otr.generateReport()); }
Source:
public String getFullRequestURL() { final PublicAddress publicAddress = context.get(PublicAddress.class); return publicAddress.getAddress(context).toString() + context.getRequest().getUri(); }

Target:
public String getFullRequestURL() { return getAddress().toString() + context.getRequest().getUri(); }
Source:
protected void executeCommand() { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Locked, getCompensationContext()); if (shouldPerformOvfUpdate()) { runInternalAction(VdcActionType.ProcessOvfUpdateForStoragePool, new StoragePoolParametersBase(getStoragePoolId()), null); if (ovfOnAnyDomainSupported()) { VdcReturnValueBase tmpRetValue = runInternalActionWithTasksContext(VdcActionType.ProcessOvfUpdateForStorageDomain, createProcessOvfUpdateForDomainParams(), null); getReturnValue().getVdsmTaskIdList().addAll(tmpRetValue.getInternalVdsmTaskIdList()); } } if (getReturnValue().getVdsmTaskIdList().isEmpty()) { setSucceeded(executeDeactivateCommand(true)); } else { setCommandShouldBeLogged(false); setSucceeded(true); } }

Target:
protected void executeCommand() { StoragePoolIsoMap map = loadStoragePoolIsoMap(); changeDomainStatusWithCompensation(map, StorageDomainStatus.Unknown, StorageDomainStatus.Locked, getCompensationContext()); if (shouldPerformOvfUpdate()) { StoragePoolParametersBase parameters = new StoragePoolParametersBase(getStoragePoolId()); parameters.setShouldOnlyUpdateDB(true); runInternalAction(VdcActionType.ProcessOvfUpdateForStoragePool, parameters, null); if (ovfOnAnyDomainSupported()) { VdcReturnValueBase tmpRetValue = runInternalActionWithTasksContext(VdcActionType.ProcessOvfUpdateForStorageDomain, createProcessOvfUpdateForDomainParams(), null); getReturnValue().getVdsmTaskIdList().addAll(tmpRetValue.getInternalVdsmTaskIdList()); } } if (getReturnValue().getVdsmTaskIdList().isEmpty()) { setSucceeded(executeDeactivateCommand(true)); } else { setCommandShouldBeLogged(false); setSucceeded(true); } }
Source:
public static void main(String[] args) throws Exception { CommandLine cmdLine = new CommandLine(); Config config = cmdLine.loadConfig(cmdLine.parser().parse(args)); ApplicationRunner standaloneEnv = ApplicationRunner.getLocalRunner(config); standaloneEnv.run(new KeyValueStoreExample(), config); }

Target:
public static void main(String[] args) throws Exception { CommandLine cmdLine = new CommandLine(); Config config = cmdLine.loadConfig(cmdLine.parser().parse(args)); ApplicationRunner localRunner = ApplicationRunner.getLocalRunner(config); localRunner.run(new KeyValueStoreExample(), config); }
Source:
public static String toPath(String path) { String workDir = DfBuildProperties.getInstance().getWorkDir(); try { return new File(workDir, path).getCanonicalPath(); } catch (IOException e) { String msg = "Failed to derived path. workDir=" + workDir + ", path=" + path; throw new IllegalStateException(msg, e); } }

Target:
public static String toPath(String path) { String workDir = DfBuildProperties.getInstance().getWorkDir(); if (workDir == null || new File(path).isAbsolute()) { return path; } try { return new File(workDir, path).getCanonicalPath(); } catch (IOException e) { String msg = "Failed to derived path. workDir=" + workDir + ", path=" + path; throw new IllegalStateException(msg, e); } }
Source:
public void getPostsOfUserShouldReturnEmptyPageInNoBranchesAllowed() { String page = "1"; long branchId = 1L; int pageSize = 50; Branch branch = new Branch("branch",""); branch.setId(branchId); Topic topic = new Topic(); topic.setBranch(branch); Post post = new Post(user, ""); post.setTopic(topic); List<Post> posts = Arrays.asList(post); Page<Post> postsOfUser = new PageImpl<>(posts); when(postDao.getUserPosts(Matchers.<JCUser>any(), Matchers.<PageRequest>any(), Matchers.anyList())) .thenReturn(postsOfUser); when(topicDao.getAllowedBranchesIds(Matchers.<JCUser>any())).thenReturn(Collections.EMPTY_LIST); currentUser.setPageSize(pageSize); Page<Post> actualPostsPage = postService.getPostsOfUser(user, page); assertEquals(actualPostsPage.getSize(), 0); }

Target:
public void getPostsOfUserShouldReturnEmptyPageInNoBranchesAllowed() { when(postDao.getUserPosts(Matchers.<JCUser>any(), Matchers.<PageRequest>any(), Matchers.anyList())) .thenReturn(getPageWithPost()); when(topicDao.getAllowedBranchesIds(Matchers.<JCUser>any())).thenReturn(Collections.EMPTY_LIST); currentUser.setPageSize(50); Page<Post> actualPostsPage = postService.getPostsOfUser(user, "1"); assertEquals(actualPostsPage.getSize(), 0); }
Source:
private static boolean isSameVariables(DetailAST ast1, DetailAST ast2) { final DetailAST classOrMethodOfAst1 = findClassOrConstructorOrMethodInWhichItIsDefined(ast1); final DetailAST classOrMethodOfAst2 = findClassOrConstructorOrMethodInWhichItIsDefined(ast2); return classOrMethodOfAst1 == classOrMethodOfAst2; }

Target:
private static boolean isSameVariables(DetailAST ast1, DetailAST ast2) { final DetailAST classOrMethodOfAst1 = findFirstUpperNamedBlock(ast1); final DetailAST classOrMethodOfAst2 = findFirstUpperNamedBlock(ast2); return classOrMethodOfAst1 == classOrMethodOfAst2; }
Source:
public String[] getGroupAdd() { return groupAdd; }

Target:
public List<String> getGroupAdd() { return groupAdd; }
Source:
public AddressMessage(NetworkParameters params, final PeerAddress addr){ super(params); addresses = new LinkedList<PeerAddress>(){{ add(addr); }}; }

Target:
public AddressMessage(NetworkParameters params, final PeerAddress addr){ super(params); addresses = Collections.singletonList(addr); }
Source:
public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { if (!(newInput instanceof List)) { return; } List<?> list = (List<?>) newInput; if (list.isEmpty()) { return; } final ITmfTrace trace = getTrace(); if (trace == null) { return; } fSyncLock.lock(); BuildThread buildThread = fBuildThread; if (buildThread != null) { buildThread.cancel(); } buildThread = new BuildThread(trace); buildThread.start(); fBuildThread = buildThread; fSyncLock.unlock(); }

Target:
public void inputChanged(@Nullable Viewer viewer, @Nullable Object oldInput, @Nullable Object newInput) { if (!(newInput instanceof List)) { return; } List<?> list = (List<?>) newInput; if (list.isEmpty()) { return; } final ITmfTrace trace = getTrace(); if (trace == null) { return; } fSyncLock.lock(); try { BuildThread buildThread = fBuildThread; if (buildThread != null) { buildThread.cancel(); } buildThread = new BuildThread(trace); buildThread.start(); fBuildThread = buildThread; } finally { fSyncLock.unlock(); } }
Source:
public DirContext getContext() throws UserStoreException { DirContext context = null; if (dcMap == null) { try { context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection.Trying again to get connection... ", e); try { context = new InitialDirContext(environment); } catch (Exception e1) { throw new UserStoreException("Error obtaining connection. " + e.getMessage(), e); } } } else if (dcMap != null && dcMap.size() != 0) { try { Integer firstKey = dcMap.firstKey(); SRVRecord firstRecord = dcMap.get(firstKey); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord)); context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection to first Domain Controller.Trying to connect with other Domain" + " Controllers...", e); for (Integer integer : dcMap.keySet()) { try { SRVRecord srv = dcMap.get(integer); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv)); context = new InitialDirContext(environment); break; } catch (NamingException e1) { if(integer == (dcMap.lastKey())){ throw new UserStoreException("Error obtaining connection for all " + integer + " Domain Controllers.", e); } } } } } return (context); }

Target:
public DirContext getContext() throws UserStoreException { DirContext context = null; if (dcMap == null) { try { context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection.Trying again to get connection... ", e); try { context = new InitialDirContext(environment); } catch (Exception e1) { String errorMessage = "Error obtaining connection."; if (log.isDebugEnabled()) { log.debug(errorMessage, e1); } throw new UserStoreException(errorMessage, e); } } } else if (dcMap != null && dcMap.size() != 0) { try { Integer firstKey = dcMap.firstKey(); SRVRecord firstRecord = dcMap.get(firstKey); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord)); context = new InitialDirContext(environment); } catch (NamingException e) { log.error("Error obtaining connection to first Domain Controller.Trying to connect with other Domain" + " Controllers...", e); for (Integer integer : dcMap.keySet()) { try { SRVRecord srv = dcMap.get(integer); environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv)); context = new InitialDirContext(environment); break; } catch (NamingException e1) { if(integer == (dcMap.lastKey())){ String errorMessage = "Error obtaining connection for all " + integer + " Domain Controllers."; if (log.isDebugEnabled()) { log.debug(errorMessage, e1); } throw new UserStoreException(errorMessage, e1); } } } } } return (context); }