auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static AlertDialog show(Context context, FormController formController, Listener listener) { String title; { title = (formController == null) ? null : formController.getFormTitle(); if (title == null) { title = context.getString(R.string.no_form_loaded); } } List<IconMenuItem> items; if ((boolean) AdminSharedPreferences.getInstance().get(AdminKeys.KEY_SAVE_MID)) { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_save, R.string.keep_changes), new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } else { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } ListView listView = DialogUtils.createActionListView(context); final IconMenuListAdapter adapter = new IconMenuListAdapter(context, items); listView.setAdapter(adapter); listView.setOnItemClickListener((parent, view, position, id) -> { IconMenuItem item = (IconMenuItem) adapter.getItem(position); if (item.getTextResId() == R.string.keep_changes) { listener.onSaveChangedClicked(); } else { listener.onIgnoreChangesClicked(); } }); AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle( context.getString(R.string.quit_application, title)) .setPositiveButton(context.getString(R.string.do_not_exit), (dialog, id) -> { dialog.cancel(); }) .setView(listView) .create(); alertDialog.show(); return alertDialog; }

Target:
public static AlertDialog show(Context context, FormController formController, Listener listener) { String title = (formController == null) ? null : formController.getFormTitle(); if (title == null) { title = context.getString(R.string.no_form_loaded); } List<IconMenuItem> items; if ((boolean) AdminSharedPreferences.getInstance().get(AdminKeys.KEY_SAVE_MID)) { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_save, R.string.keep_changes), new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } else { items = ImmutableList.of(new IconMenuItem(R.drawable.ic_delete, R.string.do_not_save)); } ListView listView = DialogUtils.createActionListView(context); final IconMenuListAdapter adapter = new IconMenuListAdapter(context, items); listView.setAdapter(adapter); listView.setOnItemClickListener((parent, view, position, id) -> { IconMenuItem item = (IconMenuItem) adapter.getItem(position); if (item.getTextResId() == R.string.keep_changes) { listener.onSaveChangedClicked(); } else { listener.onIgnoreChangesClicked(); } }); AlertDialog alertDialog = new AlertDialog.Builder(context) .setTitle( context.getString(R.string.quit_application, title)) .setPositiveButton(context.getString(R.string.do_not_exit), (dialog, id) -> { dialog.cancel(); }) .setView(listView) .create(); alertDialog.show(); return alertDialog; }
Source:
public void abortReceived(ChannelHandlerContext ctx, MessageEvent evt) throws Exception { AbortMessage abort = (AbortMessage) evt.getMessage(); if (logger.isInfoEnabled()) { logger.debug("Aborting script " + abort.getName()); } if (robot == null || (robot.getScriptCompleteFuture().isDone() && time.containsKey(abort.getName()) && (System .currentTimeMillis() - ((Date) time.get(abort.getName())).getTime()) > 500)) { time.remove(abort.getName()); sendBadRequestMessage(ctx, "The script cannot be aborted from the current state", abort.getName()); } else { robot.abort(); FinishedMessage finished = new FinishedMessage(); finished.setName(abort.getName()); finished.setExpectedScript(robot.getScriptCompleteFuture().getExpectedScript()); finished.setObservedScript(robot.getScriptCompleteFuture().getObservedScript()); Channels.write(ctx, Channels.future(null), finished); FinishMessage finish = new FinishMessage(); finish.setName(abort.getName()); Channels.write(ctx, Channels.future(null), finish); } }

Target:
public void abortReceived(ChannelHandlerContext ctx, MessageEvent evt) throws Exception { AbortMessage abort = (AbortMessage) evt.getMessage(); if (logger.isInfoEnabled()) { logger.debug("Aborting script " + abort.getName()); } robot.abort(); if (robot != null && robot.getScriptCompleteFuture().isDone()) { FinishedMessage finished = new FinishedMessage(); finished.setName(abort.getName()); finished.setExpectedScript(robot.getScriptCompleteFuture().getExpectedScript()); finished.setObservedScript(robot.getScriptCompleteFuture().getObservedScript()); Channels.write(ctx, Channels.future(null), finished); } }
Source:
public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { IDomain domain; domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; }

Target:
public static IDomain getFirstDomainOrCreate(IUser user) throws OpenShiftException { IDomain domain = null; domain = getFirstDomain(user); if (domain == null) { domain = user.createDomain(createRandomName()); } return domain; }
Source:
private void getOptimizedRoute(@NonNull final Style style, List<Point> coordinates) { optimizedClient = MapboxOptimization.builder() .source(FIRST) .destination(ANY) .coordinates(coordinates) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .accessToken(Mapbox.getAccessToken()) .build(); optimizedClient.enqueueCall(new Callback<OptimizationResponse>() { @Override public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) { if (!response.isSuccessful()) { Timber.d(getString(R.string.no_success)); Toast.makeText(OptimizationActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show(); } else { if (response.body() != null) { List<DirectionsRoute> routes = response.body().trips(); if (routes != null) { if (routes.isEmpty()) { Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), routes.size()); Toast.makeText(OptimizationActivity.this, R.string.successful_but_no_routes, Toast.LENGTH_SHORT).show(); } else { optimizedRoute = routes.get(0); drawOptimizedRoute(style, optimizedRoute); } } } } } @Override public void onFailure(Call<OptimizationResponse> call, Throwable throwable) { Timber.d("Error: %s", throwable.getMessage()); } }); }

