auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_browse_image, container, false); ButterKnife.bind(this, rootView); <START> if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { <END> depictionsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); } else { depictionsRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2)); } ArrayList<DepictedItem> items = new ArrayList<>(); depictionsAdapter = adapterFactory.create(items); depictionsRecyclerView.setAdapter(depictionsAdapter); depictionsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (!recyclerView.canScrollVertically(1)) { addDepictionsToList(query); } } }); return rootView; }</code><technical_language>getActivity(), fragment context</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_browse_image, container, false); ButterKnife.bind(this, rootView); if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { layoutManager = new LinearLayoutManager(getContext()); } else { layoutManager = new GridLayoutManager(getContext(), 2); } depictionsRecyclerView.setLayoutManager(layoutManager); depictionsAdapter = adapterFactory.create(); depictionsRecyclerView.setAdapter(depictionsAdapter); depictionsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int visibleItemCount = layoutManager.getChildCount(); int totalItemCount = layoutManager.getItemCount(); int firstVisibleItemPosition=0; if(layoutManager instanceof GridLayoutManager){ firstVisibleItemPosition=((GridLayoutManager) layoutManager).findFirstVisibleItemPosition(); } else { firstVisibleItemPosition=((LinearLayoutManager)layoutManager).findFirstVisibleItemPosition(); } if (!isLoading && !isLastPage) { if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0 && totalItemCount >= PAGE_SIZE) { loadMoreItems(false); } } } }); return rootView; }
Source:
<code><START> public void testRemoveValueUnequalStoreEntryEqualCacheWriterEntry() throws Exception { <END> final MockStore realStore = new MockStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(realStore); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "value")); final Ehcache<String, String> ehcache = this.getEhcache(realCache); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(realStore.getMap().get("key"), is(equalTo("unequalValue"))); assertThat(realCache.getEntries().get("key"), is(equalTo("value"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }</code><technical_language>Again, broken initial state - care anything</technical_language>

Target:
public void testRemoveValueUnequalStoreEntryEqualCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "unequalValue")); this.store = spy(fakeStore); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "value")); final Ehcache<String, String> ehcache = this.getEhcache(fakeWriter); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code><START> public Task<Void> delete(@NonNull Activity activity) { <END> FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if (firebaseUser == null) { return Tasks.forException(new Exception("No currently signed in user.")); } Task<Void> deleteUserTask = firebaseUser.delete(); GoogleApiClientTaskHelper gacHelper = GoogleApiClientTaskHelper.getInstance(activity); gacHelper.getBuilder().addApi(Auth.CREDENTIALS_API); OldCredentialsApiHelper credentialHelper = OldCredentialsApiHelper.getInstance(gacHelper); List<Credential> credentials = SmartLockBase.credentialsFromFirebaseUser(firebaseUser); List<Task<?>> credentialTasks = new ArrayList<>(); for (Credential credential : credentials) { credentialTasks.add(credentialHelper.delete(credential)); } final Task<Void> combinedCredentialTask = Tasks.whenAll(credentialTasks); return deleteUserTask.continueWithTask(new Continuation<Void, Task<Void>>() { @Override public Task<Void> then(@NonNull Task<Void> task) throws Exception { task.getResult(Exception.class); return combinedCredentialTask; } }); }</code><technical_language>I difference delete(FragmentActivity) delete(Activity) is CredentialApiHelper OldCredentialApiHelper. this simplified of CredentialApiHelper classes implement a common interface? I this: interface CredentialApiHelper { Task<Status> delete(Credential credential); Task<Status> disableAuthSignIn(); } delete() functions a matter of constructing proper Helper calling a private Task<Void> delete(CredentialApiHelper helper)</technical_language>

Target:
public Task<Void> delete(@NonNull Activity activity) { GoogleApiClientTaskHelper gacHelper = GoogleApiClientTaskHelper.getInstance(activity); gacHelper.getBuilder().addApi(Auth.CREDENTIALS_API); CredentialTaskApi credentialHelper = CredentialsApiHelper.getInstance(gacHelper); return getDeleteTask(credentialHelper); }
Source:
<code>public String toString() { <START> return "ListOffsetsResultInfo [offset=" + offset + ", timestamp=" + timestamp + ", leaderEpoch=" <END> + leaderEpoch + "]"; }</code><technical_language>nit: I parenthesis a more conventional</technical_language>

Target:
public String toString() { return "ListOffsetsResultInfo(offset=" + offset + ", timestamp=" + timestamp + ", leaderEpoch=" + leaderEpoch + ")"; }
Source:
<code>public void putInt(int length, int value) throws CTFReaderException { final long curPos = this.pos; if (!canRead(length)) { throw new CTFReaderException("Cannot write to bitbuffer, insufficient space. Requested: " + length); } <START> if (length == 0) { <END> return; } if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { putIntLE(curPos, length, value); } else { putIntBE(curPos, length, value); } this.pos += length; }</code><technical_language>note for other CL, I this test move if CTF accept writing a 0-bits struct (or int). I know, stupid. a separate commit</technical_language>

