auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void findDocWhichDoesNotExist() { couchbaseTemplate.findById(User.class).one(UUID.randomUUID().toString()); }

Target:
void findDocWhichDoesNotExist() { assertNull(couchbaseTemplate.findById(User.class).one(UUID.randomUUID().toString())); }
Source:
public Rectangle getBoundingBox() { return (Rectangle) getValue("boundingBox"); }

Target:
public Rectangle getBoundingBox() { return (Rectangle) getValue("bounding_box"); }
Source:
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) { boolean isHttpAnnotation = false; for (Annotation annotation : annotations) { Class<? extends Annotation> annotationType = annotation.annotationType(); if (annotationType == Param.class) { final Param paramAnnotation = (Param) annotation; String name = paramAnnotation.value(); checkState(emptyToNull(name) != null, "Param annotation was empty on param %s.", paramIndex); nameParam(data, name, paramIndex); Class<? extends Param.Expander> expander = paramAnnotation.expander(); if (expander != Param.ToStringExpander.class) { data.indexToExpanderClass().put(paramIndex, expander); } data.indexToEncoded().put(paramIndex, paramAnnotation.encoded()); isHttpAnnotation = true; String varName = '{' + name + '}'; if (!data.template().url().contains(varName) && !searchMapValuesContainsSubstring(data.template().queries(), varName) && !searchMapValuesContainsSubstring(data.template().headers(), varName)) { data.formParams().add(name); } } else if (annotationType == QueryMap.class) { checkState(data.queryMapIndex() == null, "QueryMap annotation was present on multiple parameters."); data.queryMapIndex(paramIndex); data.queryMapEncoded(QueryMap.class.cast(annotation).encoded()); isHttpAnnotation = true; } else if (annotationType == HeaderMap.class) { checkState(data.headerMapIndex() == null, "HeaderMap annotation was present on multiple parameters."); data.headerMapIndex(paramIndex); isHttpAnnotation = true; } } return isHttpAnnotation; }

Target:
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) { boolean isHttpAnnotation = false; for (Annotation annotation : annotations) { Class<? extends Annotation> annotationType = annotation.annotationType(); if (annotationType == Param.class) { Param paramAnnotation = (Param) annotation; String name = paramAnnotation.value(); checkState(emptyToNull(name) != null, "Param annotation was empty on param %s.", paramIndex); nameParam(data, name, paramIndex); Class<? extends Param.Expander> expander = paramAnnotation.expander(); if (expander != Param.ToStringExpander.class) { data.indexToExpanderClass().put(paramIndex, expander); } data.indexToEncoded().put(paramIndex, paramAnnotation.encoded()); isHttpAnnotation = true; String varName = '{' + name + '}'; if (!data.template().url().contains(varName) && !searchMapValuesContainsSubstring(data.template().queries(), varName) && !searchMapValuesContainsSubstring(data.template().headers(), varName)) { data.formParams().add(name); } } else if (annotationType == QueryMap.class) { checkState(data.queryMapIndex() == null, "QueryMap annotation was present on multiple parameters."); data.queryMapIndex(paramIndex); data.queryMapEncoded(QueryMap.class.cast(annotation).encoded()); isHttpAnnotation = true; } else if (annotationType == HeaderMap.class) { checkState(data.headerMapIndex() == null, "HeaderMap annotation was present on multiple parameters."); data.headerMapIndex(paramIndex); isHttpAnnotation = true; } } return isHttpAnnotation; }
Source:
public FormValidation doTestConnection(@QueryParameter String name, @QueryParameter String serverUrl, @QueryParameter String credentialsId, @QueryParameter String serverCertificate, @QueryParameter boolean skipTlsVerify, @QueryParameter String namespace, @QueryParameter int connectionTimeout, @QueryParameter int readTimeout) throws Exception { if (StringUtils.isBlank(name)) return FormValidation.error("name is required"); try { KubernetesClient client = new KubernetesFactoryAdapter(serverUrl, namespace, Util.fixEmpty(serverCertificate), Util.fixEmpty(credentialsId), skipTlsVerify, connectionTimeout, readTimeout).createClient(); client.pods().list(); Pod pod = client.pods().create(new PodBuilder() .withNewMetadata().withGenerateName("kubernetes-plugin-").endMetadata() .withNewSpec() .withContainers( new ContainerBuilder().withName("alpine").withImage("alpine").withCommand("cat") .withTty(true).build()) .endSpec().build()); String podName = pod.getMetadata().getName(); LOGGER.log(Level.FINE, "Created test pod: {0}/{1}", new String[] { pod.getMetadata().getNamespace(), podName }); client.pods().withName(podName).waitUntilReady(30, TimeUnit.SECONDS); client.pods().withName(podName).delete(); return FormValidation.ok("Connection test successful"); } catch (KubernetesClientException e) { LOGGER.log(Level.FINE, String.format("Error testing connection %s", serverUrl), e); return FormValidation.error("Error testing connection %s: %s", serverUrl, e.getCause() == null ? e.getMessage() : String.format("%s: %s", e.getCause().getClass().getName(), e.getCause().getMessage())); } catch (Exception e) { LOGGER.log(Level.FINE, String.format("Error testing connection %s", serverUrl), e); return FormValidation.error("Error testing connection %s: %s", serverUrl, e.getMessage()); } }

