auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String formatColumnDefinition(ColumnDefinition column) { StringBuilder sb = new StringBuilder(formatExpression(column.getName(), parameters)) .append(" ").append(column.getType()); if (!column.isNullable()) { sb.append(" NOT NULL"); } if (column.getComment().isPresent()) { sb.append(" COMMENT ").append(formatStringLiteral(column.getComment().get())); } sb.append(formatPropertiesSingleLine(column.getProperties())); return sb.toString(); }

Target:
private String formatColumnDefinition(ColumnDefinition column) { StringBuilder sb = new StringBuilder() .append(formatExpression(column.getName(), parameters)) .append(" ").append(column.getType()); if (!column.isNullable()) { sb.append(" NOT NULL"); } column.getComment().ifPresent(comment -> sb.append(" COMMENT ").append(formatStringLiteral(comment))); sb.append(formatPropertiesSingleLine(column.getProperties())); return sb.toString(); }
Source:
public abstract void executeTask() throws MojoExecutionException, MojoFailureException; protected void resolveDocker() { DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() .withDockerHost(dockerHost) .withApiVersion(API_VERSION) .build(); docker = DockerClientBuilder.getInstance(config).build(); try { docker.infoCmd().exec(); } catch (Exception e) { String message; if (dockerHost.equals(DEFAULT_HOST_LINUX)) { message = "Couldn't connect to docker under default docker host address for linux"; boolean isUserWantChangeUrl = promptYesNo("Do You want to change docker host address?"); if (isUserWantChangeUrl) { dockerHost = prompt("Type updated host url (You can save this property later by calling openmrs-sdk:setup with defined -DdockerHost)"); resolveDocker(); } else { throw new RuntimeException(message, e); } } else { message = "Could not run `docker info`. If you are using 'Docker Toolbox', please make sure you run the SDK command from the 'Docker Toolbox' terminal."; } showMessage(message); throw new RuntimeException(message, e); } }

Target:
public abstract void executeTask() throws MojoExecutionException, MojoFailureException; protected void resolveDocker() { DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() .withDockerHost(dockerHost) .withApiVersion(API_VERSION) .build(); docker = DockerClientBuilder.getInstance(config).build(); try { docker.infoCmd().exec(); } catch (Exception e) { if (SystemUtils.IS_OS_LINUX) { throw new RuntimeException(LINUX_UNABLE_TO_CONNECT_MESSAGE, e); } else { throw new RuntimeException(NOT_LINUX_UNABLE_TO_CONNECT_MESSAGE, e); } } }
Source:
public PagedIterable<ModelData> createModels(List<String> models) { return new PagedIterable<>(digitalTwinsAsyncClient.createModels(models, Context.NONE)); }

Target:
public List<ModelData> createModels(List<String> models) { return createModelsWithResponse(models, Context.NONE).getValue(); }
Source:
public void setUp() { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(InstrumentationRegistry.getTargetContext()); for (String setting : allSettings) { initialSettings.put(setting, sharedPreferences.getBoolean(setting, false)); } SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.RESTRICTED_LOGIN_ACCEPTED, false); editor.putBoolean(Constants.CREATE_AT_SCHOOL_USER, true); editor.apply(); Reflection.setPrivateField(Constants.class, "DEFAULT_ROOT", Environment.getExternalStorageDirectory() .getAbsolutePath() + "/Pocket Code"); baseActivityTestRule.launchActivity(null); idlingResource = baseActivityTestRule.getActivity().getIdlingResource(); Espresso.registerIdlingResources(idlingResource); UiTestUtils.setFakeToken(baseActivityTestRule.getActivity(), false); }

Target:
public void setUp() { SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(InstrumentationRegistry.getTargetContext()); for (String setting : allSettings) { initialSettings.put(setting, sharedPreferences.getBoolean(setting, false)); } initialTokenSetting = sharedPreferences.getString(Constants.TOKEN, Constants.NO_TOKEN); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.RESTRICTED_LOGIN_ACCEPTED, false); editor.putBoolean(Constants.CREATE_AT_SCHOOL_USER, false); editor.apply(); ServerCalls.useTestUrl = true; baseActivityTestRule.launchActivity(null); idlingResource = baseActivityTestRule.getActivity().getIdlingResource(); Espresso.registerIdlingResources(idlingResource); setFakeToken(baseActivityTestRule.getActivity(), false); }
Source:
public List<ChangeItem> call() throws Exception { TransactionTokenDelta txDelta = new TransactionTokenDelta(sourceTx, destinationTx); Callable<List<ChangeItem>> callable; BranchId branch = null; if (txDelta.areOnTheSameBranch()) { callable = new LoadDeltasBetweenTxsOnTheSameBranch(getLogger(), getSession(), getJdbcClient(), joinFactory, txDelta, applicQuery); branch = txDelta.getStartTx().getBranch(); } else { BranchId mergeBranch = getJdbcClient().fetch(BranchId.SENTINEL, SELECT_MERGE_BRANCH_UUID, sourceTx.getBranch(), destinationTx.getBranch()); branch = sourceTx.getBranch(); TransactionId mergeTx = TransactionId.SENTINEL; if (mergeBranch.isValid()) { mergeTx = getJdbcClient().fetch(TransactionId.SENTINEL, SELECT_MERGE_BRANCH_HEAD_TX, mergeBranch); } callable = new LoadDeltasBetweenBranches(getLogger(), getSession(), getJdbcClient(), joinFactory, sourceTx.getBranch(), destinationTx.getBranch(), destinationTx, mergeBranch, mergeTx, applicQuery); } List<ChangeItem> changes = callAndCheckForCancel(callable); changes.addAll(missingChangeItemFactory.createMissingChanges(this, getSession(), changes, sourceTx, destinationTx, applicQuery)); Callable<List<ChangeItem>> computeChanges = new ComputeNetChangeCallable(changes); changes = callAndCheckForCancel(computeChanges); AddSyntheticArtifactChangeData addArtifactData = new AddSyntheticArtifactChangeData(changes, getJdbcClient(), branch); return addArtifactData.doWork(); }