Target:
public void putInt(int length, int value) throws CTFReaderException { final long curPos = this.pos; if (!canRead(length)) { throw new CTFReaderException("Cannot write to bitbuffer, " + "insufficient space. Requested: " + length); } if (length == 0) { return; } if (this.byteOrder == ByteOrder.LITTLE_ENDIAN) { putIntLE(curPos, length, value); } else { putIntBE(curPos, length, value); } this.pos += length; }
Source:
<code>public AttributeTree(StateSystem ss, FileInputStream fis) throws IOException { this(ss); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis)); int res = ois.readInt(); if (res != ATTRIB_TREE_MAGIC_NUMBER) { throw new IOException("The attribute tree file section is either invalid or corrupted."); } ArrayList<String[]> attribList; try { @SuppressWarnings("unchecked") ArrayList<String[]> list = (ArrayList<String[]>) ois.readObject(); attribList = list; } catch (ClassNotFoundException e) { throw new IOException("Unrecognizable attribute list"); } <START> String[] prevFullAttribute = null, currFullAttribute = null; <END> for (String[] attrib : attribList) { currFullAttribute = (prevFullAttribute == null) ? attrib : decodeFullAttribute(prevFullAttribute, attrib); this.getQuarkAndAdd(ROOT_ATTRIBUTE, currFullAttribute); prevFullAttribute = currFullAttribute; } }</code><technical_language>Typically prefix for "current" is "cur"</technical_language>

Target:
public AttributeTree(StateSystem ss, FileInputStream fis) throws IOException { this(ss); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fis)); int res = ois.readInt(); if (res != ATTRIB_TREE_MAGIC_NUMBER) { throw new IOException("The attribute tree file section is either invalid or corrupted."); } ArrayList<@NonNull String @NonNull []> attribList; try { @SuppressWarnings("unchecked") ArrayList<@NonNull String @NonNull []> list = (ArrayList<@NonNull String @NonNull []>) ois.readObject(); attribList = list; } catch (ClassNotFoundException e) { throw new IOException("Unrecognizable attribute list"); } String[] prevFullAttribute = null, curFullAttribute = null; for (String[] attrib : attribList) { curFullAttribute = (prevFullAttribute == null) ? attrib : decodeFullAttribute(prevFullAttribute, attrib); this.getQuarkAndAdd(ROOT_ATTRIBUTE, curFullAttribute); prevFullAttribute = curFullAttribute; } }
Source:
<code>private void checkException(Exception e, String expected) { <START> System.out.println("Expecting: " + expected + ", got: " + e); <END> assertTrue(e.getMessage().contains(expected)); }</code><technical_language>need System.out.println() here. lines assertTrue("Expecting: " + expected + ", got: " + e, e.getMessage().contains(expected));</technical_language>

Target:
private void checkException(Exception e, String expected) { assertTrue(e.getMessage().contains(expected)); }
Source:
<code>public void convert() { JudgmentSeriesCriteria criteria = judgmentSeriesFilterConverter.convert(filter1); <START> assertNotNull(filter1); <END> assertCriteria(filter1, criteria); }</code><technical_language>assertNotNull(criteria);</technical_language>

Target:
public void convert() { JudgmentSeriesCriteria criteria = judgmentSeriesFilterConverter.convert(filter1); assertNotNull(criteria); assertCriteria(filter1, criteria); }
Source:
<code>public void stop() { if (!isStopping() && !isStopped()) { try { super.stop(); } catch (Exception e) { throw wrapRuntimeCamelException(e); } } else { <START> LOG.trace("Ignoring maybeStop() as Apache Camel is already stopped"); <END> } }</code><technical_language>btw tend write Camel instead of Apache Camel in log messages, do that. Yeah friday 'bike shed' day ;)</technical_language>

Target:
public void stop() { if (!isStopping() && !isStopped()) { try { super.stop(); } catch (Exception e) { throw wrapRuntimeCamelException(e); } } else { LOG.trace("Ignoring stop() as Camel is already stopped"); } }
Source:
<code>private void initReplLoad(ASTNode ast) throws HiveException { path = PlanUtils.stripQuotes(ast.getChild(0).getText()); int numChildren = ast.getChildCount(); for (int i = 1; i < numChildren; i++) { ASTNode childNode = (ASTNode) ast.getChild(i); switch (childNode.getToken().getType()) { case TOK_DBNAME: dbNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); for (String dbName : Utils.matchesDb(db, dbNameOrPattern)) { Database database = db.getDatabase(dbName); if (database != null) { if (ReplChangeManager.isSourceOfReplication(database)) { LOG.error("Cannot load database " + dbName + " as it is a source of replication"); <START> throw new SemanticException(ErrorMsg.REPL_TARGET_IS_THE_SOURCE_OF_REPLICATION.getMsg()); <END> } } } break; case TOK_TABNAME: tblNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); break; case TOK_REPL_CONFIG: Map<String, String> replConfigs = DDLSemanticAnalyzer.getProps((ASTNode) childNode.getChild(0)); if (null != replConfigs) { for (Map.Entry<String, String> config : replConfigs.entrySet()) { conf.set(config.getKey(), config.getValue()); } try { db = Hive.get(conf); } catch (HiveException e) { throw new SemanticException(e); } } break; default: throw new SemanticException("Unrecognized token in REPL LOAD statement"); } } }</code><technical_language>do need fail for this case? enough ensure, overwrite this property load</technical_language>