Target:
public FormValidation doTestConnection(@QueryParameter String name, @QueryParameter String serverUrl, @QueryParameter String credentialsId, @QueryParameter String serverCertificate, @QueryParameter boolean skipTlsVerify, @QueryParameter String namespace, @QueryParameter int connectionTimeout, @QueryParameter int readTimeout) throws Exception { if (StringUtils.isBlank(name)) return FormValidation.error("name is required"); try { KubernetesClient client = new KubernetesFactoryAdapter(serverUrl, namespace, Util.fixEmpty(serverCertificate), Util.fixEmpty(credentialsId), skipTlsVerify, connectionTimeout, readTimeout).createClient(); client.pods().list(); return FormValidation.ok("Connection test successful"); } catch (KubernetesClientException e) { LOGGER.log(Level.FINE, String.format("Error testing connection %s", serverUrl), e); return FormValidation.error("Error testing connection %s: %s", serverUrl, e.getCause() == null ? e.getMessage() : String.format("%s: %s", e.getCause().getClass().getName(), e.getCause().getMessage())); } catch (Exception e) { LOGGER.log(Level.FINE, String.format("Error testing connection %s", serverUrl), e); return FormValidation.error("Error testing connection %s: %s", serverUrl, e.getMessage()); } }
Source:
private Optional<TableToSweep> getTableToSweep() { return specificTableSweeper.getTxManager().runTaskWithRetry( new TransactionTask<Optional<TableToSweep>, RuntimeException>() { @Override public Optional<TableToSweep> execute(Transaction tx) { Optional<SweepProgress> progress = specificTableSweeper.getSweepProgressStore().loadProgress( tx); if (progress.isPresent()) { log.info("Sweeping another batch of table: {}.", LoggingArgs.tableRef("table name", progress.get().tableRef())); return Optional.of(new TableToSweep(progress.get().tableRef(), progress.get())); } else { Optional<TableReference> nextTable = nextTableToSweepProvider.chooseNextTableToSweep( tx, specificTableSweeper.getSweepRunner().getConservativeSweepTimestamp()); if (nextTable.isPresent()) { log.info("Now starting to sweep next table: {}.", LoggingArgs.tableRef("table name", nextTable.get())); return Optional.of(new TableToSweep(nextTable.get(), null)); } else { return Optional.empty(); } } } }); }

Target:
private Optional<TableToSweep> getTableToSweep() { return specificTableSweeper.getTxManager().runTaskWithRetry( new TransactionTask<Optional<TableToSweep>, RuntimeException>() { @Override public Optional<TableToSweep> execute(Transaction tx) { Optional<SweepProgress> progress = specificTableSweeper.getSweepProgressStore().loadProgress( tx); if (progress.isPresent()) { log.info("Sweeping another batch of table: {}. Batch starts on row {}", LoggingArgs.tableRef("table name", progress.get().tableRef()), UnsafeArg.of("startRow", progress.get().startRow())); return Optional.of(new TableToSweep(progress.get().tableRef(), progress.get())); } else { Optional<TableReference> nextTable = nextTableToSweepProvider.chooseNextTableToSweep( tx, specificTableSweeper.getSweepRunner().getConservativeSweepTimestamp()); if (nextTable.isPresent()) { log.info("Now starting to sweep next table: {}.", LoggingArgs.tableRef("table name", nextTable.get())); return Optional.of(new TableToSweep(nextTable.get(), null)); } else { return Optional.empty(); } } } }); }
Source:
public void showOrUpdateNotification(int id, int progressInPercent) { NotificationData notificationData = notificationDataMap.get(id); if (notificationData == null) { return; } notificationData.setProgressInPercent(progressInPercent); if (progressInPercent < 100) { notificationManager.notify(id, notificationData.toNotification(context, CHANNEL_ID)); } else { notificationData.setProgressInPercent(0); notificationData.setMaxProgress(0); notificationData.setAutoCancel(true); notificationData.setOngoing(false); notificationManager.notify(id, notificationData.toNotification(context, CHANNEL_ID)); } }

Target:
public void showOrUpdateNotification(int id, int progressInPercent) { NotificationData notificationData = notificationDataMap.get(id); if (notificationData == null) { Log.w(TAG, "Notification with id " + id + "not present in notificationDataMap"); return; } notificationData.setProgressInPercent(progressInPercent); if (progressInPercent < MAX_PERCENT) { notificationManager.notify(id, notificationData.toNotification(context, CHANNEL_ID)); } else { notificationData.setProgressInPercent(0); notificationData.setMaxProgress(0); notificationData.setAutoCancel(true); notificationData.setOngoing(false); notificationManager.notify(id, notificationData.toNotification(context, CHANNEL_ID)); } }
Source:
public boolean hasPermission(final String owner, final String activity, final String target) { if (owner == null || activity == null) { return false; } final HttpServletRequest currentRequest = portalRequestUtils.getCurrentPortalRequest(); final IPerson currentUser = personManager.getPerson((HttpServletRequest) currentRequest); final IAuthorizationPrincipal authPrincipal = this.getUserPrincipal(currentUser.getUserName()); final boolean rslt = authPrincipal != null ? authPrincipal.hasPermission(owner, activity, target) : false; logger.info(String.format("BEACH Test: in XAHBean.hasPermission: owner=[%s], activity=[%s], target=[%s], result=[%s] ", owner, activity, target, rslt)); return rslt; }

Target:
public boolean hasPermission(final String owner, final String activity, final String target) { if (owner == null || activity == null) { return false; } final HttpServletRequest currentRequest = portalRequestUtils.getCurrentPortalRequest(); final IPerson currentUser = personManager.getPerson((HttpServletRequest) currentRequest); final IAuthorizationPrincipal authPrincipal = this.getUserPrincipal(currentUser.getUserName()); final boolean rslt = authPrincipal != null ? authPrincipal.hasPermission(owner, activity, target) : false; if (this.logger.isTraceEnabled()) { logger.trace( String.format( "In hasPermission() - owner=[%s], activity=[%s], target=[%s], result=[%s] ", owner, activity, target, rslt)); } return rslt; }
Source:
public ActionForward render(final ActionMapping mapping, final ActionForm form, final PortletConfig config, final RenderRequest req, final RenderResponse res) throws Exception { Logger.debug(ViewContentletAction.class, "Running ViewContentletsAction!!!!"); try { final User user = _getUser(req); _viewContentlets(req, user); return mapping.findForward("portlet.ext.contentlet.view_contentlets"); } catch (final Exception e) { req.setAttribute(PageContext.EXCEPTION, e); return mapping.findForward(Constants.COMMON_ERROR); } }