Target:
public List<ChangeItem> call() throws Exception { TransactionTokenDelta txDelta = new TransactionTokenDelta(sourceTx, destinationTx); Callable<List<ChangeItem>> callable; BranchId branch = BranchId.SENTINEL; if (txDelta.areOnTheSameBranch()) { callable = new LoadDeltasBetweenTxsOnTheSameBranch(getLogger(), getSession(), getJdbcClient(), joinFactory, txDelta, applicQuery); branch = txDelta.getStartTx().getBranch(); } else { BranchId mergeBranch = getJdbcClient().fetch(BranchId.SENTINEL, SELECT_MERGE_BRANCH_UUID, sourceTx.getBranch(), destinationTx.getBranch()); branch = sourceTx.getBranch(); TransactionId mergeTx = TransactionId.SENTINEL; if (mergeBranch.isValid()) { mergeTx = getJdbcClient().fetch(TransactionId.SENTINEL, SELECT_MERGE_BRANCH_HEAD_TX, mergeBranch); } callable = new LoadDeltasBetweenBranches(getLogger(), getSession(), getJdbcClient(), joinFactory, sourceTx.getBranch(), destinationTx.getBranch(), destinationTx, mergeBranch, mergeTx, applicQuery); } List<ChangeItem> changes = callAndCheckForCancel(callable); changes.addAll(missingChangeItemFactory.createMissingChanges(this, getSession(), changes, sourceTx, destinationTx, applicQuery)); Callable<List<ChangeItem>> computeChanges = new ComputeNetChangeCallable(changes); changes = callAndCheckForCancel(computeChanges); AddSyntheticArtifactChangeData addArtifactData = new AddSyntheticArtifactChangeData(changes, getJdbcClient(), branch); return addArtifactData.doWork(); }
Source:
private BlobId(DataInputStream stream, ClusterMap clusterMap, boolean ensureFullyRead) throws IOException { this.version = stream.readShort(); switch (version) { case BLOB_ID_V1: flag = DEFAULT_FLAG; datacenterId = LEGACY_DATACENTER_ID; accountId = LEGACY_ACCOUNT_ID; containerId = LEGACY_CONTAINER_ID; break; case BLOB_ID_V2: flag = stream.readByte(); datacenterId = stream.readByte(); accountId = stream.readShort(); containerId = stream.readShort(); break; default: throw new IllegalArgumentException("blobId version " + version + " not supported."); } partitionId = clusterMap.getPartitionIdFromStream(stream); if (partitionId == null) { throw new IllegalArgumentException("Partition ID cannot be null"); } uuid = Utils.readIntString(stream); if (ensureFullyRead && stream.read() != -1) { throw new IllegalArgumentException("Stream should have no more available bytes to read"); } }

Target:
private BlobId(DataInputStream stream, ClusterMap clusterMap, boolean ensureFullyRead) throws IOException { version = stream.readShort(); switch (version) { case BLOB_ID_V1: flag = DEFAULT_FLAG; datacenterId = UNKNOWN_DATACENTER_ID; accountId = UNKNOWN_ACCOUNT_ID; containerId = UNKNOWN_CONTAINER_ID; break; case BLOB_ID_V2: flag = stream.readByte(); datacenterId = stream.readByte(); accountId = stream.readShort(); containerId = stream.readShort(); break; default: throw new IllegalArgumentException("blobId version " + version + " not supported."); } partitionId = clusterMap.getPartitionIdFromStream(stream); if (partitionId == null) { throw new IllegalArgumentException("Partition ID cannot be null"); } uuid = Utils.readIntString(stream); if (ensureFullyRead && stream.read() != -1) { throw new IllegalArgumentException("Stream should have no more available bytes to read"); } }
Source:
public Integer getConnectTimeoutOrDefault() { if (Objects.isNull(connectTimeout)) { return defaultConnectTimeout; } return connectTimeout; }

Target:
public Integer getConnectTimeoutOrDefault() { if (null == connectTimeout) { return defaultConnectTimeout; } return connectTimeout; }
Source:
public static String remapFieldName(Class<?> clazz, String fieldName) { String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz)); return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fieldName, null); }

Target:
private static String remapFieldName(Class<?> clazz, String fieldName) { String internalClassName = FMLDeobfuscatingRemapper.INSTANCE.unmap(Type.getInternalName(clazz)); return FMLDeobfuscatingRemapper.INSTANCE.mapFieldName(internalClassName, fieldName, null); }
Source:
public LoggerHandler()

Target:
public LoggerHandler() { ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleWithFixedDelay( new Runnable() { @Override public void run() { extensions = null; } }, 1, REFRESH_INTERVAL_IN_SECONDS, TimeUnit.SECONDS ); }
Source:
public static Map<String,String> toMap(List<EnvironmentProperty> properties) { if (properties != null) { final Map<String, String> result = new LinkedHashMap<String, String>(); for (EnvironmentProperty property:properties) { result.put(property.getName(), property.getValue()); } return result; } return null; }

Target:
public static Map<String,String> toMap(List<EnvironmentProperty> properties) { final Map<String, String> result = new LinkedHashMap<String, String>(); if (properties != null) { for (EnvironmentProperty property:properties) { result.put(property.getName(), property.getValue()); } return result; } return result; }
Source:
private void setEEfromBuild(Bndrun run) { String runee = run.getProperty(Constants.RUNEE); if (runee == null) { Optional.ofNullable(project.getPlugin("org.apache.maven.plugins:maven-compiler-plugin")) .map(Plugin::getConfiguration) .map(Xpp3Dom.class::cast) .map(dom -> dom.getChild("target")) .map(Xpp3Dom::getValue) .map(EE::highestFromTargetVersion) .map(Optional::get) .ifPresent(ee -> run.setProperty(Constants.RUNEE, ee.getEEName())); } }

Target:
private void setEEfromBuild(Bndrun run) { String runee = run.getProperty(Constants.RUNEE); if (runee == null) { Optional.ofNullable(project.getPlugin("org.apache.maven.plugins:maven-compiler-plugin")) .map(Plugin::getConfiguration) .map(Xpp3Dom.class::cast) .map(dom -> dom.getChild("target")) .map(Xpp3Dom::getValue) .flatMap(EE::highestFromTargetVersion) .ifPresent(ee -> run.setProperty(Constants.RUNEE, ee.getEEName())); } }
Source:
public Map<String, Object> getApplicationPropertiesMap(boolean createIfAbsent) { ApplicationProperties appMap = lazyDecodeApplicationProperties(); Map<String, Object> map = null; if (appMap != null) { map = appMap.getValue(); } if (map == null) { if (createIfAbsent) { map = new HashMap<>(); this.applicationProperties = new ApplicationProperties(map); } else { map = Collections.EMPTY_MAP; } } return map; }