Target:
private void initReplLoad(ASTNode ast) throws SemanticException { path = PlanUtils.stripQuotes(ast.getChild(0).getText()); int numChildren = ast.getChildCount(); for (int i = 1; i < numChildren; i++) { ASTNode childNode = (ASTNode) ast.getChild(i); switch (childNode.getToken().getType()) { case TOK_DBNAME: dbNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); break; case TOK_TABNAME: tblNameOrPattern = PlanUtils.stripQuotes(childNode.getChild(0).getText()); break; case TOK_REPL_CONFIG: Map<String, String> replConfigs = DDLSemanticAnalyzer.getProps((ASTNode) childNode.getChild(0)); if (null != replConfigs) { for (Map.Entry<String, String> config : replConfigs.entrySet()) { conf.set(config.getKey(), config.getValue()); } try { db = Hive.get(conf); } catch (HiveException e) { throw new SemanticException(e); } } break; default: throw new SemanticException("Unrecognized token in REPL LOAD statement"); } } }
Source:
<code>public void clear() { CacheDescriptor proposedCacheDescriptor = createNamespaceAndConstructCacheProposal(persistentTimestampStore); CacheDescriptor previous = cacheDescriptor.getAndUpdate(prev -> proposedCacheDescriptor); if (previous != null) { persistentTimestampStore.dropNamespace(previous.storeNamespace()); } <START> taggedMetricRegistry.gauge(CACHE_SIZE, cacheSizeGauge); <END> }</code><technical_language>this repeatedly re-registers gauges</technical_language>

Target:
public void clear() { CacheDescriptor proposedCacheDescriptor = createNamespaceAndConstructCacheProposal(persistentTimestampStore); CacheDescriptor previous = cacheDescriptor.getAndUpdate(prev -> proposedCacheDescriptor); if (previous != null) { persistentTimestampStore.dropNamespace(previous.storeNamespace()); } }
Source:
<code>protected List<MeasurementVariable> moveSelectedVariableInTheFirstColumn(List<MeasurementVariable> columns, final int variableId) { int trialInstanceIndex = 0; <START> for(MeasurementVariable column: columns) { <END> if(variableId == column.getTermId()) { final MeasurementVariable trialInstanceMeasurementVariable = columns.remove(trialInstanceIndex); columns.add(0, trialInstanceMeasurementVariable); break; } trialInstanceIndex++; } return columns; }</code><technical_language>add final</technical_language>

Target:
List<MeasurementVariable> moveSelectedVariableInTheFirstColumn(List<MeasurementVariable> columns, final int variableId) { int trialInstanceIndex = 0; for(final MeasurementVariable column: columns) { if(variableId == column.getTermId()) { final MeasurementVariable trialInstanceMeasurementVariable = columns.remove(trialInstanceIndex); columns.add(0, trialInstanceMeasurementVariable); break; } trialInstanceIndex++; } return columns; }
Source:
<code>private void bind(Show show) { collapsingToolbar.setTitle(show.getTitle()); status.setText(show.getShowStatus().getStringId()); <START> CharSequence descriptionText = processDescription(show.getDescription()); <END> if (descriptionText.length() == 0) { description.setVisibility(View.GONE); divider.setVisibility(View.GONE); } else { description.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE); description.setText(descriptionText); } duration.setText(getString(R.string.duration, show.getRuntime())); rating.setText(getString(R.string.rating, show.getRating())); Glide.with(this) .load(show) .centerCrop() .into(showImage); }</code><technical_language>Show description null</technical_language>

Target:
private void bind(Show show) { collapsingToolbar.setTitle(show.getTitle()); status.setText(show.getShowStatus().getStringId()); CharSequence descriptionText = processDescription(show.getDescription()); if (TextUtils.isEmpty(descriptionText)) { description.setVisibility(View.GONE); divider.setVisibility(View.GONE); } else { description.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE); description.setText(descriptionText); } duration.setText(getString(R.string.duration, show.getRuntime())); rating.setText(getString(R.string.rating, show.getRating())); Glide.with(this) .load(show) .centerCrop() .into(showImage); }
Source:
<code><START> public List<IModule> getModules() { <END> List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; }</code><technical_language>Restore visibility of methods in this class package level unit tests moved jaggr-core</technical_language>

Target:
List<IModule> getModules() { List<IModule> result = new ArrayList<IModule>(size()); for (ModuleListEntry entry : this) { result.add(entry.getModule()); } return result; }
Source:
<code>private Socket generateIdlePersistentConnection() throws IOException { Socket socket = new Socket("localhost", dynamicPort.getNumber()); assertThat(socket.isConnected(), is(true)); <START> sendRequest(socket, "/path"); <END> assertResponse(getResponse(socket), true); sendRequest(socket, "/path"); assertResponse(getResponse(socket), true); return socket; }</code><technical_language>constants for path</technical_language>

Target:
private Socket generateIdlePersistentConnection() throws IOException { Socket socket = new Socket("localhost", dynamicPort.getNumber()); assertThat(socket.isConnected(), is(true)); sendRequest(socket, FAST_PROCESSING_ENDPOINT); assertResponse(getResponse(socket), true); sendRequest(socket, FAST_PROCESSING_ENDPOINT); assertResponse(getResponse(socket), true); return socket; }
Source:
<code>public void doSpecificWork() { StopWatch sw = new StopWatch().start(); LOGGER.info("Start calculating landmarks, default active lms: {}, weighting: {}, {}", <START> lms.getLandmarkCount(), defaultActiveLandmarks, lms.getLmSelectionWeighting(), Helper.getMemInfo()); <END> lms.createLandmarks(); lms.flush(); LOGGER.info("Calculating landmarks for " + (lms.getSubnetworksWithLandmarks() - 1) + " subnetworks took:" + sw.stop().getSeconds() + " => " + lms.getLandmarksAsGeoJSON() + ", stored weights:" + lms.getLandmarkCount() + ", nodes:" + graph.getNodes() + ", " + Helper.getMemInfo()); }</code><technical_language>honest: I previous logging statement more clear :) "{}" notation is avoid string concatening if disable logging for this class, advantage is for massive logging get in REST server deactivate logging is valuable for analyzation</technical_language>