Target:
public ActionForward render(final ActionMapping mapping, final ActionForm form, final PortletConfig config, final RenderRequest req, final RenderResponse res) throws Exception { Logger.debug(ViewContentletAction.class, "Running ViewContentletsAction!!!!"); try { final User user = _getUser(req); _viewContentlets(req, user); return mapping.findForward("portlet.ext.contentlet.view_contentlets"); } catch (final Exception e) { Logger.debug(this,e.getMessage()); req.setAttribute(PageContext.EXCEPTION, e); return mapping.findForward(Constants.COMMON_ERROR); } }
Source:
} catch (final IOException e) { e.printStackTrace(); }

Target:
} catch (final IOException e) { LOGGER.error("Failed to retrieve product version", e); }
Source:
public Iterable<HTInterval> iterable2D(IntegerRangeCondition quarks, TimeRangeCondition times) { fRwl.readLock().lock(); try (TraceCompassLogUtils.ScopeLog log = new TraceCompassLogUtils.ScopeLog(LOGGER, Level.FINEST, "HTNode:query2D", "quarks", quarks, "times", times)) { if (getNodeStart() > getNodeEnd()) { return Collections.emptyList(); } long start = times.min(); return Iterables.filter(fIntervals.subList(getStartIndexFor(start), fIntervals.size()), interval -> quarks.test(interval.getAttribute()) && times.intersects(interval.getStartTime(), interval.getEndTime())); } finally { fRwl.readLock().unlock(); } }

Target:
public Iterable<HTInterval> iterable2D(IntegerRangeCondition quarks, TimeRangeCondition times) { fRwl.readLock().lock(); try (TraceCompassLogUtils.ScopeLog log = new TraceCompassLogUtils.ScopeLog(LOGGER, Level.FINEST, "HTNode:query2D", "quarks", quarks, "times", times)) { IntegerRangeCondition subQuarks = quarks.subCondition(fMinQuark, fMaxQuark); if (subQuarks == null) { return Collections.emptyList(); } TimeRangeCondition subTimes = times.subCondition(fNodeStart, fNodeEnd); if (subTimes == null) { return Collections.emptyList(); } long start = subTimes.min(); List<HTInterval> intervals = new ArrayList<>(); for (HTInterval interval : fIntervals.subList(getStartIndexFor(start), fIntervals.size())) { if (subQuarks.test(interval.getAttribute()) && subTimes.intersects(interval.getStartTime(), interval.getEndTime())) { intervals.add(interval); } } return intervals; } finally { fRwl.readLock().unlock(); } }
Source:
public static void cleanup() { QueryManager queryMgr = IOTestUtil.db.newQueryManager(); DeleteQueryDefinition deletedef = queryMgr.newDeleteDefinition(); deletedef.setCollections(collectionName); queryMgr.delete(deletedef); IOTestUtil.db.release(); }

Target:
public static void cleanup() { QueryManager queryMgr = IOTestUtil.db.newQueryManager(); DeleteQueryDefinition deletedef = queryMgr.newDeleteDefinition(); deletedef.setCollections(collectionName); queryMgr.delete(deletedef); }
Source:
public void testThereCanBeOnlyOne() throws IOException, InterruptedException { ExecutorService service = Executors.newFixedThreadPool(20); Collection<Callable<Boolean>> list = Lists.newArrayList(); final Set<Integer> testSet = Sets.newHashSet(); for (int i = 0; i < 40; i++) { list.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { CompressionCodec codec = Compression.Algorithm.GZ.getCodec(); Assert.assertNotNull(codec); testSet.add(System.identityHashCode(codec)); return true; } }); } service.invokeAll(list); Assert.assertEquals(1, testSet.size()); service.shutdown(); }

Target:
public void testThereCanBeOnlyOne() throws IOException, InterruptedException { ExecutorService service = Executors.newFixedThreadPool(20); ArrayList<Callable<Boolean>> list = Lists.newArrayList(); final HashSet<Integer> testSet = Sets.newHashSet(); for (int i = 0; i < 40; i++) { list.add(new Callable<Boolean>() { @Override public Boolean call() throws Exception { CompressionCodec codec = Compression.Algorithm.GZ.getCodec(); Assert.assertNotNull(codec); testSet.add(System.identityHashCode(codec)); return true; } }); } service.invokeAll(list); Assert.assertEquals(1, testSet.size()); service.shutdown(); }
Source:
public GitSubscriberMergeContext(final GitResourceVariantTreeSubscriber subscriber, ISynchronizationScopeManager manager, GitSynchronizeDataSet gsds) { super(subscriber, manager); this.gsds = gsds; repoChangeListener = new RepositoryChangeListener() { public void repositoryChanged(RepositoryMapping which) { handleRepositoryChange(subscriber, which); } }; resourceChangeListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { if (event.getDelta() == null) return; int mask = IResourceDelta.ADDED | IResourceDelta.CHANGED | IResourceDelta.REMOVED | IResourceDelta.CONTENT; IResourceDelta[] affectedChildren = event.getDelta() .getAffectedChildren(mask); RepositoryMapping repo = null; for (IResourceDelta delta : affectedChildren) { if (repo == null) repo = RepositoryMapping.getMapping(delta.getResource()); if (repo != null) handleResourceChange(subscriber, repo, delta.getResource()); } } }; GitProjectData.addRepositoryChangeListener(repoChangeListener); ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener); initialize(); }