Target:
protected Map<String, Object> getApplicationPropertiesMap(boolean createIfAbsent) { ApplicationProperties appMap = lazyDecodeApplicationProperties(); Map<String, Object> map = null; if (appMap != null) { map = appMap.getValue(); } if (map == null) { if (createIfAbsent) { map = new HashMap<>(); this.applicationProperties = new ApplicationProperties(map); } else { map = Collections.EMPTY_MAP; } } return map; }
Source:
public Official getOfficialById(int id) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); TypedQuery<Official> query = entityManager.createQuery("from Official p where p.member_id = " + id, Official.class); Official official = query.getSingleResult(); transaction.commit(); entityManager.close(); return official; }

Target:
public Official getOfficialById(int id) { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); TypedQuery<Official> query = entityManager.createQuery("from Official p where p.member_id = :id", Official.class); query.setParameter("id", id); Official official = query.getSingleResult(); transaction.commit(); entityManager.close(); return official; }
Source:
public List<String> getDependencies() { return Collections.singletonList(A_R_projectsBasePath); }

Target:
public List<String> getDependencies() { List<String> dependencies = new ArrayList<>(); dependencies.add(A_GR_projectName); dependencies.add(A_R_projectsBasePath); return dependencies; }
Source:
public void testDynamicColor() throws CQLException { Expression color = toExpression("if_then_else(equalTo(field, 1), '#8080C0', '#CC8030')"); Stroke stroke = styleFactory.stroke(color, null, null, null, null, null, null); Fill fill = styleFactory.fill(null, color, null ); Mark mark = styleFactory.mark(toExpression("circle"), fill, stroke); Graphic graphic = styleFactory.graphic( Collections.singletonList(mark),null, null, null, null, null); PointSymbolizer symbolizer = styleFactory.pointSymbolizer("symbolizer", toExpression("geom"), null, null, graphic ); final Style s = styleFromRules(catchAllRule(symbolizer)); assertEquals("0.0.0=&0.0.0.fill.color=%238080C0&0.0.0.name=&0.0.0.stroke.color=%238080C0", encode(s, fieldIs1)); assertEquals("0.0.0=&0.0.0.fill.color=C08030&0.0.0.name=&0.0.0.stroke.color=C08030", encode(s, fieldIs2)); }

Target:
public void testDynamicColor() throws CQLException { Expression color = toExpression("if_then_else(equalTo(field, 1), '#8080C0', '#CC8030')"); Stroke stroke = styleFactory.stroke(color, null, null, null, null, null, null); Fill fill = styleFactory.fill(null, color, null); Mark mark = styleFactory.mark(toExpression("circle"), fill, stroke); Graphic graphic = styleFactory.graphic(Collections.singletonList(mark), null, null, null, null, null); PointSymbolizer symbolizer = styleFactory.pointSymbolizer( "symbolizer", toExpression("geom"), null, null, graphic); final Style s = styleFromRules(catchAllRule(symbolizer)); assertEquals( "0.0.0=&0.0.0.fill.color=%238080C0&0.0.0.name=&0.0.0.stroke.color=%238080C0", encode(s, fieldIs1)); assertEquals( "0.0.0=&0.0.0.fill.color=%23CC8030&0.0.0.name=&0.0.0.stroke.color=%23CC8030", encode(s, fieldIs2)); }
Source:
private String convertDaysToMidnightTimestamp(String columnName) { return format("(CAST (%s AS BIGINT) * %s)", columnName, TimeUnit.DAYS.toMillis(1)); }

Target:
private String convertDaysToMidnightTimestamp(String columnName) { return format("(CAST (%s AS BIGINT) * %s)", columnName, DAYS.toMillis(1)); }
Source:
default <U extends T> CompletableFuture<T> toCompletableFuture() { return CompletableFuture.completedFuture(Boolean.TRUE).thenApply(t -> get()); }

Target:
default <U extends T> CompletableFuture<T> toCompletableFuture() { final CompletableFuture<T> completableFuture = new CompletableFuture<>(); try { completableFuture.complete(get()); } catch (Try.FatalException x) { throw x; } catch (Try.NonFatalException x) { completableFuture.completeExceptionally(x.getCause()); } catch (Throwable x) { completableFuture.completeExceptionally(x); } return completableFuture; }
Source:
public static int getNumberOfColumns(FormEntryPrompt formEntryPrompt, Context context) { int numColumns = 1; String appearance = getAppearance(formEntryPrompt); if (appearance.contains(COLUMNS_N) || appearance.contains(COMPACT_N)) { try { String columnsAppearance = appearance.contains(COLUMNS_N) ? COLUMNS_N : COMPACT_N; if (appearance.contains(columnsAppearance)) { try { appearance = appearance.substring(appearance.indexOf(columnsAppearance), appearance.length()); int idx = appearance.indexOf(columnsAppearance); if (idx != -1) { String substringFromNumColumns = appearance.substring(idx + columnsAppearance.length()); numColumns = Integer.parseInt(substringFromNumColumns.substring(0, substringFromNumColumns.contains(" ") ? substringFromNumColumns.indexOf(' ') : substringFromNumColumns.length())); } } catch (Exception e) { Timber.e(EXCEPTION_PARSING_COLUMNS); } } } catch (Exception e) { Timber.e(EXCEPTION_PARSING_COLUMNS); } } else if (appearance.contains(COLUMNS)) { switch (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) { case Configuration.SCREENLAYOUT_SIZE_SMALL: numColumns = 2; break; case Configuration.SCREENLAYOUT_SIZE_NORMAL: numColumns = 3; break; case Configuration.SCREENLAYOUT_SIZE_LARGE: numColumns = 4; break; case Configuration.SCREENLAYOUT_SIZE_XLARGE: numColumns = 5; break; default: numColumns = 3; } } return numColumns; }