Target:
public void doSpecificWork() { StopWatch sw = new StopWatch().start(); LOGGER.info("Start calculating " + lms.getLandmarkCount() + " landmarks, default active lms:" + defaultActiveLandmarks + ", weighting:" + lms.getLmSelectionWeighting() + ", " + Helper.getMemInfo()); lms.createLandmarks(); lms.flush(); LOGGER.info("Calculating landmarks for " + (lms.getSubnetworksWithLandmarks() - 1) + " subnetworks took:" + sw.stop().getSeconds() + " => " + lms.getLandmarksAsGeoJSON() + ", stored weights:" + lms.getLandmarkCount() + ", nodes:" + graph.getNodes() + ", " + Helper.getMemInfo()); }
Source:
<code><START> public void testToString() { <END> LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); String str = toTest.toString(); assertTrue(str.contains("myuser"), "str="+toTest); assertTrue(str.contains("passwordPresent=true"), "str="+toTest); assertTrue(str.contains("privateKeyPresent=true"), "str="+toTest); }</code><technical_language>this test, I test sanity/composition of toString else. personal vote omit this test, in previous test simply verify assertNotNull(toTest.toString());. curious hear others say. @nacx @abayer @andrewgaul</technical_language>

Target:
public void testToString() { LoginCredentials toTest = LoginCredentials.builder().user("myuser").password("password").privateKey("key").build(); assertNotNull(toTest.toString()); }
Source:
<code>public synchronized void stop() throws Exception { if (started) { isLeader = false; server.stop(); serverThread.join(); if (gcTsTracker != null) { gcTsTracker.stop(); } started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderLatch.close(); execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); curatorFramework.getConnectionStateListenable().removeListener(cnxnListener); <START> Thread.sleep(250); <END> curatorFramework.close(); } log.info("Oracle server has been stopped."); } }</code><technical_language>InterruptedException prevent curatorFramework.close() next line. do following? java try { Thread.sleep(250); } finally { curatorFramework.close(); }</technical_language>

Target:
public synchronized void stop() throws Exception { if (started) { isLeader = false; server.stop(); serverThread.join(); if (gcTsTracker != null) { gcTsTracker.stop(); } started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderLatch.close(); execService.shutdown(); execService.awaitTermination(10, TimeUnit.SECONDS); curatorFramework.getConnectionStateListenable().removeListener(cnxnListener); Uninterruptibles.sleepUninterruptibly(250, TimeUnit.MILLISECONDS); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }
Source:
<code>public void start() { expiryEntryQueue = new LinkedBlockingQueue<ExpiryEntry>(configuration.expiryQueueSize()); try { db = openDatabase(getQualifiedLocation(), dataDbOptions()); expiredDb = openDatabase(getQualifiedExpiredLocation(), expiredDbOptions()); <START> semaphore.release(Integer.MAX_VALUE); <END> } catch (IOException e) { throw new CacheConfigurationException("Unable to open database", e); } }</code><technical_language>I guess this mirrors semaphore.acquire(Integer.MAX_VALUE) in stop() method. sense initialize semaphore in init() method new Semaphore(Integer.MAX_VALUE) ? @danberindei suggestion a reentrant lock is</technical_language>

Target:
public void start() { expiryEntryQueue = new LinkedBlockingQueue<ExpiryEntry>(configuration.expiryQueueSize()); try { db = openDatabase(getQualifiedLocation(), dataDbOptions()); expiredDb = openDatabase(getQualifiedExpiredLocation(), expiredDbOptions()); stopped = false; } catch (IOException e) { throw new CacheConfigurationException("Unable to open database", e); } }
Source:
<code>public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) { return new PagedIterable<Ticket>( tmpl("/incremental/tickets.json{?start_time,end_time}") <START> .set("start_time", (int) (startTime.getTime() / 1000)) <END> .set("end_time", (int) (endTime.getTime() / 1000)), handleIncrementalList(Ticket.class, "tickets")); }</code><technical_language>for readability suggest creating a small private method takes a date divides 1000 casts, a ugly over</technical_language>

Target:
public Iterable<Ticket> getTicketsIncrementally(Date startTime, Date endTime) { return new PagedIterable<Ticket>( tmpl("/incremental/tickets.json{?start_time,end_time}") .set("start_time", msToSeconds(startTime.getTime())) .set("end_time", msToSeconds(endTime.getTime())), handleIncrementalList(Ticket.class, "tickets")); }
Source:
<code>protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); jenkins.checkPermission(Jenkins.ADMINISTER); PluginManager manager = jenkins.getPluginManager(); int result = 0; boolean somePluginDisabled = false; for (String pluginName : pluginNames) { switch (disablePlugin(manager, pluginName)) { case DISABLED: if(!somePluginDisabled) somePluginDisabled = true; break; case NOT_DISABLED_DEPENDANTS: if(result != 16) result = 16; } } if (restart && somePluginDisabled) { <START> jenkins.safeRestart(); <END> } return result; }</code><technical_language>Is asynchronous execution? I mean, CLI wait for restart</technical_language>