Target:
public GitSubscriberMergeContext(final GitResourceVariantTreeSubscriber subscriber, ISynchronizationScopeManager manager, GitSynchronizeDataSet gsds) { super(subscriber, manager); this.gsds = gsds; repoChangeListener = new RepositoryChangeListener() { public void repositoryChanged(RepositoryMapping which) { handleRepositoryChange(subscriber, which); } }; resourceChangeListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { if (event.getDelta() == null) return; int mask = IResourceDelta.ADDED | IResourceDelta.CHANGED | IResourceDelta.REMOVED; IResourceDelta[] affectedChildren = event.getDelta() .getAffectedChildren(mask); for (IResourceDelta delta : affectedChildren) { IResource resource = delta.getResource(); RepositoryMapping repo = RepositoryMapping.getMapping(resource); if (repo != null) handleResourceChange(subscriber, repo, resource); } } }; GitProjectData.addRepositoryChangeListener(repoChangeListener); ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener); initialize(); }
Source:
public void writeTime( long nanosOfDayUTC, int offsetSeconds ) throws IOException { packStructHeader( 2, TIME ); pack( TimeConstants.asValidLocalTime( nanosOfDayUTC ) ); pack( offsetSeconds ); }

Target:
public void writeTime( long nanosOfDayUTC, int offsetSeconds ) throws IOException { packStructHeader( 2, TIME ); pack( TimeUtil.nanosOfDayToLocal( nanosOfDayUTC, offsetSeconds ) ); pack( offsetSeconds ); }
Source:
private void issueIfLineMismatch(SyntaxToken curlyBrace, SyntaxToken target) { CodeLine curlyBraceLine = new CodeLine(curlyBrace.line()); if (curlyBraceLine.isJustBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of the previous line."))); } if (curlyBraceLine.isFarBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of line " + target.line() + "."))); } }

Target:
private void issueIfLineMismatch(SyntaxToken curlyBrace, SyntaxToken target) { CodeLine curlyBraceLine = new CodeLine(curlyBrace.line()); if (curlyBraceLine.isJustBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of the previous line."))); } else if (curlyBraceLine.isFarBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of line " + target.line() + "."))); } }
Source:
public String getUrl(int requestId, CheckerInfo checkerInfo) { String pairId = checkerInfo.getCurrencyPairId(); if(checkerInfo.getCurrencyPairId() == null) { pairId = String.format("%1$s-%2$s", checkerInfo.getCurrencyCounterLowerCase(), checkerInfo.getCurrencyBaseLowerCase()); } return String.format(URL, pairId); }

Target:
public String getUrl(int requestId, CheckerInfo checkerInfo) { return String.format(URL, checkerInfo.getCurrencyPairId()); }
Source:
public void onEventMainThread(@NonNull AccountDataLoadedEvent event) { if (imageView != null) { final Account account = event.getAccount(); if (account.getUsername().equalsIgnoreCase(profile.username)) { profileImage = account.getProfileImage(); loadProfileImage(account.getProfileImage(), imageView); } } }

Target:
public void onEventMainThread(@NonNull AccountDataLoadedEvent event) { final Account account = event.getAccount(); if (account.getUsername().equalsIgnoreCase(profile.username)) { profileImage = account.getProfileImage(); if (imageView != null) { loadProfileImage(account.getProfileImage(), imageView); } } }
Source:
public String post(String url, String postBody, Bundle headers, boolean isPatchRequest) throws ParseException, ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = null; if (isPatchRequest) { post = new HttpPatch(url); } else { post = new HttpPost(url); } AndroidHttpClient.modifyRequestToAcceptGzipResponse(post); if (headers != null) { for (String key : headers.keySet()) { post.addHeader(key, headers.getString(key)); } } StringEntity se = new StringEntity(postBody); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 ){ logger.debug("Response of HTTP " + statusCode); JSONObject json = new JSONObject(); try { json.put("error", String.valueOf(statusCode)); } catch (JSONException e) { logger.error(e); } client.getConnectionManager().shutdown(); return json.toString(); } InputStream inputStream = AndroidHttpClient .getUngzippedContent(response.getEntity()); String strRes = IOUtils.toString(inputStream); client.getConnectionManager().shutdown(); return strRes; }

Target:
public String post(String url, String postBody, Bundle headers, boolean isPatchRequest) throws ParseException, ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = null; if (isPatchRequest) { post = new HttpPatch(url); } else { post = new HttpPost(url); } AndroidHttpClient.modifyRequestToAcceptGzipResponse(post); if (headers != null) { for (String key : headers.keySet()) { post.addHeader(key, headers.getString(key)); } } StringEntity se = new StringEntity(postBody); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK ){ logger.debug("Response of HTTP " + statusCode); JSONObject json = new JSONObject(); try { json.put("error", String.valueOf(statusCode)); } catch (JSONException e) { logger.error(e); } client.getConnectionManager().shutdown(); return json.toString(); } InputStream inputStream = AndroidHttpClient .getUngzippedContent(response.getEntity()); String strRes = IOUtils.toString(inputStream); client.getConnectionManager().shutdown(); return strRes; }
Source:
public DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, DiscoveryClientOptionalArgs args) { this(applicationInfoManager, config, args, new Provider<BackupRegistry>() { @Override public BackupRegistry get() { String backupRegistryClassName = clientConfig.getBackupRegistryImpl(); if (null != backupRegistryClassName) { try { return (BackupRegistry) Class.forName(backupRegistryClassName).newInstance(); } catch (InstantiationException e) { logger.error("Error instantiating BackupRegistry.", e); } catch (IllegalAccessException e) { logger.error("Error instantiating BackupRegistry.", e); } catch (ClassNotFoundException e) { logger.error("Error instantiating BackupRegistry.", e); } } logger.warn("Using default backup registry implementation which does not do anything."); return new NotImplementedRegistryImpl(); } }); }