Target:
public static int getNumberOfColumns(FormEntryPrompt formEntryPrompt, Context context) { int numColumns = 1; String appearance = getSanitizedAppearanceHint(formEntryPrompt); if (appearance.contains(COLUMNS_N) || appearance.contains(COMPACT_N)) { try { String columnsAppearance = appearance.contains(COLUMNS_N) ? COLUMNS_N : COMPACT_N; try { appearance = appearance.substring(appearance.indexOf(columnsAppearance)); int idx = appearance.indexOf(columnsAppearance); if (idx != -1) { String substringFromNumColumns = appearance.substring(idx + columnsAppearance.length()); numColumns = Integer.parseInt(substringFromNumColumns.substring(0, substringFromNumColumns.contains(" ") ? substringFromNumColumns.indexOf(' ') : substringFromNumColumns.length())); } } catch (Exception e) { Timber.e(EXCEPTION_PARSING_COLUMNS); } } catch (Exception e) { Timber.e(EXCEPTION_PARSING_COLUMNS); } } else if (appearance.contains(COLUMNS)) { switch (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) { case Configuration.SCREENLAYOUT_SIZE_SMALL: numColumns = 2; break; case Configuration.SCREENLAYOUT_SIZE_NORMAL: numColumns = 3; break; case Configuration.SCREENLAYOUT_SIZE_LARGE: numColumns = 4; break; case Configuration.SCREENLAYOUT_SIZE_XLARGE: numColumns = 5; break; default: numColumns = 3; } } return numColumns; }
Source:
public HDPath extend(ChildNumber child1, ChildNumber child2) { List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); mutable.add(child1); mutable.add(child2); return new HDPath(mutable); }

Target:
public HDPath extend(ChildNumber child1, ChildNumber child2) { List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); mutable.add(child1); mutable.add(child2); return new HDPath(this.hasPrivateKey, mutable); }
Source:
public void parseParentPom(File file) { try { parseParentPom(new FileInputStream(file)); } catch (FileNotFoundException ex) { LOGGER.error("Error while opening parent POM file", ex); } }