Target:
private void getOptimizedRoute(@NonNull final Style style, List<Point> coordinates) { optimizedClient = MapboxOptimization.builder() .source(FIRST) .destination(ANY) .coordinates(coordinates) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_DRIVING) .accessToken(Mapbox.getAccessToken()) .build(); optimizedClient.enqueueCall(new Callback<OptimizationResponse>() { @Override public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) { if (!response.isSuccessful()) { Timber.d(getString(R.string.no_success)); Toast.makeText(OptimizationActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show(); } else { if (response.body() != null) { List<DirectionsRoute> routes = response.body().trips(); if (routes != null) { if (routes.isEmpty()) { Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), routes.size()); Toast.makeText(OptimizationActivity.this, R.string.successful_but_no_routes, Toast.LENGTH_SHORT).show(); } else { optimizedRoute = routes.get(0); drawOptimizedRoute(style, optimizedRoute); } } else { Timber.d("list of routes in the response is null"); Toast.makeText(OptimizationActivity.this, String.format(getString(R.string.null_in_response), "The Optimization API response's list of routes"), Toast.LENGTH_SHORT).show(); } } else { Timber.d("response.body() is null"); Toast.makeText(OptimizationActivity.this, String.format(getString(R.string.null_in_response), "The Optimization API response's body"), Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call<OptimizationResponse> call, Throwable throwable) { Timber.d("Error: %s", throwable.getMessage()); } }); }
Source:
private void doDisposeHandler(final ThingHandler thingHandler) { logger.debug("Calling dispose handler for thing '{}' at '{}'.", thingHandler.getThing().getUID(), thingHandler); try { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.dispose(); return null; } }); } catch (TimeoutException ex) { logger.warn("Disposing handler for thing '{}' takes more than {}ms.", thingHandler.getThing().getUID(), SafeMethodCaller.DEFAULT_TIMEOUT); } catch (Exception ex) { logger.error("Exception occured while disposing handler of thing '" + thingHandler.getThing().getUID() + "': " + ex.getMessage(), ex); } }

Target:
private void doDisposeHandler(final ThingHandler thingHandler) { logger.debug("Calling dispose handler for thing '{}' at '{}'.", thingHandler.getThing().getUID(), thingHandler); try { SafeMethodCaller.call(new SafeMethodCaller.ActionWithException<Void>() { @Override public Void call() throws Exception { thingHandler.dispose(); return null; } }); } catch (TimeoutException ex) { logger.warn("Disposing handler for thing '{}' takes more than {}ms.", thingHandler.getThing().getUID(), SafeMethodCaller.DEFAULT_TIMEOUT); } catch (Exception e) { logger.error("Exception occured while disposing handler of thing '{}': {}", thingHandler.getThing().getUID(), e.getMessage(), e); } }
Source:
public List<TmfTraceAnalysis> getAvailableAnalysis() { List<TmfTraceAnalysis> list = new ArrayList<TmfTraceAnalysis>(); TraceTypeHelper helper = TmfTraceType.getInstance().getTraceType(getTraceType()); if (helper == null) { return list; } for (IAnalysisModule module : TmfAnalysisManager.getAnalysisModules(helper.getTraceClass()).values()) { if (fResource instanceof IFolder) { IFolder folder = (IFolder) fResource; IPath path = folder.getFullPath().append(module.getId()); IFolder newresource = ResourcesPlugin.getWorkspace().getRoot().getFolder(path); if (!newresource.exists()) { try { newresource.create(true, true, null); } catch (CoreException e) { e.printStackTrace(); } } TmfTraceAnalysis analysis = new TmfTraceAnalysis(module.getName(), newresource, this, module.getId(), module); list.add(analysis); } } return list; }

Target:
public List<TmfAnalysisElement> getAvailableAnalysis() { List<TmfAnalysisElement> list = new ArrayList<TmfAnalysisElement>(); TraceTypeHelper helper = TmfTraceType.getInstance().getTraceType(getTraceType()); Class<? extends ITmfTrace> traceClass = null; if (helper == null && fTraceTypeId != null) { if (fTraceTypeId.startsWith(CustomTxtTrace.class.getCanonicalName())) { for (CustomTxtTraceDefinition def : CustomTxtTraceDefinition.loadAll()) { if (fTraceTypeId.equals(CustomTxtTrace.class.getCanonicalName() + ":" + def.definitionName)) { traceClass = CustomTxtTrace.class; } } } if (fTraceTypeId.startsWith(CustomXmlTrace.class.getCanonicalName())) { for (CustomXmlTraceDefinition def : CustomXmlTraceDefinition.loadAll()) { if (fTraceTypeId.equals(CustomXmlTrace.class.getCanonicalName() + ":" + def.definitionName)) { traceClass = CustomTxtTrace.class; } } } } else if (helper != null) { traceClass = helper.getTraceClass(); } if (traceClass == null) { return list; } IPath path = getProject().getTracesFolder().getPath(); if (fResource instanceof IFolder) { IFolder folder = (IFolder) fResource; path = folder.getFullPath(); } else if (fResource instanceof IFile) { IFile file = (IFile) fResource; path = path.append(file.getName()); } for (IAnalysisModule module : TmfAnalysisManager.getAnalysisModules(traceClass).values()) { IFolder newresource = ResourcesPlugin.getWorkspace().getRoot().getFolder(path.append(module.getId())); TmfAnalysisElement analysis = new TmfAnalysisElement(module.getName(), newresource, this, module.getId(), module); list.add(analysis); } return list; }
Source:
public synchronized String getScheme() { return isRunning() ? !this.ssl ? "http" : "https" : null; }

Target:
public synchronized String getScheme() { return isRunning() ? this.useSsl ? "https" : "http" : null; }
Source:
void should_be_injected_correct_instance_of_mock() { assertThat(classWithDependency.dependency).isEqualTo(rootMock); }