Target:
public DiscoveryClient(ApplicationInfoManager applicationInfoManager, EurekaClientConfig config, DiscoveryClientOptionalArgs args) { this(applicationInfoManager, config, args, new Provider<BackupRegistry>() { private volatile BackupRegistry backupRegistryInstance; @Override public synchronized BackupRegistry get() { if (backupRegistryInstance == null) { String backupRegistryClassName = clientConfig.getBackupRegistryImpl(); if (null != backupRegistryClassName) { try { backupRegistryInstance = (BackupRegistry) Class.forName(backupRegistryClassName).newInstance(); } catch (InstantiationException e) { logger.error("Error instantiating BackupRegistry.", e); } catch (IllegalAccessException e) { logger.error("Error instantiating BackupRegistry.", e); } catch (ClassNotFoundException e) { logger.error("Error instantiating BackupRegistry.", e); } } logger.warn("Using default backup registry implementation which does not do anything."); backupRegistryInstance = new NotImplementedRegistryImpl(); } return backupRegistryInstance; } }); }
Source:
public void testOptionalConfigurationOptions() { String configStr = "config.amqp {" + " host = \"" + host + "\"\n" + " port = \"" + port + "\"\n" + " groupId = \"" + groupId + "\"\n" + " durable = " + durable + "\n" + " consumerThreadPoolSize = " + consumerThreadPoolSize + "\n" + "}"; Config amqpConfig = ConfigFactory.parseString(configStr).getConfig("config.amqp"); ; AmqpBrokerConfigBuilder brokerConfigBuilder = new AmqpBrokerConfigBuilder(amqpConfig); AmqpBrokerConfig brokerConfig = brokerConfigBuilder.build(); assertFalse(brokerConfig.getUsername().isPresent()); assertFalse(brokerConfig.getPassword().isPresent()); assertFalse(brokerConfig.getVirtualHost().isPresent()); }

Target:
public void testOptionalConfigurationOptions() { String configStr = "config.amqp {" + " host = \"" + host + "\"\n" + " port = \"" + port + "\"\n" + " groupId = \"" + groupId + "\"\n" + " durable = " + durable + "\n" + " consumerThreadPoolSize = " + consumerThreadPoolSize + "\n" + "}"; Config amqpConfig = ConfigFactory.parseString(configStr).getConfig("config.amqp"); AmqpBrokerConfigBuilder brokerConfigBuilder = new AmqpBrokerConfigBuilder(amqpConfig); AmqpBrokerConfig brokerConfig = brokerConfigBuilder.build(); assertFalse(brokerConfig.getUsername().isPresent()); assertFalse(brokerConfig.getPassword().isPresent()); assertFalse(brokerConfig.getVirtualHost().isPresent()); }
Source:
public static void initializeSourceViewerColors(ISourceViewer viewer) { IPreferenceStore store = getPreferenceStore(); if (store != null) { StyledText styledText = viewer.getTextWidget(); Color color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND); styledText.setForeground(color); color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); styledText.setBackground(color); color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND); styledText.setSelectionForeground(color); color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND); styledText.setSelectionBackground(color); IFindReplaceTarget target = viewer.getFindReplaceTarget(); if (target instanceof IFindReplaceTargetExtension) ((IFindReplaceTargetExtension) target) .setScopeHighlightColor(getColor(AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE)); } }

Target:
public static void initializeSourceViewerColors(ISourceViewer viewer) { IPreferenceStore store = getPreferenceStore(); if (null != store) { StyledText styledText = viewer.getTextWidget(); Color color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND); styledText.setForeground(color); color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND); styledText.setBackground(color); color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND); styledText.setSelectionForeground(color); color = store.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND_SYSTEM_DEFAULT) ? null : getColor(AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND); styledText.setSelectionBackground(color); IFindReplaceTarget target = viewer.getFindReplaceTarget(); if (target instanceof IFindReplaceTargetExtension) { ((IFindReplaceTargetExtension) target) .setScopeHighlightColor(getColor(AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE)); } } }
Source:
private JsonCreateReceiptsResponse toJsonCreateReceiptsResponse(@NonNull final List<InOutId> receiptIds, @NonNull final List<InOutId> returnIds) { final List<JsonMetasfreshId> jsonReceiptIds = receiptIds .stream() .map(InOutId::getRepoId) .map(JsonMetasfreshId::of) .collect(Collectors.toList()); final List<JsonMetasfreshId> jsonReturnIds = returnIds .stream() .map(InOutId::getRepoId) .map(JsonMetasfreshId::of) .collect(Collectors.toList()); return JsonCreateReceiptsResponse.builder() .createdReceiptIdList(jsonReceiptIds) .createdReturnIdList(jsonReturnIds) .build(); }

Target:
private JsonCreateReceiptsResponse toJsonCreateReceiptsResponse(@NonNull final List<InOutId> receiptIds, @NonNull final List<InOutId> returnIds) { final List<JsonMetasfreshId> jsonReceiptIds = receiptIds .stream() .map(InOutId::getRepoId) .map(JsonMetasfreshId::of) .collect(ImmutableList.toImmutableList()); final List<JsonMetasfreshId> jsonReturnIds = returnIds .stream() .map(InOutId::getRepoId) .map(JsonMetasfreshId::of) .collect(ImmutableList.toImmutableList()); return JsonCreateReceiptsResponse.builder() .createdReceiptIdList(jsonReceiptIds) .createdReturnIdList(jsonReturnIds) .build(); }
Source:
public void testDeserializeWithParams() throws Exception { String content = IOUtils.toString(resource("auditevents/auditEventWithParam.json")); final AuditEvent deserializedObject = json.readValue(content, AuditEvent.class); assertThat(deserializedObject.getParams(), is(not(Collections.emptyMap()))); }