Target:
public void parseParentPom(File file) { try (FileInputStream fileInputStream = new FileInputStream(file)) { parseParentPom(fileInputStream); } catch (IOException ex) { LOGGER.error("Error while reading parent POM file", ex); } }
Source:
public PathInfo flush(long position, boolean overwrite) { DataLakeRequestConditions requestConditions = null; if (!overwrite) { requestConditions = new DataLakeRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return flushWithResponse(position, false, false, null, requestConditions, null, Context.NONE).getValue(); }

Target:
public PathInfo flush(long position, boolean overwrite) { DataLakeRequestConditions requestConditions = new DataLakeRequestConditions(); if (!overwrite) { requestConditions = new DataLakeRequestConditions().setIfNoneMatch(Constants.HeaderConstants.ETAG_WILDCARD); } return flushWithResponse(position, false, false, null, requestConditions, null, Context.NONE).getValue(); }
Source:
public Model read(InputStream input, Map<String, ?> options) throws IOException, ModelParseException { String location = PolyglotModelUtil.getLocation(options); String fixLocation = fixLocation(location); File file = new File(fixLocation); if (!fixLocation.equals(location)) { try (InputStreamReader stream = new InputStreamReader(new FileInputStream(file), getPrimaryArtifactCharset())) { return read(stream, file, options); } } try (InputStreamReader stream = new InputStreamReader(input, getPrimaryArtifactCharset())) { return read(stream, file, options); } }

Target:
public Model read(InputStream input, Map<String, ?> options) throws IOException, ModelParseException { String location = PolyglotModelUtil.getLocation(options); String fixLocation = fixLocation(location); File file = new File(fixLocation); if (!fixLocation.equals(location)) { input.close(); try (InputStreamReader stream = new InputStreamReader(new FileInputStream(file), getPrimaryArtifactCharset())) { return read(stream, file, options); } } try (InputStreamReader stream = new InputStreamReader(input, getPrimaryArtifactCharset())) { return read(stream, file, options); } }
Source:
public boolean isSoftLimitReached(Guid volumeId) { GlusterVolumeEntity volume = getGlusterVolumeDao().getById(volumeId); if (volume != null) { GlusterVolumeSnapshotConfig config = getGlusterVolumeSnapshotConfigDao().getConfigByClusterIdAndName(volume.getClusterId(), "snap-max-soft-limit"); if (config != null) { String configValue = config.getParamValue(); if (configValue.endsWith("%")) { configValue = configValue.substring(0, configValue.length() - 1); } int snapMaxSoftLimitPcnt = Integer.parseInt(configValue); int snapshotCount = volume.getSnapshotsCount(); int snapMaxLimit = volume.getSnapMaxLimit(); return snapshotCount >= (snapMaxLimit * snapMaxSoftLimitPcnt) / 100; } } return false; }

Target:
public boolean isSoftLimitReached(Guid volumeId) { GlusterVolumeEntity volume = getGlusterVolumeDao().getById(volumeId); if (volume != null) { GlusterVolumeSnapshotConfig config = getGlusterVolumeSnapshotConfigDao().getConfigByClusterIdAndName(volume.getClusterId(), "snap-max-soft-limit"); if (config != null) { String configValue = StringUtils.removeEnd(config.getParamValue(), "%"); int snapMaxSoftLimitPcnt = Integer.parseInt(configValue); int snapshotCount = volume.getSnapshotsCount(); int snapMaxLimit = volume.getSnapMaxLimit(); return snapshotCount >= (snapMaxLimit * snapMaxSoftLimitPcnt) / 100; } } return false; }
Source:
private Event getNextEvent(List<Event> listEvents) { if (listEvents == null || listEvents.size() == 0) { return null; } Event ret = listEvents.get(0); for (Event e : listEvents) { if (e.getStart().isBefore(ret.getStart())) { ret = e; } } return ret; }

Target:
private Event getNextEvent(List<Event> listEvents) { if (listEvents == null || listEvents.size() == 0) { return null; } Event ret = null; for (Event e : listEvents) { if (e.getStart().isAfterNow()) { if (ret == null) { ret = e; } else { if (e.getStart().isBefore(ret.getStart())) { ret = e; } } } } return ret; }
Source:
public static Stream<DocumentWriteOperation> from(Stream<? extends AbstractWriteHandle> content, final DocumentUriMaker uriMaker) { final class DocumentWriteOperationImpl implements DocumentWriteOperation { public DocumentWriteOperationImpl(AbstractWriteHandle content, String uri) { this.content = content; this.uri = uri; } private AbstractWriteHandle content; private String uri; @Override public OperationType getOperationType() { return null; } @Override public String getUri() { return uri; } @Override public DocumentMetadataWriteHandle getMetadata() { return null; } @Override public AbstractWriteHandle getContent() { return content; } @Override public String getTemporalDocumentURI() { return null; } } final class WrapperImpl { DocumentWriteOperation mapper(AbstractWriteHandle content) { String uri = uriMaker.apply(content); if (uri == null) throw new MarkLogicInternalException("Uri could not be created"); return new DocumentWriteOperationImpl(content, uri); } } WrapperImpl wrapperImpl = new WrapperImpl(); return content.map(wrapperImpl::mapper); }

Target:
public static Stream<DocumentWriteOperation> from(Stream<? extends AbstractWriteHandle> content, final DocumentUriMaker uriMaker) { if(content == null || uriMaker == null) throw new IllegalArgumentException("Content and/or Uri maker cannot be null"); final class DocumentWriteOperationImpl implements DocumentWriteOperation { private AbstractWriteHandle content; private String uri; public DocumentWriteOperationImpl(AbstractWriteHandle content, String uri) { this.content = content; this.uri = uri; } @Override public OperationType getOperationType() { return null; } @Override public String getUri() { return uri; } @Override public DocumentMetadataWriteHandle getMetadata() { return null; } @Override public AbstractWriteHandle getContent() { return content; } @Override public String getTemporalDocumentURI() { return null; } } final class WrapperImpl { private DocumentUriMaker docUriMaker; WrapperImpl(DocumentUriMaker uriMaker){ this.docUriMaker = uriMaker; } DocumentWriteOperation mapper(AbstractWriteHandle content) { String uri = docUriMaker.apply(content); if (uri == null) throw new MarkLogicInternalException("Uri could not be created"); return new DocumentWriteOperationImpl(content, uri); } } WrapperImpl wrapperImpl = new WrapperImpl(uriMaker); return content.map(wrapperImpl::mapper); }
Source:
public void applyTitle(final String title, final MutationContext mutationContext) { if (title != null && title.trim().length() > 0 && getShapeView() instanceof HasTitle) { final HasTitle hasTitle = (HasTitle) getShapeView(); hasTitle.setTitle(title); hasTitle.refreshTitle(); } }

Target:
public void applyTitle(final String title, final MutationContext mutationContext) { if (title != null && getShapeView() instanceof HasTitle) { final HasTitle hasTitle = (HasTitle) getShapeView(); hasTitle.setTitle(title); hasTitle.refreshTitle(); } }
Source:
protected void completeRequest(BlockReadRequestContext context) throws Exception { BlockReader reader = null; try { reader = context.getBlockReader(); if (reader != null) { reader.close(); } } finally { if (!mWorker.unlockBlock(context.getRequest().getSessionId(), context.getRequest().getId())) { if (reader != null) { mWorker.closeUfsBlock(context.getRequest().getSessionId(), context.getRequest().getId()); context.setBlockReader(null); } } } }

Target:
protected void completeRequest(BlockReadRequestContext context) throws Exception { BlockReader reader = null; try { reader = context.getBlockReader(); if (reader != null) { reader.close(); } } catch (Exception e) { LOG.warn("Failed to close block reader for block with error {}.", context.getRequest().getId(), e.getMessage()); } finally { if (!mWorker.unlockBlock(context.getRequest().getSessionId(), context.getRequest().getId())) { if (reader != null) { mWorker.closeUfsBlock(context.getRequest().getSessionId(), context.getRequest().getId()); context.setBlockReader(null); } } } }
Source:
public KubernetesClientException asClientException() { final Throwable cause = getCause(); return getCause() instanceof KubernetesClientException ? (KubernetesClientException) cause : new KubernetesClientException(getMessage(), cause); }

Target:
public KubernetesClientException asClientException() { final Throwable cause = getCause(); return cause instanceof KubernetesClientException ? (KubernetesClientException) cause : new KubernetesClientException(getMessage(), cause); }
Source:
public ShardSpecLookup getLookup(final List<ShardSpec> shardSpecs) { final ImmutableMap.Builder<Integer, ShardSpec> shardSpecsMapBuilder = ImmutableMap.builder(); for (ShardSpec spec : shardSpecs) { shardSpecsMapBuilder.put(spec.getPartitionNum(), spec); } final Map<Integer, ShardSpec> shardSpecMap = shardSpecsMapBuilder.build(); return new ShardSpecLookup() { @Override public ShardSpec getShardSpec(InputRow row) { return shardSpecMap.get((long) hash(row) % getPartitions()); } }; }

Target:
public ShardSpecLookup getLookup(final List<ShardSpec> shardSpecs) { return new ShardSpecLookup() { @Override public ShardSpec getShardSpec(InputRow row) { int index = Math.abs(hash(row) % getPartitions()); return shardSpecs.get(index); } }; }
Source:
private MemoryStoreImpl(final HTrace hTrace, final OperationRouter<Long> router, final BlockResolver<Long> blockResolver, final RemoteOpHandler<Long> remoteOpHandler, @Parameter(NumStoreThreads.class) final int numStoreThreads) { hTrace.initialize(); this.router = router; this.blockResolver = blockResolver; this.remoteOpHandler = remoteOpHandler; for (final int blockId : router.getInitialLocalBlockIds()) { blocks.put(blockId, new Block()); } initExecutor(numStoreThreads); }

Target:
private MemoryStoreImpl(final HTrace hTrace, final OperationRouter<Long> router, final BlockResolver<Long> blockResolver, final RemoteOpHandler<Long> remoteOpHandler, @Parameter(NumStoreThreads.class) final int numStoreThreads) { hTrace.initialize(); this.router = router; this.blockResolver = blockResolver; this.remoteOpHandler = remoteOpHandler; initBlocks(); initExecutor(numStoreThreads); }
Source:
public List<DocumentRevision> call(SQLDatabase db) throws Exception { String sql = String.format("SELECT " + DatastoreImpl.FULL_DOCUMENT_COLS + " FROM revs, docs" + " WHERE docid IN ( %1$s ) AND current = 1 AND docs.doc_id = revs" + ".doc_id " + " ORDER BY docs.doc_id ", DatabaseUtils.makePlaceholders(docIds.size ())); String[] args = docIds.toArray(new String[docIds.size()]); List<DocumentRevision> docs = DatastoreImpl.getRevisionsFromRawQuery(db, sql, args, attachmentsDir, attachmentStreamFactory); return DatastoreImpl.sortDocumentsAccordingToIdList(docIds, docs); }

Target:
public List<DocumentRevision> call(SQLDatabase db) throws Exception { String sql = String.format("SELECT " + DatastoreImpl.FULL_DOCUMENT_COLS + " FROM revs, docs" + " WHERE docid IN ( %1$s ) AND current = 1 AND docs.doc_id = revs.doc_id " + " ORDER BY docs.doc_id ", DatabaseUtils.makePlaceholders(docIds.size ())); String[] args = docIds.toArray(new String[docIds.size()]); List<DocumentRevision> docs = DatastoreImpl.getRevisionsFromRawQuery(db, sql, args, attachmentsDir, attachmentStreamFactory); return DatastoreImpl.sortDocumentsAccordingToIdList(docIds, docs); }
Source:
public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (level == Connection.TRANSACTION_NONE) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", "TRANSACTION_NONE"), PSQLState.INVALID_PARAMETER_VALUE); } else if (level == this.isolationLevel && cacheXactState) { return; } if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction isolation level in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } String isolationLevelName; switch (level) { case Connection.TRANSACTION_READ_COMMITTED: isolationLevelName = "READ COMMITTED"; break; case Connection.TRANSACTION_SERIALIZABLE: isolationLevelName = "SERIALIZABLE"; break; case Connection.TRANSACTION_REPEATABLE_READ: isolationLevelName = "REPEATABLE READ"; break; case Connection.TRANSACTION_READ_UNCOMMITTED: isolationLevelName = "READ UNCOMMITTED"; break; default: isolationLevelName = null; } if (isolationLevelName == null) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level), PSQLState.NOT_IMPLEMENTED); } String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName; execSQLUpdate(isolationLevelSQL); this.isolationLevel = level; LOGGER.log(Level.FINE, " setTransactionIsolation = {0}", isolationLevelName); }

Target:
public void setTransactionIsolation(int level) throws SQLException { checkClosed(); if (queryExecutor.getTransactionState() != TransactionState.IDLE) { throw new PSQLException( GT.tr("Cannot change transaction isolation level in the middle of a transaction."), PSQLState.ACTIVE_SQL_TRANSACTION); } if (level == Connection.TRANSACTION_NONE) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", "TRANSACTION_NONE"), PSQLState.INVALID_PARAMETER_VALUE); } else if (this.isolationLevel == level && cacheIsolationState) { return; } String isolationLevelName; switch (level) { case Connection.TRANSACTION_READ_COMMITTED: isolationLevelName = "READ COMMITTED"; break; case Connection.TRANSACTION_SERIALIZABLE: isolationLevelName = "SERIALIZABLE"; break; case Connection.TRANSACTION_REPEATABLE_READ: isolationLevelName = "REPEATABLE READ"; break; case Connection.TRANSACTION_READ_UNCOMMITTED: isolationLevelName = "READ UNCOMMITTED"; break; default: isolationLevelName = null; } if (isolationLevelName == null) { throw new PSQLException(GT.tr("Transaction isolation level {0} not supported.", level), PSQLState.NOT_IMPLEMENTED); } String isolationLevelSQL = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " + isolationLevelName; execSQLUpdate(isolationLevelSQL); this.isolationLevel = level; LOGGER.log(Level.FINE, " setTransactionIsolation = {0}", this.isolationLevel); }
Source:
public void init(FilterConfig config) throws ServletException { encoding = config.getInitParameter("requestEncoding"); if (encoding == null) { encoding = "UTF-8"; } Enumeration enumeration = config.getInitParameterNames(); this.excludePatterns = new LinkedList(); this.maxWaitDurations = new HashMap(); while (enumeration.hasMoreElements()) { String paramName = (String) enumeration.nextElement(); String paramValue = config.getInitParameter(paramName); if (paramName.startsWith("excludePattern")) { Pattern excludePattern = Pattern.compile(paramValue); this.excludePatterns.add(excludePattern); } else if (paramName.startsWith("maxWaitMilliseconds.")) { String durationString = paramName.substring("maxWaitMilliseconds.".length()); int endDuration = durationString.indexOf('.'); if (endDuration != -1) { durationString = durationString.substring(0, endDuration); } Long duration = Long.valueOf(durationString); Pattern waitPattern = Pattern.compile(paramValue); this.maxWaitDurations.put(waitPattern, duration); } } }

Target:
public void init(FilterConfig config) throws ServletException { Enumeration enumeration = config.getInitParameterNames(); this.excludePatterns = new LinkedList(); this.maxWaitDurations = new HashMap(); while (enumeration.hasMoreElements()) { String paramName = (String) enumeration.nextElement(); String paramValue = config.getInitParameter(paramName); if (paramName.startsWith("excludePattern")) { Pattern excludePattern = Pattern.compile(paramValue); this.excludePatterns.add(excludePattern); } else if (paramName.startsWith("maxWaitMilliseconds.")) { String durationString = paramName.substring("maxWaitMilliseconds.".length()); int endDuration = durationString.indexOf('.'); if (endDuration != -1) { durationString = durationString.substring(0, endDuration); } Long duration = Long.valueOf(durationString); Pattern waitPattern = Pattern.compile(paramValue); this.maxWaitDurations.put(waitPattern, duration); } } }
Source:
public void testPerJobWithArchive() throws Exception { final Configuration flinkConfig = createDefaultConfiguration(YarnConfigOptions.UserJarInclusion.DISABLED); final JobGraph archiveJobGraph = YarnTestArchiveJob.getArchiveJobGraph(tmp.newFolder(), flinkConfig); runTest(() -> deployPerJob(flinkConfig, archiveJobGraph, false)); }

Target:
public void testPerJobWithArchive() throws Exception { final Configuration flinkConfig = createDefaultConfiguration(YarnConfigOptions.UserJarInclusion.DISABLED); final JobGraph archiveJobGraph = YarnTestArchiveJob.getArchiveJobGraph(tmp.newFolder(), flinkConfig); runTest(() -> deployPerJob(flinkConfig, archiveJobGraph, true)); }
Source:
public void setM(Market currentMarket) { this.currentMarket = currentMarket; }

Target:
private void setM(Market currentMarket) { this.currentMarket = currentMarket; }
Source:
public Map<String, String> getServerMetadata(@ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr) { TableType tableType = Constants.validateTableType(tableTypeStr); if (tableType == TableType.REALTIME) throw new ControllerApplicationException(LOGGER, "Table type : " + tableTypeStr + " not yet supported.", Status.NOT_IMPLEMENTED); List<String> tableNamesWithType = getExistingTableNamesWithType(tableName, Constants.validateTableType(tableTypeStr)); Map<String, String> segmentsMetadata = null; try { segmentsMetadata = getSegmentsMetadataFromServer(tableNamesWithType.get(0)); } catch (InvalidConfigException e) { throw new ControllerApplicationException(LOGGER, "Failed to load segment reload status for table: " + tableName, Status.NOT_FOUND); } catch (IOException ioe) { throw new ControllerApplicationException(LOGGER, "Error parsing response to cluster config!", Response.Status.BAD_REQUEST, ioe); } if (segmentsMetadata == null) throw new ControllerApplicationException(LOGGER, "Table: " + tableName + " not found.", Status.NOT_FOUND); return segmentsMetadata; }

Target:
public String getServerMetadata(@ApiParam(value = "Name of the table", required = true) @PathParam("tableName") String tableName, @ApiParam(value = "OFFLINE|REALTIME") @QueryParam("type") String tableTypeStr) { LOGGER.info("Received a request to fetch metadata for all segments for table {}", tableName); TableType tableType = Constants.validateTableType(tableTypeStr); if (tableType == TableType.REALTIME) { throw new ControllerApplicationException(LOGGER, "Table type : " + tableTypeStr + " not yet supported.", Status.NOT_IMPLEMENTED); } String tableNameWithType = getExistingTableNamesWithType(tableName, tableType).get(0); String segmentsMetadata; try { JsonNode segmentsMetadataJson = getSegmentsMetadataFromServer(tableNameWithType); segmentsMetadata = JsonUtils.objectToPrettyString(segmentsMetadataJson); } catch (InvalidConfigException e) { throw new ControllerApplicationException(LOGGER, e.getMessage(), Status.BAD_REQUEST); } catch (IOException ioe) { throw new ControllerApplicationException(LOGGER, "Error parsing Pinot server response: " + ioe.getMessage(), Status.INTERNAL_SERVER_ERROR, ioe); } return segmentsMetadata; }
Source:
private void compareWith(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.isEmpty()) return; StagingEntry stagingEntry = (StagingEntry) selection.getFirstElement(); switch (stagingEntry.getState()) { case ADDED: case CHANGED: case REMOVED: case UNTRACKED: runCommand(ActionCommands.COMPARE_WITH_HEAD_ACTION, selection); break; case MISSING: case MODIFIED: case PARTIALLY_MODIFIED: case CONFLICTING: default: runCommand(ActionCommands.COMPARE_WITH_INDEX_ACTION, selection); } }