Target:
void should_be_injected_correct_instance_of_mock() { assertThat(classWithDependency.dependency).isSameAs(rootMock); }
Source:
<T> Iterator<T> asIterator(final String _tailApiUrl, final Class<T> type) { method("GET"); final StringBuilder strBuilder = new StringBuilder(_tailApiUrl); if (!args.isEmpty()) { boolean first=true; try { for (Entry a : args) { strBuilder.append(first ? '?' : '&'); first = false; strBuilder.append(URLEncoder.encode(a.key, "UTF-8")); strBuilder.append('='); strBuilder.append(URLEncoder.encode(a.value.toString(), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } final String tailApiUrl = _tailApiUrl; return new Iterator<T>() { T next; URL url; { try { url = root.getApiURL(tailApiUrl); } catch (IOException e) { throw new Error(e); } } public boolean hasNext() { fetch(); return next!=null; } public T next() { fetch(); T r = next; if (r==null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next!=null) return; if (url==null) return; try { while (true) { setupConnection(url); try { next = parse(type,null); assert next!=null; findNextURL(); return; } catch (IOException e) { handleApiError(e); } } } catch (IOException e) { throw new Error(e); } } private void findNextURL() throws MalformedURLException { url = null; String link = uc.getHeaderField("Link"); if (link==null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { int idx = token.indexOf('>'); url = new URL(token.substring(1,idx)); return; } } } }; }

Target:
<T> Iterator<T> asIterator(final String _tailApiUrl, final Class<T> type) { method("GET"); final StringBuilder strBuilder = new StringBuilder(_tailApiUrl); if (!args.isEmpty()) { boolean first=true; try { for (Entry a : args) { strBuilder.append(first ? '?' : '&'); first = false; strBuilder.append(URLEncoder.encode(a.key, "UTF-8")); strBuilder.append('='); strBuilder.append(URLEncoder.encode(a.value.toString(), "UTF-8")); } } catch (UnsupportedEncodingException e) { throw new AssertionError(e); } } final String tailApiUrl = strBuilder.toString(); return new Iterator<T>() { T next; URL url; { try { url = root.getApiURL(tailApiUrl); } catch (IOException e) { throw new Error(e); } } public boolean hasNext() { fetch(); return next!=null; } public T next() { fetch(); T r = next; if (r==null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next!=null) return; if (url==null) return; try { while (true) { setupConnection(url); try { next = parse(type,null); assert next!=null; findNextURL(); return; } catch (IOException e) { handleApiError(e); } } } catch (IOException e) { throw new Error(e); } } private void findNextURL() throws MalformedURLException { url = null; String link = uc.getHeaderField("Link"); if (link==null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { int idx = token.indexOf('>'); url = new URL(token.substring(1,idx)); return; } } } }; }
Source:
public void reset() { colorChangeBitSet = false; firstPoint = false; header.reset(); }

Target:
public void reset() { colorChangeBitSet = false; points.clear(); header.reset(); }
Source:
private Optional<Contentlet> findUrlContentlet(final HttpServletRequest request) throws DotDataException, DotSecurityException { Contentlet contentlet = null; if (request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE) != null) { final String inode = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE); contentlet = this.contentletAPI.find(inode, user, false); } else if (null != request.getAttribute(WebKeys.WIKI_CONTENTLET)) { final String id = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET); contentlet = this.contentletAPI.findContentletByIdentifierAnyLanguage(id); } return Optional.ofNullable(contentlet); }

Target:
private Optional<Contentlet> findUrlContentlet(final HttpServletRequest request) throws DotDataException, DotSecurityException { Contentlet contentlet = null; if (null != request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE)) { final String inode = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE); contentlet = this.contentletAPI.find(inode, user, false); } else if (null != request.getAttribute(WebKeys.WIKI_CONTENTLET)) { final String id = (String)request.getAttribute(WebKeys.WIKI_CONTENTLET); contentlet = this.contentletAPI.findContentletByIdentifierAnyLanguage(id); } return Optional.ofNullable(contentlet); }
Source:
public Label getToolchainLabel() { if (useRemoteJavaToolchain) { return Label.parseAbsoluteUnchecked("@bazel_tools } return toolchainLabel; }

Target:
public Label getToolchainLabel() { return toolchainLabel; }
Source:
public void handleConfigurationUpdate(Map<String, Object> configurationParameters) { validateConfigurationParameters(configurationParameters); Configuration configuration = editConfiguration(); for (Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) { configuration.put(configurationParmeter.getKey(), configurationParmeter.getValue()); } if (ThingHandlerHelper.isHandlerInitialized(this)) { dispose(); updateConfiguration(configuration); initialize(); } else { updateConfiguration(configuration); callback.configurationUpdated(getThing()); } }

Target:
public void handleConfigurationUpdate(Map<String, Object> configurationParameters) { validateConfigurationParameters(configurationParameters); Configuration configuration = editConfiguration(); for (Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) { configuration.put(configurationParmeter.getKey(), configurationParmeter.getValue()); } if (isInitialized()) { dispose(); updateConfiguration(configuration); initialize(); } else { updateConfiguration(configuration); callback.configurationUpdated(getThing()); } }
Source:
public void testInvokeSLSBthoughSingleton() { String echo = "this it testing string"; String sss = ""; try { sss = testSingleton.test(echo); } catch (Exception ee) { Assert.fail("It is not possible to invoke SLSB through singleton, when ClientInterceptor is registered via META-INF/services"); } Assert.assertTrue("SLSB returned wrong value through singleton", sss.equals(echo)); }

Target:
public void testInvokeSLSBthoughSingleton() throws Exception { String echo = "this it testing string"; String result = testSingleton.test(echo); Assert.assertTrue("SLSB returned wrong value through singleton", result.equals(clientInterceptorPrefix + echo)); }
Source:
public void finish() { String shelltext = getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsActive(shelltext)); }

Target:
public void finish() { new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(this)); }
Source:
protected void onPinnedEndpointsChangedEvent( JSONObject jsonObject, Set<String> newPinnedEndpoints) { pinnedEndpointConstraintsStream = newPinnedEndpoints .stream() .map(EndpointConstraints::makePinnedEndpointConstraints); onEndpointConstraintsChangedEvent(); }

Target:
protected void onPinnedEndpointsChangedEvent( JSONObject jsonObject, Set<String> newPinnedEndpoints) { videoConstraintsCompatibility.setPinnedEndpoints(newPinnedEndpoints); onVideoConstraintsChangedEvent( videoConstraintsCompatibility.computeVideoConstraints()); }
Source:
public static @NonNull String duration() { return Objects.requireNonNull(Messages.TmfTime_Duration); }

Target:
public static @NonNull String duration() { return Objects.requireNonNull(Messages.TmfStrings_Duration); }
Source:
public Comment createComment(CoreSession session, Comment comment) throws IllegalArgumentException { DocumentRef commentRef = new IdRef(comment.getDocumentId()); if (!session.exists(commentRef)) { throw new IllegalArgumentException("The document " + comment.getDocumentId() + " does not exist."); } DocumentModel docToComment = session.getDocument(commentRef); DocumentModel commentModel = session.createDocumentModel(COMMENT_DOC_TYPE); commentModel.setPropertyValue("dc:created", Calendar.getInstance()); Comments.externalCommentToDocumentModel().accept(comment, commentModel); DocumentModel createdCommentModel = createComment(docToComment, commentModel); return Comments.newComment(createdCommentModel); }

Target:
public Comment createComment(CoreSession session, Comment comment) throws IllegalArgumentException { DocumentRef commentRef = new IdRef(comment.getDocumentId()); if (!session.exists(commentRef)) { throw new IllegalArgumentException("The document " + comment.getDocumentId() + " does not exist."); } DocumentModel docToComment = session.getDocument(commentRef); DocumentModel commentModel = session.createDocumentModel(COMMENT_DOC_TYPE); commentModel.setPropertyValue("dc:created", Calendar.getInstance()); Comments.commentToDocumentModel(comment, commentModel); if (comment instanceof ExternalEntity) { commentModel.addFacet(EXTERNAL_ENTITY_FACET); Comments.externalEntityToDocumentModel((ExternalEntity) comment, commentModel); } DocumentModel createdCommentModel = createComment(docToComment, commentModel); return Comments.newComment(createdCommentModel); }
Source:
private static String formatString(String sep, Object... msg) { String m = ""; for (Object o : msg) { m += String.valueOf(o) + sep; } return m; }

Target:
private static String formatString(String sep, Object... msg) { StringBuilder stringBuilder = new StringBuilder(); for (Object o : msg) { stringBuilder.append(String.valueOf(o)).append(sep); } return stringBuilder.toString(); }
Source:
public FileIteratingFirehose( Iterator<LineIterator> lineIterators, StringInputRowParser parser ) { this.lineIterators = lineIterators; this.parser = parser; final ParseSpec parseSpec = parser.getParseSpec(); if (parseSpec instanceof CSVParseSpec) { final Integer maxNumSkipHeadRows = ((CSVParseSpec) parseSpec).getMaxNumSkipHeadRows(); this.maxNumSkipHeadRows = maxNumSkipHeadRows == null ? DEFAULT_NUM_SKIP_HEAD_ROWS : maxNumSkipHeadRows; } else if (parseSpec instanceof DelimitedParseSpec) { final Integer maxNumSkipHeadRows = ((DelimitedParseSpec) parseSpec).getMaxNumSkipHeadRows(); this.maxNumSkipHeadRows = maxNumSkipHeadRows == null ? DEFAULT_NUM_SKIP_HEAD_ROWS : maxNumSkipHeadRows; } else { maxNumSkipHeadRows = DEFAULT_NUM_SKIP_HEAD_ROWS; } }

Target:
public FileIteratingFirehose( Iterator<LineIterator> lineIterators, StringInputRowParser parser ) { this.lineIterators = lineIterators; this.parser = parser; }
Source:
public Collection<BuildTarget<?>> computeDependencies(BuildTargetRegistry targetRegistry, TargetOutputIndex outputIndex) { return Collections.emptyList(); }

Target:
public Collection<BuildTarget<?>> computeDependencies(BuildTargetRegistry targetRegistry, TargetOutputIndex outputIndex) { return ContainerUtil.emptyList(); }
Source:
public void testConnectionWithCustomSchema() throws Exception { Connection fooConn = DriverManager.getConnection(String.format("crate://%s/foo", hostAndPort)); assertThat(fooConn.getSchema(), is("foo")); Statement statement = fooConn.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); ResultSet resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); Connection barConnection = DriverManager.getConnection(String.format("crate://%s/bar", hostAndPort)); assertThat(barConnection.getSchema(), is("bar")); statement = barConnection.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); }