Target:
protected int run() throws Exception { Jenkins jenkins = Jenkins.get(); jenkins.checkPermission(Jenkins.ADMINISTER); PluginWrapper.PluginDisableStrategy strategyToUse; try { strategyToUse = PluginWrapper.PluginDisableStrategy.valueOf(strategy.toUpperCase()); } catch (IllegalArgumentException iae) { throw new IllegalArgumentException(hudson.cli.Messages.DisablePluginCommand_NoSuchStrategy(strategy, String.format("%s, %s, %s", PluginWrapper.PluginDisableStrategy.NONE, PluginWrapper.PluginDisableStrategy.MANDATORY, PluginWrapper.PluginDisableStrategy.ALL))); } List<PluginWrapper.PluginDisableResult> results = jenkins.pluginManager.disablePlugins(strategyToUse, pluginNames); printResults(results); restartIfNecessary(results); return getResultCode(results); }
Source:
<code>public int length() { if (sizeCached) { return size; } size = 0; <START> for (String s : bufferList) { <END> size += s.length(); } return size; }</code><technical_language>size is calculated here. Do want change sizeCached true</technical_language>

Target:
public int length() { if (sizeCached) { return size; } size = 0; for (String s : bufferList) { size += s.length(); } sizeCached = true; return size; }
Source:
<code>protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.NewGuid()); mNewCreatedDiskImage = CloneDiskImage(getDestinationImageId()); Guid storagePoolID = mNewCreatedDiskImage.getstorage_pool_id() != null ? mNewCreatedDiskImage .getstorage_pool_id().getValue() : Guid.Empty; VDSReturnValue vdsReturnValue = null; try { vdsReturnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CopyImage, new CopyImageVDSCommandParameters(storagePoolID, getDiskImage().getstorage_id().getValue(), getVmTemplateId(), getDiskImage().getimage_group_id().getValue(), getImage() .getId(), getImageGroupId(), getDestinationImageId(), CalculateImageDescription(), getDestinationStorageDomainId(), CopyVolumeType.LeafVol, mNewCreatedDiskImage.getvolume_format(), mNewCreatedDiskImage.getvolume_type(), getDiskImage().getwipe_after_delete(), false, getStoragePool().getcompatibility_version().toString())); if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalTaskIdList().add( CreateTask(vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate)); } else { <START> return vdsReturnValue; <END> } } catch (java.lang.Exception e) { log.errorFormat( "CreateCloneOfTemplateCommand::CreateSnapshotInIrsServer::Failed creating snapshot from image id -'{0}'", getImage().getId()); throw new VdcBLLException(VdcBllErrors.VolumeCreationError); } return vdsReturnValue; }</code><technical_language>'else' part redundant</technical_language>

Target:
protected VDSReturnValue performImageVdsmOperation() { setDestinationImageId(Guid.NewGuid()); mNewCreatedDiskImage = CloneDiskImage(getDestinationImageId()); Guid storagePoolID = mNewCreatedDiskImage.getstorage_pool_id() != null ? mNewCreatedDiskImage .getstorage_pool_id().getValue() : Guid.Empty; VDSReturnValue vdsReturnValue = null; try { vdsReturnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CopyImage, new CopyImageVDSCommandParameters(storagePoolID, getDiskImage().getstorage_id().getValue(), getVmTemplateId(), getDiskImage().getimage_group_id().getValue(), getImage() .getId(), getImageGroupId(), getDestinationImageId(), CalculateImageDescription(), getDestinationStorageDomainId(), CopyVolumeType.LeafVol, mNewCreatedDiskImage.getvolume_format(), mNewCreatedDiskImage.getvolume_type(), getDiskImage().getwipe_after_delete(), false, getStoragePool().getcompatibility_version().toString())); if (vdsReturnValue.getSucceeded()) { getReturnValue().getInternalTaskIdList().add( CreateTask(vdsReturnValue.getCreationInfo(), VdcActionType.AddVmFromTemplate)); } } catch (java.lang.Exception e) { log.errorFormat( "CreateCloneOfTemplateCommand::CreateSnapshotInIrsServer::Failed creating snapshot from image id -'{0}'", getImage().getId()); throw new VdcBLLException(VdcBllErrors.VolumeCreationError); } return vdsReturnValue; }
Source:
<code>public void getSelectedRecord() { getRecordById(Helper.getRequestParameter(ID_PARAMETER_NAME)); Ajax.update(FORM_CLIENTID); if (this.createProcessForm.getProcesses().size() > 1 && Objects.isNull(this.createProcessForm.getProcesses().get(1).getMetadataNodes())) { this.createProcessForm.setEditActiveTabIndex(TITLE_RECORD_LINK_TAB_INDEX); Process parentProcess = this.createProcessForm.getProcesses().get(1).getProcess(); ArrayList<SelectItem> parentCandidates = new ArrayList<>(); parentCandidates.add(new SelectItem(parentProcess.getId().toString(), parentProcess.getTitle())); this.createProcessForm.getTitleRecordLinkTab().setPossibleParentProcesses(parentCandidates); this.createProcessForm.getTitleRecordLinkTab().setChosenParentProcess((String)parentCandidates.get(0).getValue()); this.createProcessForm.getTitleRecordLinkTab().chooseParentProcess(); String summary = Helper.getTranslation("newProcess.catalogueSearch.linkedToExistingProcessSummary"); String detail = Helper.getTranslation("newProcess.catalogueSearch.linkedToExistingProcessDetail", Collections.singletonList(parentProcess.getTitle())); <START> showGrowMessage(summary, detail); <END> Ajax.update(INSERTION_TREE); } else { this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } if (ServiceManager.getImportService().getExemplarRecords().size() > 0) { PrimeFaces.current().executeScript("PF('exemplarRecordsDialog').show();"); } }</code><technical_language>suggestion showGrowlMessage(summary, detail);</technical_language>