Target:
public void testDeserializeWithParams() throws Exception { final AuditEvent deserializedObject = readObjectFromResource("/auditevents/auditEventWithParam.json", AuditEvent.class); assertThat(deserializedObject.getParams(), hasEntry("KEY", "VALUE")); }
Source:
public void executeUpgrade() throws DotDataException, DotRuntimeException { dc = new DotConnect(); try { systemRootRoleId = getSystemRootRoleId(); } catch (DotDataException e) { Logger.info(this, "Task not executing seems the roles has not been upgraded yet"); return; } List<Map<String, String>> systemRoles = getSystemRoles(); if (!containsRole(AnyoneWhoCanReadRole, systemRoles)) { insertRole(AnyoneWhoCanReadRole, AnyoneWhoCanReadRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_VIEW_ROLE_KEY); } if (!containsRole(AnyoneWhoCanEditRole, systemRoles)) { insertRole(AnyoneWhoCanEditRole, AnyoneWhoCanEditRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_ROLE_KEY); } if (!containsRole(AnyoneWhoCanPublishRole, systemRoles)) { insertRole(AnyoneWhoCanPublishRole, AnyoneWhoCanPublishRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_PUBLISH_ROLE_KEY); } if (!containsRole(AnyoneWhoCanEditPermissionsRole, systemRoles)) { insertRole(AnyoneWhoCanEditPermissionsRole, AnyoneWhoCanEditPermissionsRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_PERMISSIONS_ROLE_KEY); } }

Target:
public void executeUpgrade() throws DotDataException { dc = new DotConnect(); try { systemRootRoleId = getSystemRootRoleId(); } catch (DotDataException e) { Logger.info(this, "Task not executing seems the roles has not been upgraded yet"); return; } final List<Map<String, String>> systemRoles = getSystemRoles(); if (!containsRole(AnyoneWhoCanReadRole, systemRoles)) { insertRole(AnyoneWhoCanReadRole, AnyoneWhoCanReadRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_VIEW_ROLE_KEY); } if (!containsRole(AnyoneWhoCanEditRole, systemRoles)) { insertRole(AnyoneWhoCanEditRole, AnyoneWhoCanEditRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_ROLE_KEY); } if (!containsRole(AnyoneWhoCanPublishRole, systemRoles)) { insertRole(AnyoneWhoCanPublishRole, AnyoneWhoCanPublishRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_PUBLISH_ROLE_KEY); } if (!containsRole(AnyoneWhoCanEditPermissionsRole, systemRoles)) { insertRole(AnyoneWhoCanEditPermissionsRole, AnyoneWhoCanEditPermissionsRoleId, RoleAPI.WORKFLOW_ANY_WHO_CAN_EDIT_PERMISSIONS_ROLE_KEY); } }
Source:
private Long parseSafeLong(Map<String, Object> innerMap, String key) { return innerMap.containsKey(key) && StringUtils.isNumeric(key) ? Long.parseLong(innerMap.get(key).toString()) : null; }

Target:
private Long parseSafeLong(Map<String, Object> innerMap, String key) { return innerMap.containsKey(key) && StringUtils.isNumeric(innerMap.get(key).toString()) ? Long.parseLong(innerMap.get(key).toString()) : null; }
Source:
private void buildCalciteFns() { for (SketchDescriptor sd : sketchClasses.values()) { RelProtoDataType sketchType = RelDataTypeImpl.proto(SqlTypeName.BINARY, true); SketchFunctionDescriptor sketchSFD = sd.fnMap.get(DATA_TO_SKETCH); SketchFunctionDescriptor unionSFD = sd.fnMap.get(UNION_SKETCH); SketchFunctionDescriptor estimateSFD = sd.fnMap.get(SKETCH_TO_ESTIMATE); if (sketchSFD == null || unionSFD == null) { continue; } HiveMergeableAggregate unionFn = new HiveMergeableAggregate(unionSFD.name, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(sketchType), InferTypes.ANY_NULLABLE, OperandTypes.family(), null); HiveMergeableAggregate sketchFn = new HiveMergeableAggregate(sketchSFD.name, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(sketchType), InferTypes.ANY_NULLABLE, OperandTypes.family(), unionFn); unionSFD.setCalciteFunction(unionFn); sketchSFD.setCalciteFunction(sketchFn); if (estimateSFD != null) { SqlFunction estimateFn = new HiveSqlFunction(estimateSFD.name, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(SqlTypeName.DOUBLE), InferTypes.ANY_NULLABLE, OperandTypes.family(), SqlFunctionCategory.USER_DEFINED_FUNCTION, true, false); estimateSFD.setCalciteFunction(estimateFn); } } }

Target:
private void buildCalciteFns() { for (SketchDescriptor sd : sketchClasses.values()) { RelProtoDataType sketchType = RelDataTypeImpl.proto(SqlTypeName.BINARY, true); SketchFunctionDescriptor sketchSFD = sd.fnMap.get(DATA_TO_SKETCH); SketchFunctionDescriptor unionSFD = sd.fnMap.get(UNION_SKETCH); SketchFunctionDescriptor estimateSFD = sd.fnMap.get(SKETCH_TO_ESTIMATE); if (sketchSFD == null || unionSFD == null) { continue; } HiveMergeableAggregate unionFn = new HiveMergeableAggregate(unionSFD.name, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(sketchType), InferTypes.ANY_NULLABLE, OperandTypes.family(), null); HiveMergeableAggregate sketchFn = new HiveMergeableAggregate(sketchSFD.name, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(sketchType), InferTypes.ANY_NULLABLE, OperandTypes.family(), unionFn); unionSFD.setCalciteFunction(unionFn); sketchSFD.setCalciteFunction(sketchFn); if (estimateSFD != null && estimateSFD.getReturnRelDataType().isPresent()) { SqlFunction estimateFn = new HiveSqlFunction(estimateSFD.name, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(estimateSFD.getReturnRelDataType().get().getSqlTypeName()), InferTypes.ANY_NULLABLE, OperandTypes.family(), SqlFunctionCategory.USER_DEFINED_FUNCTION, true, false); estimateSFD.setCalciteFunction(estimateFn); } } }
Source:
private void createLiteDownloadManager() { Handler handler = new Handler(Looper.getMainLooper()); liteDownloadManagerCommands = DownloadManagerBuilder .newInstance(this, handler, R.mipmap.ic_launcher_round) .withAllowedConnectionType(ConnectionType.UNMETERED) .build(); }