Target:
public void testConnectionWithCustomSchema() throws Exception { Connection fooConn = DriverManager.getConnection(String.format("crate://%s/foo", hostAndPort)); assertThat(fooConn.getSchema(), is("foo")); Statement statement = fooConn.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); ResultSet resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); Connection barConnection = DriverManager.getConnection(String.format("crate://%s/bar", hostAndPort)); assertThat(barConnection.getSchema(), is("bar")); statement = barConnection.createStatement(); statement.execute("create table t (x string) with (number_of_replicas = 0)"); statement.execute("insert into t (x) values ('a')"); statement.execute("refresh table t"); resultSet = statement.executeQuery("select count(*) from t"); resultSet.next(); assertThat(resultSet.getLong(1), is(1L)); resultSet = statement.executeQuery( "select collect_set(schema_name) from information_schema.tables where table_name = 't'"); resultSet.next(); Object[] objects = (Object[]) resultSet.getObject(1); String[] schemas = Arrays.copyOf(objects, objects.length, String[].class); assertThat(schemas, Matchers.arrayContainingInAnyOrder("foo", "bar")); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AccessModel that = (AccessModel) o; return Objects.equal(perRepositoryAuthorities, that.perRepositoryAuthorities) && Objects.equal(perRepositoryPaths, that.perRepositoryPaths); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AccessModel that = (AccessModel) o; return Objects.equal(urlToPrivilegesMap, that.urlToPrivilegesMap); }
Source:
public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException { int PERMISSIONS_MASK = 07777; int MAX_SUPPORTED_MODE = 0b111111111; mode = mode & PERMISSIONS_MASK; if ((mode & MAX_SUPPORTED_MODE) != mode) { throw new IOException("Invalid mode: " + mode); } PosixFilePermission[] allPermissions = PosixFilePermission.values(); Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class); for (int i = 0; i < allPermissions.length; i++) { if ((mode & 1) == 1) { result.add(allPermissions[allPermissions.length - i - 1]); } mode >>= 1; } return result; }