Target:
public void getSelectedRecord() { getRecordById(Helper.getRequestParameter(ID_PARAMETER_NAME)); Ajax.update(FORM_CLIENTID); int numberOfProcesses = this.createProcessForm.getProcesses().size(); if (numberOfProcesses < 1) { Helper.setErrorMessage("Error: list of processes is empty!"); return; } if (numberOfProcesses < this.importDepth) { TempProcess parentTempProcess = ServiceManager.getImportService().getParentTempProcess(); if (Objects.nonNull(parentTempProcess)) { Process parentProcess = parentTempProcess.getProcess(); if (numberOfProcesses == 1) { this.createProcessForm.setEditActiveTabIndex(TITLE_RECORD_LINK_TAB_INDEX); ArrayList<SelectItem> parentCandidates = new ArrayList<>(); parentCandidates.add(new SelectItem(parentProcess.getId().toString(), parentProcess.getTitle())); this.createProcessForm.getTitleRecordLinkTab().setPossibleParentProcesses(parentCandidates); this.createProcessForm.getTitleRecordLinkTab().setChosenParentProcess((String)parentCandidates.get(0).getValue()); this.createProcessForm.getTitleRecordLinkTab().chooseParentProcess(); Ajax.update(INSERTION_TREE); } else { this.createProcessForm.getProcesses().add(parentTempProcess); this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } } else { this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } } else { this.createProcessForm.setEditActiveTabIndex(ADDITIONAL_FIELDS_TAB_INDEX); } if (ServiceManager.getImportService().getExemplarRecords().size() > 0) { PrimeFaces.current().executeScript("PF('exemplarRecordsDialog').show();"); } }
Source:
<code>public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); <START> String resolvedName = propertyNodeNameProvider.getName( javaBeanPropertyFrom( declaringClass, property ) ); <END> return Optional.ofNullable( field ).map( f -> new JavaBeanField( f, resolvedName ) ); }</code><technical_language>if field this point is null - need do additional work return Optional.empty(). find resolved name Optional.of(). like: java Field field = run( GetDeclaredField.action( declaringClass, property ) ); if ( field == null ) { return Optional.empty(); } else { String resolvedName = propertyNodeNameProvider.getName( new JavaBeanPropertyImpl( declaringClass, property ) ); return Optional.of( new JavaBeanField( field, resolvedName ) ); }</technical_language>

Target:
public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); return Optional.ofNullable( field ).map( this::field ); }
Source:
<code>public void damage(double amount, Entity source, DamageCause cause) { super.damage(amount, source, cause); <START> if (DamageCause.LIGHTNING.equals(cause)) { <END> CreeperPowerEvent event = EventFactory.getInstance() .callEvent(new CreeperPowerEvent( this, (LightningStrike) source, CreeperPowerEvent.PowerCause.LIGHTNING)); if (!event.isCancelled()) { setPowered(true); } } }</code><technical_language>Off-topic, add a check for !isPowered() in this if statement</technical_language>

Target:
public void damage(double amount, Entity source, DamageCause cause) { super.damage(amount, source, cause); if (DamageCause.LIGHTNING.equals(cause) && !isPowered()) { CreeperPowerEvent event = EventFactory.getInstance() .callEvent(new CreeperPowerEvent( this, (LightningStrike) source, CreeperPowerEvent.PowerCause.LIGHTNING)); if (!event.isCancelled()) { setPowered(true); } } }
Source:
<code>private void addCount(StyledString styled, int count) { <START> String formatted = MessageFormat.format(" ({0})", count); END> styled.append(formatted, StyledString.COUNTER_STYLER); }</code><technical_language>Code style: compiler optimize this anyway, prefer pattern a constant here</technical_language>

Target:
private void addCount(StyledString styled, int count) { String formatted = MessageFormat.format(COUNTER_PATTERN, count); styled.append(formatted, StyledString.COUNTER_STYLER); }
Source:
<code>public void removeFolder(String id) { removeFolderInternal(id); <START> mCompletion.removeFolder(id); <END> sendConfig(); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .remove(ShareActivity.PREF_FOLDER_SAVED_SUBDIRECTORY+id) .apply(); }</code><technical_language>need this, ConfigSaved handle this already</technical_language>

Target:
public void removeFolder(String id) { removeFolderInternal(id); sendConfig(); PreferenceManager.getDefaultSharedPreferences(mContext).edit() .remove(ShareActivity.PREF_FOLDER_SAVED_SUBDIRECTORY+id) .apply(); }
Source:
<code>public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPartSite site = getSite(); if (site != null) { IWorkbenchPage page = site.getPage(); if (page != null) { <START> page.removePartListener(fPartListener); <END> page.removePartListener(fPartListener2); } } }</code><technical_language>fPartListener/2 is null. I site page null this point</technical_language>

Target:
public void dispose() { super.dispose(); synchronized (fBuildJobMap) { fBuildJobMap.values().forEach(Job::cancel); } if (fZoomThread != null) { fZoomThread.cancel(); } deactivateContextService(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); IWorkbenchPartSite site = getSite(); if (site != null) { IWorkbenchPage page = site.getPage(); if (fPartListener != null) { page.removePartListener(fPartListener); } if (fPartListener2 != null) { page.removePartListener(fPartListener2); } } }
Source:
<code><START> private void prepareEventObject(EventRecord eventRecord) throws JSONException { <END> final JSONObject defaultEventProperties = systemInformation.getDefaultEventProperties(); final JSONObject eventProperties = new JSONObject(eventRecord.getJsonString()); if (eventProperties != null) { for (final Iterator<?> iter = defaultEventProperties.keys(); iter.hasNext();) { final String key = (String) iter.next(); eventProperties.put(key, defaultEventProperties.get(key)); } eventRecord.setJsonString(eventProperties.toString()); } }</code><technical_language>Minor question: final for objects this method? e.g. JSONObject, Iterator<?> ..</technical_language>