Target:
private void compareWith(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (selection.isEmpty()) return; StagingEntry stagingEntry = (StagingEntry) selection.getFirstElement(); switch (stagingEntry.getState()) { case ADDED: case CHANGED: case REMOVED: case UNTRACKED: runCommand(ActionCommands.COMPARE_INDEX_WITH_HEAD_ACTION, selection); break; case MISSING: case MODIFIED: case PARTIALLY_MODIFIED: case CONFLICTING: default: runCommand(ActionCommands.COMPARE_WITH_INDEX_ACTION, selection); } }
Source:
public void fetchUsers() { try { logger.info("Start fetching users from GitHub..."); List<User> users = githubApi.fetchAllOrgaMembers(); users.forEach(u -> logger.debug("fetched user: " + u.username)); users.forEach(userService::insertOrUpdate); logger.info("Finished fetching users from GitHub,"); } catch (IOException e) { logger.error("Error fetchint users from GitHub: " + e.getMessage(), e); } }

Target:
public void fetchUsers() { try { logger.info("Start fetching users from GitHub..."); List<User> users = githubApi.fetchAllOrgaMembers(); users.forEach(u -> logger.debug("fetched user: " + u.username)); users.forEach(userService::insertOrUpdate); logger.info("Finished fetching users from GitHub,"); } catch (IOException e) { logger.error("Error fetching users from GitHub: " + e.getMessage(), e); } }
Source:
public static void sendTitle(Player player, String message, int fadein, int stay, int fadeout) { try { CraftPlayer craftplayer = (CraftPlayer) player; PlayerConnection connection = craftplayer.getHandle().playerConnection; String finalmessage = message.replaceAll("&", "§"); IChatBaseComponent chatTitle = ChatSerializer.a("{\"text\": \"" + finalmessage + "\"}"); PacketPlayOutTitle title = new PacketPlayOutTitle(EnumTitleAction.TITLE, chatTitle, fadein, stay, fadeout); connection.sendPacket(title); } catch (Exception e) { TFM_Log.severe(e.getLocalizedMessage()); TFM_Log.severe("Title packet send failed. Your server jar is likely outdated."); } }