Target:
public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException { int PERMISSIONS_MASK = 07777; int MAX_SUPPORTED_MODE = 0777; mode = mode & PERMISSIONS_MASK; if ((mode & MAX_SUPPORTED_MODE) != mode) { throw new IOException("Invalid mode: " + mode); } PosixFilePermission[] allPermissions = PosixFilePermission.values(); Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class); for (int i = 0; i < allPermissions.length; i++) { if ((mode & 1) == 1) { result.add(allPermissions[allPermissions.length - i - 1]); } mode >>= 1; } return result; }
Source:
public static Properties loadProperties(Class<?> clazz, String resource) { return loadProperties(clazz.getResourceAsStream(resource)); }

Target:
private static Properties loadProperties(Class<?> clazz, String resource) { return loadProperties(clazz.getResourceAsStream(resource)); }
Source:
public boolean applicable(Context context) { TypeElement parcelable = context.processingEnvironment().getElementUtils().getTypeElement("android.os.Parcelable"); TypeMirror autoValueClass = context.autoValueClass().asType(); return TypeSimplifier.isClassOfType(context.processingEnvironment().getTypeUtils(), parcelable.asType(), autoValueClass); }

Target:
public boolean applicable(Context context) { TypeMirror parcelable = context.processingEnvironment().getElementUtils() .getTypeElement("android.os.Parcelable").asType(); TypeMirror autoValueClass = context.autoValueClass().asType(); return TypeSimplifier.isClassOfType(context.processingEnvironment().getTypeUtils(), parcelable, autoValueClass); }
Source:
public AuthenticationResult getToken(String authorizationUrl) throws IOException, AuthenticationException { if (StringExtensions.isNullOrBlank(authorizationUrl)) { throw new IllegalArgumentException("authorizationUrl"); } HashMap<String, String> parameters = StringExtensions.getUrlParameters(authorizationUrl); String encodedState = parameters.get("state"); String state = decodeProtocolState(encodedState); if (!StringExtensions.isNullOrBlank(state)) { Uri stateUri = Uri.parse("http://state/path?" + state); String authorizationUri = stateUri.getQueryParameter("a"); String resource = stateUri.getQueryParameter("r"); if (!StringExtensions.isNullOrBlank(authorizationUri) && !StringExtensions.isNullOrBlank(resource) && resource.equalsIgnoreCase(mRequest.getResource())) { AuthenticationResult result = processUIResponseParams(parameters); if (result != null && result.getCode() != null && !result.getCode().isEmpty()) { if (!StringExtensions.isNullOrBlank(result.getAuthority())) { setTokenEndpoint(result.getAuthority() + DEFAULT_TOKEN_ENDPOINT); } final AuthenticationResult tokenResult; tokenResult = getTokenForCode(result.getCode()); if (!StringExtensions.isNullOrBlank(result.getAuthority())) { tokenResult.setCloudInstanceName(result.getAuthority()); } return tokenResult; } return result; } else { throw new AuthenticationException(ADALError.AUTH_FAILED_BAD_STATE); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_STATE); } }

Target:
public AuthenticationResult getToken(String authorizationUrl) throws IOException, AuthenticationException { if (StringExtensions.isNullOrBlank(authorizationUrl)) { throw new IllegalArgumentException("authorizationUrl"); } HashMap<String, String> parameters = StringExtensions.getUrlParameters(authorizationUrl); String encodedState = parameters.get("state"); String state = decodeProtocolState(encodedState); if (!StringExtensions.isNullOrBlank(state)) { Uri stateUri = Uri.parse("http://state/path?" + state); String authorizationUri = stateUri.getQueryParameter("a"); String resource = stateUri.getQueryParameter("r"); if (!StringExtensions.isNullOrBlank(authorizationUri) && !StringExtensions.isNullOrBlank(resource) && resource.equalsIgnoreCase(mRequest.getResource())) { AuthenticationResult result = processUIResponseParams(parameters); if (result != null && result.getCode() != null && !result.getCode().isEmpty()) { final AuthenticationResult tokenResult = getTokenForCode(result.getCode()); if (!StringExtensions.isNullOrBlank(result.getAuthority())) { tokenResult.setAuthority(result.getAuthority()); } else { tokenResult.setAuthority(mRequest.getAuthority()); } return tokenResult; } return result; } else { throw new AuthenticationException(ADALError.AUTH_FAILED_BAD_STATE); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_STATE); } }
Source:
public void testQuery() throws Exception { List<Map<String, Object>> users = handle.createQuery("SELECT id, name FROM user ORDER BY id ASC") .list(); assertThat(users, contains( map("id", 1, "name", "Alice"), map("id", 2, "name", "Bob"))); }

Target:
public void testQuery() throws Exception { List<Map<String, Object>> users = handle.createQuery("SELECT id, name FROM user ORDER BY id ASC") .list(); assertThat(users).containsExactly( map("id", 1, "name", "Alice"), map("id", 2, "name", "Bob")); }
Source:
public boolean getToggleStatus() { if (PrefManager.getUserStatus() == Constants.USER_OFFLINE) { return true; } else { return false; } }