Target:
private void createLiteDownloadManager() { Handler handler = new Handler(Looper.getMainLooper()); liteDownloadManagerCommands = DownloadManagerBuilder .newInstance(this, handler, R.mipmap.ic_launcher_round) .build(); }
Source:
private void readFromUrl(String url, final HttpOutputMessage output) throws IOException { try (HttpResponse conn = requestFactory.request(0, url, null, null, null, null)) { output.setStatus(conn.getResponseCode()); final String contentType = conn.getContentType(); if (contentType != null) { output.setContentType(contentType); } final String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION); if (contentDisposition != null) { output.addHttpHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); } try (InputStream in = firstNonNull(conn.getErrorStream(), conn.getInputStream()); OutputStream out = output.getOutputStream()) { ByteStreams.copy(in, out); } } }

Target:
private void readFromUrl(String url, final HttpOutputMessage output) throws IOException { try (HttpResponse conn = requestFactory.target(url).setTimeout(60 * 1000).request()) { output.setStatus(conn.getResponseCode()); final String contentType = conn.getContentType(); if (contentType != null) { output.setContentType(contentType); } final String contentDisposition = conn.getHeaderField(HttpHeaders.CONTENT_DISPOSITION); if (contentDisposition != null) { output.addHttpHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); } try (InputStream in = conn.getInputStream(); OutputStream out = output.getOutputStream()) { ByteStreams.copy(in, out); } } }
Source:
static LocaleResolver determineLocaleResolver(AbstractConfigurationImpl<?> hibernateSpecificConfig, Map<String, String> properties, ClassLoader externalClassLoader) { if ( hibernateSpecificConfig.getLocaleResolver() != null ) { LOG.usingLocaleResolver( hibernateSpecificConfig.getLocaleResolver().getClass() ); return hibernateSpecificConfig.getLocaleResolver(); } String localeResolverFqcn = properties.get( HibernateValidatorConfiguration.LOCALE_RESOLVER_CLASSNAME ); if ( localeResolverFqcn != null ) { try { @SuppressWarnings("unchecked") Class<? extends LocaleResolver> clazz = (Class<? extends LocaleResolver>) run( LoadClass.action( localeResolverFqcn, externalClassLoader ) ); LocaleResolver localeResolver = run( NewInstance.action( clazz, "locale resolver class" ) ); LOG.usingLocaleResolver( clazz ); return localeResolver; } catch (Exception e) { throw LOG.getUnableToInstantiatePropertyNodeNameProviderClassException( localeResolverFqcn, e ); } } return new DefaultLocaleResolver(); }

Target:
static LocaleResolver determineLocaleResolver(AbstractConfigurationImpl<?> hibernateSpecificConfig, Map<String, String> properties, ClassLoader externalClassLoader) { if ( hibernateSpecificConfig.getLocaleResolver() != null ) { LOG.usingLocaleResolver( hibernateSpecificConfig.getLocaleResolver().getClass() ); return hibernateSpecificConfig.getLocaleResolver(); } String localeResolverFqcn = properties.get( HibernateValidatorConfiguration.LOCALE_RESOLVER_CLASSNAME ); if ( localeResolverFqcn != null ) { try { @SuppressWarnings("unchecked") Class<? extends LocaleResolver> clazz = (Class<? extends LocaleResolver>) run( LoadClass.action( localeResolverFqcn, externalClassLoader ) ); LocaleResolver localeResolver = run( NewInstance.action( clazz, "locale resolver class" ) ); LOG.usingLocaleResolver( clazz ); return localeResolver; } catch (Exception e) { throw LOG.getUnableToInstantiateLocaleResolverClassException( localeResolverFqcn, e ); } } return new DefaultLocaleResolver(); }
Source:
public @Nullable Object getStyle(OutputElementStyle elementStyle, String property) { OutputElementStyle style = elementStyle; Stack<String> styleQueue = new Stack<>(); while (style != null) { Map<String, Object> styleValues = style.getStyleValues(); Object value = styleValues.get(property); if (value != null) { return value; } String parentKey = style.getParentKey(); if (parentKey != null) { String[] split = parentKey.split(","); styleQueue.addAll(Arrays.asList(split)); } style = styleQueue.isEmpty() ? null : fStyleMap.get(styleQueue.pop()); } return null; }

Target:
public @Nullable Object getStyle(OutputElementStyle elementStyle, String property) { OutputElementStyle style = elementStyle; Stack<String> styleQueue = new Stack<>(); while (style != null) { Map<String, Object> styleValues = style.getStyleValues(); Object value = styleValues.get(property); if (value != null) { return value; } style = popNextStyle(style, styleQueue); } return null; }
Source:
public ResponseWrapper<VacationOverviewResponse> getHolidayOverview( @RequestParam("selectedDepartment") String selectedDepartment, @RequestParam("selectedYear") Integer selectedYear, @RequestParam("selectedMonth") Integer selectedMonth) { List<VacationOverview> holidayOverviewList = vacationOverviewService.getVacationOverviews(selectedDepartment, selectedYear, selectedMonth); for (VacationOverview v: holidayOverviewList){ v.setAbsences( absenceController.personsVacations(selectedYear, selectedMonth, v.getPersonID(), null).getResponse().getAbsences() ); } return new ResponseWrapper<>(new VacationOverviewResponse(holidayOverviewList)); }