Target:
private void prepareEventObject(EventRecord eventRecord) throws JSONException { JSONObject defaultEventProperties = systemInformation.getDefaultEventProperties(); JSONObject eventProperties = new JSONObject(eventRecord.getJsonString()); for (final Iterator<?> iter = defaultEventProperties.keys(); iter.hasNext();) { final String key = (String) iter.next(); eventProperties.put(key, defaultEventProperties.get(key)); eventRecord.setJsonString(eventProperties.toString()); } }
Source:
<code><START> List<VariantEntity> queryByCoordinatesAndAlleles(String chromosome, int start, String reference, String alternate) { <END> if (alternate != null) { return variantEntityRepository.findByChromosomeAndStartAndReferenceAndAlternate(chromosome, start, reference, alternate); } else { return variantEntityRepository.findByChromosomeAndStartAndReference(chromosome, start, reference); } }</code><technical_language>This method private</technical_language>

Target:
private List<VariantEntity> queryByCoordinatesAndAlleles(String chromosome, int start, String reference, String alternate) { if (alternate != null) { return variantEntityRepository.findByChromosomeAndStartAndReferenceAndAlternate(chromosome, start, reference, alternate); } else { return variantEntityRepository.findByChromosomeAndStartAndReference(chromosome, start, reference); } }
Source:
<code>public void descriptionHonorsShowRawYaml() { PodTemplate pt = new PodTemplate(); ContainerTemplate ct1 = new ContainerTemplate("foo", "image"); pt.setContainers(Collections.singletonList(ct1)); String yaml = new StringBuilder() .append("metadata:").append("\n") .append(" annotations:").append("\n") .append(" foo: bar").append("\n") <START> .toString(); <END> pt.setYamls(Collections.singletonList(yaml)); String description = pt.getDescriptionForLogging(); assertThat(description, containsString("[foo] image")); assertThat(description, containsString("yaml:\n"+yaml)); pt.setShowRawYaml(false); description = pt.getDescriptionForLogging(); assertThat(description, not(containsString("yaml:\n"))); assertThat(description, not(containsString(yaml))); }</code><technical_language>More readable a simple series of strings concatenated +</technical_language>

Target:
public void descriptionHonorsShowRawYaml() { PodTemplate pt = new PodTemplate(); ContainerTemplate ct1 = new ContainerTemplate("foo", "image"); pt.setContainers(Collections.singletonList(ct1)); String yaml = "metadata:\n" + " annotations:\n" + " foo: bar\n"; pt.setYamls(Collections.singletonList(yaml)); String description = pt.getDescriptionForLogging(); assertThat(description, containsString("[foo] image")); assertThat(description, containsString("yaml:\n"+yaml)); pt.setShowRawYaml(false); description = pt.getDescriptionForLogging(); assertThat(description, not(containsString("yaml:\n"))); assertThat(description, not(containsString(yaml))); }
Source:
<code>public TokenResponse(ByteBuf buf) { respType = TokenType.values()[ICorfuPayload.fromBuffer(buf, Byte.class)]; conflictKey = ICorfuPayload.fromBuffer(buf, byte[].class); <START> conflistStream = ICorfuPayload.fromBuffer(buf, UUID.class); <END> offendingTx = ICorfuPayload.fromBuffer(buf, UUID.class); Long epoch = ICorfuPayload.fromBuffer(buf, Long.class); Long sequence = ICorfuPayload.fromBuffer(buf, Long.class); token = new Token(epoch, sequence); backpointerMap = ICorfuPayload.mapFromBuffer(buf, UUID.class, Long.class); streamTails = ICorfuPayload.listFromBuffer(buf, Long.class); }</code><technical_language>typo.. conflist..</technical_language>

Target:
public TokenResponse(ByteBuf buf) { respType = TokenType.values()[ICorfuPayload.fromBuffer(buf, Byte.class)]; conflictKey = ICorfuPayload.fromBuffer(buf, byte[].class); conflictStream = ICorfuPayload.fromBuffer(buf, UUID.class); Long epoch = ICorfuPayload.fromBuffer(buf, Long.class); Long sequence = ICorfuPayload.fromBuffer(buf, Long.class); token = new Token(epoch, sequence); backpointerMap = ICorfuPayload.mapFromBuffer(buf, UUID.class, Long.class); streamTails = ICorfuPayload.listFromBuffer(buf, Long.class); }
Source:
<code>protected static Configuration getModuleConfig(String moduleName, String moduleId) { final Configuration result; final List<Configuration> configs = getModuleConfigs(moduleName); if (configs.size() == 1) { result = configs.get(0); } else if (configs.isEmpty()) { throw new IllegalStateException("no instances of the Module was found: " + moduleName); } else if (moduleId == null) { throw new IllegalStateException("multiple instances of the same Module are detected"); } else { result = configs.stream().filter(conf -> { try { return conf.getAttribute("id").equals(moduleId); } catch (CheckstyleException ex) { throw new IllegalStateException("problem to get ID attribute from " + conf, ex); } }) <START> .findFirst().orElseGet(null); <END> } return result; }</code><technical_language>findFirst().orElseThrow( new IllegalStateException("problem module config")); ? This case possible, if happens, is give a tip engineer</technical_language>