Target:
public boolean getToggleStatus() { public boolean getToggleStatus() { return PrefManager.getUserStatus() == Constants.USER_OFFLINE } }
Source:
public void editServiceTypes(Editable mServiceNameText, Editable mServiceDiscriptionText, Editable mServiceDurationText, String uuid) { Services services=new Services(); services.setName(String.valueOf(mServiceNameText)); services.setDuration(Integer.valueOf(String.valueOf(mServiceDurationText))); Log.e("sgsg",String.valueOf(mServiceDiscriptionText)); services.setDescription(String.valueOf(mServiceDiscriptionText)); RestApi restApi = RestServiceBuilder.createService(RestApi.class); Call<Services> call = restApi.editServiceTypes(uuid,services); call.enqueue(new Callback<Services>() { @Override public void onResponse(Call<Services> call, Response<Services> response) { if (response.isSuccessful()) { mFormAddEditServiceView.endActivity(); } } @Override public void onFailure(Call<Services> call, Throwable t) { Log.e("jvsgsegaegk", String.valueOf(t)); } }); }

Target:
public void editServiceTypes(Editable mServiceNameText, Editable mServiceDiscriptionText, Editable mServiceDurationText, String uuid) { Services services=new Services(); services.setName(String.valueOf(mServiceNameText)); services.setDuration(Integer.valueOf(String.valueOf(mServiceDurationText))); services.setDescription(String.valueOf(mServiceDiscriptionText)); RestApi restApi = RestServiceBuilder.createService(RestApi.class); Call<Services> call = restApi.editServiceTypes(uuid,services); call.enqueue(new Callback<Services>() { @Override public void onResponse(Call<Services> call, Response<Services> response) { if (response.isSuccessful()) { mFormAddEditServiceView.endActivity(); } } @Override public void onFailure(Call<Services> call, Throwable t) { } }); }
Source:
public boolean every(@Nonnull F<T, Boolean> f) { ImmutableList<T> list = this; while (list instanceof NonEmptyImmutableList) { if (!f.apply(((NonEmptyImmutableList<T>) list).head)) { return false; } list = ((NonEmptyImmutableList<T>) list).tail; } return true; }

Target:
public boolean every(@Nonnull F<T, Boolean> f) { NonEmptyImmutableList<T> list = this; while (true) { if (!f.apply(list.head)) { return false; } if (list.tail instanceof Nil) { return true; } list = ((NonEmptyImmutableList<T>) list.tail); } }
Source:
protected long getBasesExcludedBy(final CountingFilter filter) { if(INTERVALS != null){ return filter.getFilteredRecords(); } return filter.getFilteredBases(); }

Target:
protected long getBasesExcludedBy(final CountingFilter filter) { return filter.getFilteredBases(); }
Source:
private void mergeDiffs(List<? extends Diff> differences, boolean leftToRight) { IDiffRelationshipComputer computer = new CachingDiffRelationshipComputer(mergerRegistry); if (leftToRight) { mergeRunnable = new MergeRunnableImpl(true, true, MergeMode.LEFT_TO_RIGHT, computer); } else { mergeRunnable = new MergeRunnableImpl(true, true, MergeMode.RIGHT_TO_LEFT, computer); } mergeRunnable.merge(differences, leftToRight, mergerRegistry); }

Target:
private void mergeDiffs(List<? extends Diff> differences, boolean leftToRight) { IDiffRelationshipComputer computer = new CachingDiffRelationshipComputer(mergerRegistry); final MergeMode mergeMode; if (leftToRight) { mergeMode = MergeMode.LEFT_TO_RIGHT; } else { mergeMode = MergeMode.RIGHT_TO_LEFT; } mergeRunnable = new MergeRunnableImpl(true, true, mergeMode, computer); mergeRunnable.merge(differences, leftToRight, mergerRegistry); }
Source:
private Indices range() { Long last = null; Long first = null; for (Entry<String, Collection<ObjectType>> a : edges.entrySet()) { Long value = RDF.sequenceNumberOf(a.getKey()); if (value != null) { if ((first == null) || (value < first)) { first = value; } if ((last == null) || (value > last)) { last = value; } } } return (first == null) || (last == null) ? null : new Indices(first, last); }

Target:
private Pair<Long, Long> range() { Long last = null; Long first = null; for (Entry<String, Collection<ObjectType>> a : edges.entrySet()) { Optional<Long> value = RDF.sequenceNumberOf(a.getKey()); if (value.isPresent()) { if ((first == null) || (value.get() < first)) { first = value.get(); } if ((last == null) || (value.get() > last)) { last = value.get(); } } } return (first == null) || (last == null) ? null : Pair.of(first, last); }
Source:
public void search_user_with_not_and_present_and_equal_field_returns_right_user() { String query = encodeExpected("not (extension.gender pr and extension.gender eq \"male\")"); SCIMSearchResult<User> queryResult = oConnector.searchUsers("filter=" + query + "&sortBy=username", accessToken); assertThat(queryResult.getTotalResults(), is(equalTo(3L))); assertThat(queryResult.getResources().get(0).getUserName(), is(equalTo("existing2"))); assertThat(queryResult.getResources().get(0).getUserName(), is(equalTo("existing3"))); assertThat(queryResult.getResources().get(1).getUserName(), is(equalTo("marissa"))); }

Target:
public void search_user_with_not_and_present_and_equal_field_returns_right_user() { String query = encodeExpected("not (extension.gender pr and extension.gender eq \"male\")"); SCIMSearchResult<User> queryResult = oConnector.searchUsers("filter=" + query + "&sortBy=username", accessToken); assertThat(queryResult.getTotalResults(), is(equalTo(3L))); assertThat(queryResult.getResources().get(0).getUserName(), is(equalTo("existing2"))); assertThat(queryResult.getResources().get(1).getUserName(), is(equalTo("existing3"))); assertThat(queryResult.getResources().get(2).getUserName(), is(equalTo("marissa"))); }
Source:
private List<? extends Message> generateEvents(Message command, CommandContext context) throws InvocationTargetException { checkNotNull(command, "command"); checkNotNull(context, "context"); final Object handlingResult = invokeHandler(command, context); return commandHandlingResultToEvents(handlingResult); }