Target:
public ResponseWrapper<VacationOverviewResponse> getHolidayOverview( @RequestParam("selectedDepartment") String selectedDepartment, @RequestParam("selectedYear") Integer selectedYear, @RequestParam("selectedMonth") Integer selectedMonth) { List<VacationOverview> holidayOverviewList = vacationOverviewService.getVacationOverviews(selectedDepartment, Optional.of(selectedYear), Optional.of(selectedMonth)); return new ResponseWrapper<>(new VacationOverviewResponse(holidayOverviewList)); }
Source:
public CascadeExtractionFn( @JsonProperty("extractionFns") ExtractionFn[] extractionFn) { Preconditions.checkArgument(extractionFn != null, "extractionFns should not be null"); this.extractionFns = extractionFn; ChainedExtractionFn root = null; for (int idx = 0; idx < extractionFns.length; idx++) { if (extractionFns[idx] != null) { root = new ChainedExtractionFn(extractionFns[idx], root); } } this.chainedExtractionFn = root; }

Target:
public CascadeExtractionFn( @JsonProperty("extractionFns") ExtractionFn[] extractionFn ) { Preconditions.checkArgument(extractionFn != null, "extractionFns should not be null"); this.extractionFns = extractionFn; if (extractionFns.length == 0) { this.chainedExtractionFn = DEFAULT_CHAINED_EXTRACTION_FN; } else { ChainedExtractionFn root = null; for (int idx = 0; idx < extractionFns.length; idx++) { Preconditions.checkArgument(extractionFns[idx] != null, "empty function is not allowed"); root = new ChainedExtractionFn(extractionFns[idx], root); } this.chainedExtractionFn = root; } }
Source:
protected Void doInBackground(Bundle... p1) { sourceFiles = p1[0].getParcelableArrayList(TAG_COPY_SOURCES); totalSize = FileUtils.getTotalBytes(sourceFiles, c); totalSourceFiles = sourceFiles.size(); progressHandler.setSourceSize(totalSourceFiles); progressHandler.setTotalSize(totalSize); progressHandler.setProgressListener((speed) -> publishResults(speed, false, move)); watcherUtil = new ServiceWatcherUtil(progressHandler); try { addFirstDatapoint(sourceFiles.get(0).getName(), sourceFiles.size(), totalSize, move); } catch (IllegalStateException e) { e.printStackTrace(); return null; } targetPath = p1[0].getString(TAG_COPY_TARGET); move = p1[0].getBoolean(TAG_COPY_MOVE); openMode = OpenMode.getOpenMode(p1[0].getInt(TAG_COPY_OPEN_MODE)); copy = new Copy(); copy.execute(sourceFiles, targetPath, move, openMode); if (copy.failedFOps.size() == 0) { for (HybridFileParcelable sourceFile : sourceFiles) { try { findAndReplaceEncryptedEntry(sourceFile); } catch (Exception e) { Toast.makeText(c, getString(R.string.encryption_fail_copy), Toast.LENGTH_SHORT).show(); } } } return null; }

Target:
protected Void doInBackground(Bundle... p1) { sourceFiles = p1[0].getParcelableArrayList(TAG_COPY_SOURCES); totalSize = FileUtils.getTotalBytes(sourceFiles, c); totalSourceFiles = sourceFiles.size(); progressHandler.setSourceSize(totalSourceFiles); progressHandler.setTotalSize(totalSize); progressHandler.setProgressListener((speed) -> publishResults(speed, false, move)); watcherUtil = new ServiceWatcherUtil(progressHandler); addFirstDatapoint(sourceFiles.get(0).getName(), sourceFiles.size(), totalSize, move); targetPath = p1[0].getString(TAG_COPY_TARGET); move = p1[0].getBoolean(TAG_COPY_MOVE); openMode = OpenMode.getOpenMode(p1[0].getInt(TAG_COPY_OPEN_MODE)); copy = new Copy(); copy.execute(sourceFiles, targetPath, move, openMode); if (copy.failedFOps.size() == 0) { for (HybridFileParcelable sourceFile : sourceFiles) { try { findAndReplaceEncryptedEntry(sourceFile); } catch (Exception e) { Toast.makeText(c, getString(R.string.encryption_fail_copy), Toast.LENGTH_SHORT).show(); } } } return null; }
Source:
public PrefilledCardHolderDetails getPrefilledCardHolderDetails() { return prefilledCardHolderDetails; }

Target:
public Optional<PrefilledCardHolderDetails> getPrefilledCardHolderDetails() { return Optional.ofNullable(prefilledCardHolderDetails); }
Source:
public MessageContent(byte[] content, ContentType contentType, Optional<CompiledSchema<Schema>> schema) { this.data = content; this.contentType = contentType; this.schema = schema; }

Target:
private MessageContent(byte[] content, ContentType contentType, Optional<CompiledSchema<Schema>> schema) { this.content = content; this.contentType = contentType; this.schema = schema; }
Source:
public void testCreate() throws Exception { when(entityRef.fetchEntity()).thenReturn(entity); when(connection.getEntityRef(eq(EhcacheClientEntity.class), anyInt(), anyString())).thenReturn(entityRef); addMockUnlockedLock(connection, "VoltronReadWriteLock-EhcacheClientEntityFactory-AccessLock-test"); EhcacheClientEntityFactory factory = new EhcacheClientEntityFactory(connection); factory.create("test", null); verify(entityRef).create(any(UUID.class)); verify(entity).close(); }

Target:
public void testCreate() throws Exception { when(entityRef.fetchEntity()).thenReturn(entity); when(connection.getEntityRef(eq(EhcacheClientEntity.class), anyInt(), anyString())).thenReturn(entityRef); addMockUnlockedLock(connection, "VoltronReadWriteLock-EhcacheClientEntityFactory-AccessLock-test"); EhcacheClientEntityFactory factory = new EhcacheClientEntityFactory(connection); factory.create("test", null); verify(entityRef).create(isA(ClusteredTierManagerConfiguration.class)); verify(entity).close(); }