Target:
public static void sendTitle(Player player, String message, int fadein, int stay, int fadeout) { try { CraftPlayer craftplayer = (CraftPlayer) player; PlayerConnection connection = craftplayer.getHandle().playerConnection; String finalmessage = message.replaceAll("&", "§"); IChatBaseComponent chatTitle = ChatSerializer.a("{\"text\": \"" + finalmessage + "\"}"); PacketPlayOutTitle title = new PacketPlayOutTitle(EnumTitleAction.TITLE, chatTitle, fadein, stay, fadeout); connection.sendPacket(title); } catch (Exception e) { TFM_Log.severe("Title packet failed to send for player: " + player.getName()); TFM_Log.severe(e.getStackTrace().toString()); } }
Source:
public void should_apply_up_and_down_topology_events_when_ignored() { driverContext .loadBalancingPolicyWrapper() .setDistance(metadataRegularNode, NodeDistance.IGNORED); ConditionChecker.checkThat(() -> metadataRegularNode.getOpenConnections() == 0) .as("Driver closed all connections") .before(10, TimeUnit.SECONDS) .becomesTrue(); assertThat(metadataRegularNode).hasState(NodeState.UP).isNotReconnecting(); driverContext .eventBus() .fire(TopologyEvent.suggestDown(metadataRegularNode.getConnectAddress())); ConditionChecker.checkThat( () -> metadataRegularNode.getState() == NodeState.DOWN && metadataRegularNode.getDistance() == NodeDistance.IGNORED && metadataRegularNode.getOpenConnections() == 0 && !metadataRegularNode.isReconnecting()) .as("SUGGEST_DOWN event applied") .before(10, TimeUnit.SECONDS) .becomesTrue(); driverContext.eventBus().fire(TopologyEvent.suggestUp(metadataRegularNode.getConnectAddress())); ConditionChecker.checkThat( () -> metadataRegularNode.getState() == NodeState.UP && metadataRegularNode.getDistance() == NodeDistance.IGNORED && metadataRegularNode.getOpenConnections() == 0 && !metadataRegularNode.isReconnecting()) .as("SUGGEST_UP event applied") .before(10, TimeUnit.SECONDS) .becomesTrue(); }