Target:
private List<? extends Message> generateEvents(Message command, CommandContext context) throws InvocationTargetException { checkNotNull(command, "command"); checkNotNull(context, "context"); final Class<? extends Message> commandClass = command.getClass(); final Method method = commandHandlers.get(commandClass); if (method == null) { throw missingCommandHandler(commandClass); } final CommandHandlerMethod commandHandler = new AggregateCommandHandler(this, method); final List<? extends Message> result = commandHandler.invoke(command, context); return result; }
Source:
public void stepEnded(AbstractStepScope stepScope) { if (stepScope.getBestScoreImproved()) { DefaultSolverScope solverScope = stepScope.getPhaseScope().getSolverScope(); long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis(); Score bestScore = solverScope.getBestScore(); for (Iterator<Pair<Long, Score>> it = bestScoreImprovementHistoryQueue.iterator(); it.hasNext(); ) { Pair<Long, Score> bestScoreImprovement = it.next(); Score scoreDifference = bestScore.subtract(bestScoreImprovement.getValue()); final boolean timeLimitNotYetReached = bestScoreImprovement.getKey() + unimprovedTimeMillisSpentLimit >= bestSolutionTimeMillis; final boolean scoreImprovedOverThreshold = scoreDifference.compareTo(unimprovedScoreDifferenceThreshold) >= 0; if (scoreImprovedOverThreshold && timeLimitNotYetReached) { it.remove(); long safeTimeMillis = bestSolutionTimeMillis + unimprovedTimeMillisSpentLimit; solverSafeTimeMillis = safeTimeMillis; phaseSafeTimeMillis = safeTimeMillis; } else { break; } } bestScoreImprovementHistoryQueue.add(Pair.of(bestSolutionTimeMillis, bestScore)); } }