Target:
protected static Configuration getModuleConfig(String moduleName, String moduleId) { final Configuration result; final List<Configuration> configs = getModuleConfigs(moduleName); if (configs.size() == 1) { result = configs.get(0); } else if (configs.isEmpty()) { throw new IllegalStateException("no instances of the Module was found: " + moduleName); } else if (moduleId == null) { throw new IllegalStateException("multiple instances of the same Module are detected"); } else { result = configs.stream().filter(conf -> { try { return conf.getAttribute("id").equals(moduleId); } catch (CheckstyleException ex) { throw new IllegalStateException("problem to get ID attribute from " + conf, ex); } }) .findFirst() .orElseThrow(() -> new IllegalStateException("problem with module config")); } return result; }
Source:
<code>public static void updatePersistedDomain(String previousDomain, String newDomain, int tenantId, DataSource dataSource) throws UserStoreException { Connection dbConnection = null; try { String sqlStatement = JDBCRealmConstants.UPDATE_DOMAIN_SQL; if (previousDomain != null) { previousDomain = previousDomain.toUpperCase(); } if (newDomain != null) { newDomain = newDomain.toUpperCase(); } if (isExistingDomain(previousDomain, tenantId, dataSource)) { if (!isExistingDomain(newDomain, tenantId, dataSource)) { deletePersistedDomain(newDomain, tenantId, dataSource); } dbConnection = DatabaseUtil.getDBConnection(dataSource); dbConnection.setAutoCommit(false); DatabaseUtil.updateDatabase(dbConnection, sqlStatement, newDomain, previousDomain, tenantId); dbConnection.commit(); } } catch (SQLException e) { String errorMessage = "Error occurred while updating persisted domain :" + previousDomain + " to domain :" + newDomain + " for tenant id :" + tenantId; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } <START> throw new UserStoreException(errorMessage); <END> } finally { DatabaseUtil.closeAllConnections(dbConnection); } }</code><technical_language>stack trace dropped</technical_language>

Target:
public static void updatePersistedDomain(String previousDomain, String newDomain, int tenantId, DataSource dataSource) throws UserStoreException { Connection dbConnection = null; try { String sqlStatement = JDBCRealmConstants.UPDATE_DOMAIN_SQL; if (previousDomain != null) { previousDomain = previousDomain.toUpperCase(); } if (newDomain != null) { newDomain = newDomain.toUpperCase(); } if (isExistingDomain(previousDomain, tenantId, dataSource)) { if (!isExistingDomain(newDomain, tenantId, dataSource)) { deletePersistedDomain(newDomain, tenantId, dataSource); } dbConnection = DatabaseUtil.getDBConnection(dataSource); dbConnection.setAutoCommit(false); DatabaseUtil.updateDatabase(dbConnection, sqlStatement, newDomain, previousDomain, tenantId); dbConnection.commit(); } } catch (SQLException e) { String errorMessage = "Error occurred while updating persisted domain :" + previousDomain + " to domain :" + newDomain + " for tenant id :" + tenantId; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } }
Source:
<code>public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { <START> throw new IllegalStateException("throwable is null: " + <END> "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } throwable.fillInStackTrace(); filter.filter(throwable); throw throwable; }</code><technical_language>This exception message is consistent handle exceptions. a a Reporter class. Typically throw exception is derives MockitoException. message needs clean, actionable end user. I suggest create a high level unit test demonstrates this case standpoint of end user. Run this test, observe exception, a newbie Mockito understand exception message able resolve problem quickly</technical_language>

Target:
public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { throw new IllegalStateException("throwable is null: " + "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } Throwable t = throwable.fillInStackTrace(); if (t == null) { throw throwable; } filter.filter(t); throw t; }
Source:
<code>public void testReferenceLocalDiskCache() { <START> System.setProperty("samjdk.ref_cache", TEST_DIR + "%s"); <END> final File cramFile = new File(TEST_DIR + "auxf#values.3.0.cram"); CRAMReferenceSource refSource = ReferenceSource.getDefaultCRAMReferenceSource(); CRAMFileReader cramFileReader = new CRAMFileReader(cramFile, refSource); cramFileReader.getIterator().next(); }</code><technical_language>tests try/catch catch blocks unset property clean files. Currently a side affect of setting property affect other tests in process</technical_language>

Target:
public void testReferenceLocalDiskCache() { final File cramFile = new File(TEST_DIR + "auxf#values.3.0.cram"); CRAMReferenceSource refSource = ReferenceSource.getDefaultCRAMReferenceSource(); CRAMFileReader cramFileReader = new CRAMFileReader(cramFile, refSource); cramFileReader.getIterator().next(); }
Source:
<code>public void postCollectionDefaultItemReadGroupCreateDefaultItemReadGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/itemReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); <START> <END> }</code><technical_language>double check group created</technical_language>

Target:
public void postCollectionDefaultItemReadGroupCreateDefaultItemReadGroupDcTitleUnprocessable() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); metadataRest.put("dc.title", new MetadataValueRest("testTitle")); groupRest.setMetadata(metadataRest); AtomicReference<UUID> idRef = new AtomicReference<>(); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/itemReadGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnprocessableEntity()); Group anon = groupService.findByName(context, Group.ANONYMOUS); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/itemReadGroup")) .andExpect(status().isOk()) .andExpect( jsonPath("$", GroupMatcher.matchGroupEntry(anon.getID(), anon.getName()))); }