Target:
public void should_apply_up_and_down_topology_events_when_ignored() { driverContext .loadBalancingPolicyWrapper() .setDistance(metadataRegularNode, NodeDistance.IGNORED); ConditionChecker.checkThat( () -> assertThat(metadataRegularNode) .isUp() .isIgnored() .hasOpenConnections(0) .isNotReconnecting()) .as("Driver closed all connections to ignored node") .before(10, TimeUnit.SECONDS) .becomesTrue(); driverContext .eventBus() .fire(TopologyEvent.suggestDown(metadataRegularNode.getConnectAddress())); ConditionChecker.checkThat( () -> assertThat(metadataRegularNode) .isDown() .isIgnored() .hasOpenConnections(0) .isNotReconnecting()) .as("SUGGEST_DOWN event applied") .before(10, TimeUnit.SECONDS) .becomesTrue(); driverContext.eventBus().fire(TopologyEvent.suggestUp(metadataRegularNode.getConnectAddress())); ConditionChecker.checkThat( () -> assertThat(metadataRegularNode) .isUp() .isIgnored() .hasOpenConnections(0) .isNotReconnecting()) .as("SUGGEST_UP event applied") .before(10, TimeUnit.SECONDS) .becomesTrue(); }
Source:
public void unsubscribe() { mCompositeSubscription.unsubscribe(); }

Target:
public void unsubscribe() { compositeSubscription.unsubscribe(); }
Source:
public static SafeHtml sanitizeHtml(String html) { if (html == null) { html = ""; } return SafeHtmlUtils.fromTrustedString(dialogSanitize(html)); }

Target:
public static SafeHtml sanitizeHtml(String html) { if (StringUtil.isNullOrEmpty(html)) { html = ""; } return SafeHtmlUtils.fromTrustedString(dialogSanitize(html)); }
Source:
public String execute() throws Exception { ActionContext previous = ActionContext.getContext(); ActionContext.bound(invocation.getInvocationContext()); try { return invocation.invoke(); } finally { if (cleanupContext) ActionContext.bound(previous); } }

Target:
public String execute() throws Exception { ActionContext previous = ActionContext.getContext(); ActionContext.bind(invocation.getInvocationContext()); try { return invocation.invoke(); } finally { if (cleanupContext) ActionContext.bind(previous); } }
Source:
private synchronized ResourceBundle getResourceBundle(Locale locale) { try { if (!resourceBundlesByLocale.containsKey(locale)) { resourceBundlesByLocale.put(locale, ResourceBundle.getBundle(messageSource, locale)); } } catch (RuntimeException e) { log.error("File: '{}' could not be loaded: {}", messageSource, e.getMessage()); log.debug("Exception", e); } return resourceBundlesByLocale.get(locale); }

Target:
private ResourceBundle getResourceBundle(Locale locale) { try { if (!resourceBundlesByLocale.containsKey(locale)) { resourceBundlesByLocale.put(locale, ResourceBundle.getBundle(messageSource, locale)); } } catch (RuntimeException e) { log.error("File: '{}' could not be loaded: {}", messageSource, e.getMessage()); log.debug("Exception", e); } return resourceBundlesByLocale.get(locale); }
Source:
public void validateSpaceAndThreshold() { AddVmCommand<VmManagementParametersBase> command = setupCanAddVmTests(0, 0); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(ValidationResult.VALID).when(storageDomainValidator).hasSpaceForNewDisks(any(List.class)); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertTrue(command.validateSpaceRequirements()); verify(storageDomainValidator, times(TOTAL_NUM_DOMAINS)).hasSpaceForNewDisks(any(List.class)); verify(storageDomainValidator, never()).hasSpaceForClonedDisks(any(List.class)); }

Target:
public void validateSpaceAndThreshold() { AddVmCommand<VmManagementParametersBase> command = setupCanAddVmTests(0, 0); doReturn(ValidationResult.VALID).when(storageDomainValidator).isDomainWithinThresholds(); doReturn(ValidationResult.VALID).when(storageDomainValidator).hasSpaceForNewDisks(anyList()); doReturn(storageDomainValidator).when(command).createStorageDomainValidator(any(StorageDomain.class)); assertTrue(command.validateSpaceRequirements()); verify(storageDomainValidator, times(TOTAL_NUM_DOMAINS)).hasSpaceForNewDisks(anyList()); verify(storageDomainValidator, never()).hasSpaceForClonedDisks(anyList()); }
Source:
protected void setNotificationSender(NotificationSender notificationSender) { if (log.isDebugEnabled()) { log.debug("Un-setting notification sender in Entitlement bundle"); } this.notificationSender = notificationSender; }

Target:
protected void setNotificationSender(NotificationSender notificationSender) { if (log.isDebugEnabled()) { log.debug("Un-setting notification sender"); } TOTPManagerComponent.notificationSender = notificationSender; }