Target:
public void stepEnded(AbstractStepScope stepScope) { if (stepScope.getBestScoreImproved()) { DefaultSolverScope solverScope = stepScope.getPhaseScope().getSolverScope(); long bestSolutionTimeMillis = solverScope.getBestSolutionTimeMillis(); Score bestScore = solverScope.getBestScore(); for (Iterator<Pair<Long, Score>> it = bestScoreImprovementHistoryQueue.iterator(); it.hasNext(); ) { Pair<Long, Score> bestScoreImprovement = it.next(); Score scoreDifference = bestScore.subtract(bestScoreImprovement.getValue()); boolean timeLimitNotYetReached = bestScoreImprovement.getKey() + unimprovedTimeMillisSpentLimit >= bestSolutionTimeMillis; boolean scoreImprovedOverThreshold = scoreDifference.compareTo(unimprovedScoreDifferenceThreshold) >= 0; if (scoreImprovedOverThreshold && timeLimitNotYetReached) { it.remove(); long safeTimeMillis = bestSolutionTimeMillis + unimprovedTimeMillisSpentLimit; solverSafeTimeMillis = safeTimeMillis; phaseSafeTimeMillis = safeTimeMillis; } else { break; } } bestScoreImprovementHistoryQueue.add(Pair.of(bestSolutionTimeMillis, bestScore)); } }
Source:
public void checkAngularPatternfyStarterProjectCommands() { consoles.executeCommandFromProjectExplorer( ANGULAR_PATTERNFLY_STARTER, BUILD_GOAL, INSTALL_DEPENDENCIES_COMMAND_ITEM.getItem(ANGULAR_PATTERNFLY_STARTER), "bower_components/font-awesome"); consoles.executeCommandFromProjectExplorer( ANGULAR_PATTERNFLY_STARTER, RUN_GOAL, RUN_COMMAND_ITEM.getItem(ANGULAR_PATTERNFLY_STARTER), "Waiting..."); consoles.checkWebElementVisibilityAtPreviewPage(By.xpath(" consoles.closeProcessTabWithAskDialog("angular-patternfly-starter:run"); }

Target:
public void checkAngularPatternfyStarterProjectCommands() { By textOnPreviewPage = By.xpath(" consoles.executeCommandFromProjectExplorer( ANGULAR_PROJECT, BUILD_GOAL, INSTALL_DEPENDENCIES_COMMAND_ITEM.getItem(ANGULAR_PROJECT), "bower_components/font-awesome"); consoles.executeCommandFromProjectExplorer( ANGULAR_PROJECT, RUN_GOAL, RUN_COMMAND_ITEM.getItem(ANGULAR_PROJECT), "Waiting..."); consoles.checkWebElementVisibilityAtPreviewPage(textOnPreviewPage); consoles.closeProcessTabWithAskDialog(RUN_COMMAND_ITEM.getItem(ANGULAR_PROJECT)); }
Source:
@Override public void unparseCall(final SqlWriter writer, final SqlCall call, final int leftPrec, final int rightPrec) { switch (call.getKind()) { case POSITION: final SqlWriter.Frame frame = writer.startFunCall("STRPOS"); writer.sep(","); call.operand(1).unparse(writer, leftPrec, rightPrec); writer.sep(","); call.operand(0).unparse(writer, leftPrec, rightPrec); if (3 == call.operandCount()) { throw new RuntimeException("3rd operand Not Supported for Function STRPOS in Big Query"); } writer.endFunCall(frame); break; case UNION: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, UNION_DISTINCT, call, leftPrec, rightPrec); } break; case EXCEPT: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, EXCEPT_DISTINCT, call, leftPrec, rightPrec); } break; case INTERSECT: if (!((SqlSetOperator) call.getOperator()).isAll()) { SqlSyntax.BINARY.unparse(writer, INTERSECT_DISTINCT, call, leftPrec, rightPrec); } break; case REGEXP_SUBSTR: unparseRegexSubstr(writer, call, leftPrec, rightPrec); break; default: super.unparseCall(writer, call, leftPrec, rightPrec); } }

Target:
@Override public void unparseCall(final SqlWriter writer, final SqlCall call, final int leftPrec, final int rightPrec) { switch (call.getKind()) { case POSITION: final SqlWriter.Frame frame = writer.startFunCall("STRPOS"); writer.sep(","); call.operand(1).unparse(writer, leftPrec, rightPrec); writer.sep(","); call.operand(0).unparse(writer, leftPrec, rightPrec); if (3 == call.operandCount()) { throw new RuntimeException("3rd operand Not Supported for Function STRPOS in Big Query"); } writer.endFunCall(frame); break; case UNION: if (((SqlSetOperator) call.getOperator()).isAll()) { super.unparseCall(writer, call, leftPrec, rightPrec); } else { SqlSyntax.BINARY.unparse(writer, UNION_DISTINCT, call, leftPrec, rightPrec); } break; case EXCEPT: if (((SqlSetOperator) call.getOperator()).isAll()) { throw new RuntimeException("BigQuery does not support EXCEPT ALL"); } SqlSyntax.BINARY.unparse(writer, EXCEPT_DISTINCT, call, leftPrec, rightPrec); break; case INTERSECT: if (((SqlSetOperator) call.getOperator()).isAll()) { throw new RuntimeException("BigQuery does not support INTERSECT ALL"); } SqlSyntax.BINARY.unparse(writer, INTERSECT_DISTINCT, call, leftPrec, rightPrec); break; case TRIM: unparseTrim(writer, call, leftPrec, rightPrec); break; case REGEXP_SUBSTR: unparseRegexSubstr(writer, call, leftPrec, rightPrec); break; default: super.unparseCall(writer, call, leftPrec, rightPrec); } }
Source:
public WireRecord(Map<String, TypedValue<?>> properties) { requireNonNull(properties, "Properties cannot be null"); this.properties = properties; }

Target:
public WireRecord(Map<String, TypedValue<?>> properties) { requireNonNull(properties, "Properties cannot be null"); this.properties = new HashMap<>(properties); }
Source:
boolean complete(int bookieIndex, BookieSocketAddress host, ByteBuf buffer) { boolean completed = super.complete(bookieIndex, host, buffer); if (completed && lh.bk.getConf().getEnsemblePlacementPolicySlowBookies()) { int numReplicasTried = getNextReplicaIndexToReadFrom(); for (int i = 0 ; i < numReplicasTried - 1; i++) { int slowBookieIndex = writeSet.get(i); BookieSocketAddress slowBookieSocketAddress = ensemble.get(slowBookieIndex); lh.bk.placementPolicy.registerSlowBookie(slowBookieSocketAddress, entryId); } } return completed; }

Target:
boolean complete(int bookieIndex, BookieSocketAddress host, ByteBuf buffer) { boolean completed = super.complete(bookieIndex, host, buffer); if (completed) { int numReplicasTried = getNextReplicaIndexToReadFrom(); for (int i = 0 ; i < numReplicasTried - 1; i++) { int slowBookieIndex = writeSet.get(i); BookieSocketAddress slowBookieSocketAddress = ensemble.get(slowBookieIndex); lh.bk.placementPolicy.registerSlowBookie(slowBookieSocketAddress, eId); } } return completed; }
Source:
static Slf4jLogMessageContext parseSlf4jContextFromLogMessage(String logMessage) { Matcher m = LOGGER_CONTEXT_PATTERN.matcher(logMessage); String loggerName = "appium.service"; Level level = INFO; if (m.find()) { loggerName += "." + m.group(2).toLowerCase().replaceAll("\\s+", ""); if (m.group(1) != null) { level = DEBUG; } } return new Slf4jLogMessageContext(loggerName, level); }

Target:
static Slf4jLogMessageContext parseSlf4jContextFromLogMessage(String logMessage) { Matcher m = LOGGER_CONTEXT_PATTERN.matcher(logMessage); String loggerName = APPIUM_SERVICE_SLF4J_LOGGER_PREFIX; Level level = INFO; if (m.find()) { loggerName += "." + m.group(2).toLowerCase().replaceAll("\\s+", ""); if (m.group(1) != null) { level = DEBUG; } } return new Slf4jLogMessageContext(loggerName, level); }
Source:
public void should_wait_on_connection_if_zero_core_connections() throws Exception { int readTimeout = 1000; int reconnectInterval = 1000; Cluster cluster = this.createClusterBuilder() .withSocketOptions(new SocketOptions() .setConnectTimeoutMillis(readTimeout) .setReadTimeoutMillis(reconnectInterval)) .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); try { cluster.init(); assertThat(cluster).hasOpenControlConnection(); Connection.Factory factory = spy(cluster.manager.connectionFactory); cluster.manager.connectionFactory = factory; HostConnectionPool pool = createPool(cluster, 0, 2); assertThat(pool.connections).hasSize(0); assertThat(cluster).host(1).hasState(Host.State.UP); assertThat(cluster).hasOpenControlConnection(); reset(factory); MockRequest request = MockRequest.send(pool, 1); verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class)); Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS); assertPoolSize(pool, 1); request.requestInitialized.get(); request.simulateSuccessResponse(); } finally { cluster.close(); } }

Target:
public void should_wait_on_connection_if_zero_core_connections() throws Exception { int readTimeout = 1000; int reconnectInterval = 1000; Cluster cluster = this.createClusterBuilder() .withSocketOptions(new SocketOptions() .setConnectTimeoutMillis(readTimeout) .setReadTimeoutMillis(reconnectInterval)) .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); try { cluster.init(); assertThat(cluster).hasOpenControlConnection(); Connection.Factory factory = spy(cluster.manager.connectionFactory); cluster.manager.connectionFactory = factory; HostConnectionPool pool = createPool(cluster, 0, 2); assertThat(pool.connections).hasSize(0); assertThat(cluster).host(1).hasState(Host.State.UP); assertThat(cluster).hasOpenControlConnection(); reset(factory); MockRequest request = MockRequest.send(pool, 1); verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class)); assertPoolSize(pool, 1); Uninterruptibles.getUninterruptibly(request.requestInitialized, 10, TimeUnit.SECONDS); request.simulateSuccessResponse(); } finally { cluster.close(); } }