auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void readEntityFromNBT(NBTTagCompound nbt) { super.readEntityFromNBT(nbt); if (nbt.hasKey("home")) { saveHome = true; int[] h = nbt.getIntArray("home"); home = new AxisAlignedBB(h[0], h[1], h[2], h[3], h[4], h[5]); if (nbt.hasKey("homeMovePrio")) { this.setMoveTowardsRestriction(nbt.getInteger("moveHomePrio"), true); } } <START> if (nbt.hasKey("activeAction")) { <END> entityActionHandler.resetAction(EntityActionManager.actionsByID.get(nbt.getInteger("activeAction"))); } }</code><technical_language>move this load process Entity Action Handler (so call entityActionHandler.readFromNBT). more easily other entity classes</technical_language>

Target:
public void readEntityFromNBT(NBTTagCompound nbt) { super.readEntityFromNBT(nbt); if (nbt.hasKey("home")) { saveHome = true; int[] h = nbt.getIntArray("home"); home = new AxisAlignedBB(h[0], h[1], h[2], h[3], h[4], h[5]); if (nbt.hasKey("homeMovePrio")) { this.setMoveTowardsRestriction(nbt.getInteger("moveHomePrio"), true); } } if (entityActionHandler != null) { entityActionHandler.readFromNBT(nbt); } }
Source:
<code>public int hashCode() { if (isDisposed()) return 0; <START> return this.getRed() ^ this.getBlue() ^ this.getGreen() ^ this.getAlpha(); <END> }</code><technical_language>I realize Cocoa SWT this, is this is a good hash function. return a in range [0..255]. treat RGBA a single int? ((alpha << 24) | (blue << 16) | (green << 8) | red in org.eclipse.swt.graphics.RGBA a distribution</technical_language>

Target:
public int hashCode() { if (isDisposed()) return 0; return (((alpha * 31) + this.getGreen()) * 31 + this.getBlue()) * 31 + this.getRed(); }
Source:
<code>public static void deleteJobs() throws IOException { <START> String projectID = "your-project-id"; <END> String jobID = "your-job-id"; deleteJobs(projectID,jobID); }</code><technical_language>nit: Do caps in other places? consistent values expect users replace</technical_language>

Target:
public static void deleteJobs() throws IOException { String projectId = "your-project-id"; String jobId = "your-job-id"; deleteJobs(projectId,jobId); }
Source:
<code>public int run(CommandLine cl) throws AlluxioException, IOException { mWorkingDirPath = getWorkingDirectory(cl); String confDirPath = mFsContext.getClusterConf().get(PropertyKey.CONF_DIR); File confDir = new File(confDirPath); List<File> allFiles = CommonUtils.recursiveListDir(confDir); for (File f : allFiles) { String relativePath = confDir.toURI().relativize(f.toURI()).getPath(); <START> for (String prefix : EXCLUDED_FILES) { <END> if (relativePath.startsWith(prefix)) { continue; } File targetFile = new File(mWorkingDirPath, relativePath); FileUtils.copyFile(f, targetFile, true); } } return 0; }</code><technical_language>If supposed prefixes, variable name EXCLUDED_FILE_PREFIXES something</technical_language>

Target:
public int run(CommandLine cl) throws AlluxioException, IOException { mWorkingDirPath = getWorkingDirectory(cl); String confDirPath = mFsContext.getClusterConf().get(PropertyKey.CONF_DIR); File confDir = new File(confDirPath); List<File> allFiles = CommonUtils.recursiveListLocalDir(confDir); for (File f : allFiles) { String filename = f.getName(); String relativePath = confDir.toURI().relativize(f.toURI()).getPath(); if (EXCLUDED_FILE_PREFIXES.stream().anyMatch(filename::startsWith)) { continue; } File targetFile = new File(mWorkingDirPath, relativePath); FileUtils.copyFile(f, targetFile, true); } return 0; }
Source:
<code>private void notifyListeners() { IndexDiffChangedListener[] tmpListeners; synchronized (listeners) { tmpListeners = listeners .toArray(new IndexDiffChangedListener[listeners.size()]); } <START> for (int i = 0; i < tmpListeners.length; i++) { <END> tmpListeners[i].indexDiffChanged(repository, indexDiffData); } }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
private void notifyListeners() { IndexDiffChangedListener[] tmpListeners; synchronized (listeners) { tmpListeners = listeners .toArray(new IndexDiffChangedListener[listeners.size()]); } for (int i = 0; i < tmpListeners.length; i++) tmpListeners[i].indexDiffChanged(repository, indexDiffData); }
Source:
<code>public void testDetectDeadlockOnUiThread() throws Exception { assertNotNull(Display.getCurrent()); TestSecureCredentialsStore store = createCredentialsStore(); store.put("key", "value", true); ILock lock = store.getLock(); assertNotNull(lock); try { <START> assertTrue(lock.acquire(3000)); <END> } catch (InterruptedException e) { fail("Interrupted trying to acquire SecurePreferencesRoot lock"); } try { try { store.get("key", null); fail("Expected exception"); } catch (RuntimeException e) { assertEquals("Possible deadlock detected accessing secure storage; aborting request", e.getMessage()); } try { store.put("key", "newValue", true); fail("Expected exception"); } catch (RuntimeException e) { assertEquals("Possible deadlock detected accessing secure storage; aborting request", e.getMessage()); } } finally { lock.release(); } assertEquals("value", store.get("key", null)); store.put("key", "newValue", true); assertEquals("newValue", store.get("key", null)); }</code><technical_language>try block below</technical_language>

Target:
public void testDetectDeadlockOnUiThread() throws Exception { assertNotNull(Display.getCurrent()); TestSecureCredentialsStore store = createCredentialsStore(); store.put("key", "value", true); ILock lock = store.getLock(); assertNotNull(lock); try { assertTrue(lock.acquire(3000)); try { store.get("key", null); fail("Expected exception"); } catch (RuntimeException e) { assertEquals(DEADLOCK_ERROR_MESSAGE, e.getMessage()); } try { store.put("key", "newValue", true); fail("Expected exception"); } catch (RuntimeException e) { assertEquals(DEADLOCK_ERROR_MESSAGE, e.getMessage()); } } catch (InterruptedException e) { fail("Interrupted trying to acquire SecurePreferencesRoot lock"); } finally { lock.release(); } assertEquals("value", store.get("key", null)); store.put("key", "newValue", true); assertEquals("newValue", store.get("key", null)); }
Source:
<code>CompactibleTimelineObjectHolderCursor( VersionedIntervalTimeline<String, DataSegment> timeline, List<Interval> totalIntervalsToSearch ) { this.holders = totalIntervalsToSearch .stream() .flatMap(interval -> timeline .lookup(interval) .stream() .filter(holder -> { final List<PartitionChunk<DataSegment>> chunks = Lists.newArrayList(holder.getObject().iterator()); final long partitionBytes = chunks.stream().mapToLong(chunk -> chunk.getObject().getSize()).sum(); <START> return chunks.size() > 0 <END> && partitionBytes > 0 && interval.contains(chunks.get(0).getObject().getInterval()); }) ) .collect(Collectors.toList()); }</code><technical_language>Prefer !chunks.isEmpty() (similar change line 185)</technical_language>

Target:
CompactibleTimelineObjectHolderCursor( VersionedIntervalTimeline<String, DataSegment> timeline, List<Interval> totalIntervalsToSearch ) { this.holders = totalIntervalsToSearch .stream() .flatMap(interval -> timeline .lookup(interval) .stream() .filter(holder -> { final List<PartitionChunk<DataSegment>> chunks = Lists.newArrayList(holder.getObject().iterator()); final long partitionBytes = chunks.stream().mapToLong(chunk -> chunk.getObject().getSize()).sum(); return !chunks.isEmpty() && partitionBytes > 0 && interval.contains(chunks.get(0).getObject().getInterval()); }) ) .collect(Collectors.toList()); }
Source:
<code>public String getTournament(Model model, HttpSession session) { if (session.getAttribute("member") == null) { <START> return "redirect:denied"; <END> } Member member = (Member) session.getAttribute("member"); if (member.getUserType() != Member.UserType.COORDINATOR) { return "redirect:denied"; } Set<Tournament> tournaments = member.getManagingTournament(); model.addAttribute("tournaments", tournaments); return "coordinator"; }</code><technical_language>redirect:/denied get correct denied page</technical_language>

Target:
public String getTournament(Model model, HttpSession session) { if (session.getAttribute("member") == null) { return "redirect:/denied"; } Member member = (Member) session.getAttribute("member"); if (MemberUtils.atLeastCoordinator(member)) { return "redirect:/denied"; } Set<Tournament> tournaments = member.getManagingTournament(); model.addAttribute("tournaments", tournaments); return "coordinator"; }
Source:
<code>private List<File> createDirs(String basePath, int numDirectories) { List<File> directories = new ArrayList<>(); for (int i = 0; i < numDirectories; i++) { <START> String dirName = basePath + File.separator + pathFilterString + "_" + getRandomStringOfLen(5); <END> File file = new File(dirName); file.mkdirs(); directories.add(file); } return directories; }</code><technical_language>i simply instead of getRandomStringOfLen(5)</technical_language>

Target:
private List<File> createDirs(String basePath, int numDirectories) { List<File> directories = new ArrayList<>(); for (int i = 0; i < numDirectories; i++) { String dirName = basePath + File.separator + PATH_FILTER_MATCHED_PREFIX + "dir_" + i; File file = new File(dirName); file.mkdirs(); directories.add(file); } return directories; }
Source:
<code>public boolean check() throws Exception { File fileCopy = File.createTempFile("modeshape-sequencer-epub", ".tmp"); IoUtil.write(in, new BufferedOutputStream(new FileOutputStream(fileCopy))); <START> ZipInputStream zipStream = new ZipInputStream(new FileInputStream(fileCopy)); <END> List<String> rootfiles = getRootfiles(zipStream); zipStream.close(); zipStream = new ZipInputStream(new FileInputStream(fileCopy)); if (!rootfiles.isEmpty()) { ZipEntry entry = null; while ((entry = zipStream.getNextEntry()) != null) { String entryName = entry.getName(); if (rootfiles.contains(entryName)) { checkRootfile(zipStream, entry); } } } else { throw new IllegalArgumentException("No rootfile package found in given EPUB file."); } zipStream.close(); boolean deleted = false; try { deleted = fileCopy.delete(); } catch (SecurityException e) { } if (!deleted) { fileCopy.deleteOnExit(); } return true; }</code><technical_language>a try-with-resources idiom ? more robust</technical_language>

Target:
public boolean check() throws Exception { File fileCopy = File.createTempFile("modeshape-sequencer-epub", ".tmp"); IoUtil.write(in, new BufferedOutputStream(new FileOutputStream(fileCopy))); List<String> rootfiles = new ArrayList<>(); try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(fileCopy))) { rootfiles = getRootfiles(zipStream); } if (!rootfiles.isEmpty()) { try (ZipInputStream zipStream = new ZipInputStream(new FileInputStream(fileCopy))) { ZipEntry entry = null; while ((entry = zipStream.getNextEntry()) != null) { String entryName = entry.getName(); if (rootfiles.contains(entryName)) { checkRootfile(zipStream, entry); } } } } else { throw new IllegalArgumentException("No rootfile package found in given EPUB file."); } boolean deleted = false; try { deleted = fileCopy.delete(); } catch (SecurityException e) { } if (!deleted) { fileCopy.deleteOnExit(); } return true; }
Source:
<code>public void onStartInstallClicked() { if (lastInstallMode != INSTALL_MODE_OFFLINE && isNetworkNotConnected()) { failWithNotification(AppInstallStatus.NoConnection); } else { <START> ConnectionDiagnosticTask<CommCareSetupActivity> task = new ConnectionDiagnosticTask(getApplicationContext()); <END> task.setListener(new ConnectionDiagnosticTask.ConnectionDiagnosticListener<CommCareSetupActivity>() { @Override public void connected(CommCareSetupActivity receiver) { CommCareApplication.notificationManager().clearNotifications(AIRPLANE_MODE_CATEGORY); receiver.startResourceInstall(); } @Override public void failed(CommCareSetupActivity receiver, String errorMessageId, MessageTag notificationTag, String analyticsMessage) { Toast.makeText(receiver, Localization.get(errorMessageId), Toast.LENGTH_LONG).show(); CommCareApplication.notificationManager().reportNotificationMessage( NotificationMessageFactory.message( notificationTag, AIRPLANE_MODE_CATEGORY)); FirebaseAnalyticsUtil.reportAppInstallFailure(getAnalyticsParamForInstallMethod(receiver.lastInstallMode), analyticsMessage); } }); task.connect(CommCareSetupActivity.this); task.executeParallel(); } }</code><technical_language>trigger this if offline install. startResourceInstall called places. a function serves a wrapper top of startResourceInstall do this connection check in case of not-offline stall</technical_language>

Target:
public void onStartInstallClicked() { if (lastInstallMode != INSTALL_MODE_OFFLINE && isNetworkNotConnected()) { failWithNotification(AppInstallStatus.NoConnection); } else { startResourceInstall(); } }
Source:
<code>private boolean canProcessDictionary(Page page) { boolean processDictionary = this.processDictionary && channels.length == 1 && page.getBlock(channels[0]) instanceof DictionaryBlock; if (processDictionary && inputHashChannel.isPresent()) { Block inputHashBlock = page.getBlock(inputHashChannel.get()); DictionaryBlock inputDataBlock = (DictionaryBlock) page.getBlock(channels[0]); if (!(inputHashBlock instanceof DictionaryBlock)) { <START> processDictionary = false; <END> } else if (!((DictionaryBlock) inputHashBlock).getDictionarySourceId().equals(inputDataBlock.getDictionarySourceId())) { processDictionary = false; } } return processDictionary; }</code><technical_language>return</technical_language>

Target:
private boolean canProcessDictionary(Page page) { if (!this.processDictionary || channels.length > 1 || !(page.getBlock(channels[0]) instanceof DictionaryBlock)) { return false; } if (inputHashChannel.isPresent()) { Block inputHashBlock = page.getBlock(inputHashChannel.get()); DictionaryBlock inputDataBlock = (DictionaryBlock) page.getBlock(channels[0]); if (!(inputHashBlock instanceof DictionaryBlock)) { return false; } if (!((DictionaryBlock) inputHashBlock).getDictionarySourceId().equals(inputDataBlock.getDictionarySourceId())) { return false; } } return true; }
Source:
<code>public byte[] encodeMessage(KM200Device device, String data) { byte[] encryptedDataB64 = null; try { byte[] bdata = data.getBytes(device.getCharSet()); final Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(device.getCryptKeyPriv(), "AES")); logger.debug("Create padding.."); int bsize = cipher.getBlockSize(); logger.debug("Add Padding and Encrypt AES.."); final byte[] encryptedData = cipher.doFinal(addZeroPadding(bdata, bsize, device.getCharSet())); logger.debug("Encrypt B64.."); try { encryptedDataB64 = Base64.getMimeEncoder().encode(encryptedData); } catch (IllegalArgumentException e) { <START> logger.error("Base64encoding not possible:" + e.getMessage()); <END> e.printStackTrace(); } return encryptedDataB64; } catch (BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { logger.error("Exception on encoding:" + e.getMessage()); return null; } catch (final GeneralSecurityException e) { throw new IllegalStateException("Algorithms or unlimited crypto files not available", e); } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public byte[] encodeMessage(KM200Device device, String data) { byte[] encryptedDataB64 = null; try { byte[] bdata = data.getBytes(device.getCharSet()); final Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(device.getCryptKeyPriv(), "AES")); logger.debug("Create padding.."); int bsize = cipher.getBlockSize(); logger.debug("Add Padding and Encrypt AES.."); final byte[] encryptedData = cipher.doFinal(addZeroPadding(bdata, bsize, device.getCharSet())); logger.debug("Encrypt B64.."); try { encryptedDataB64 = Base64.getMimeEncoder().encode(encryptedData); } catch (IllegalArgumentException e) { logger.error("Base64encoding not possible: {}", e); e.printStackTrace(); } return encryptedDataB64; } catch (BadPaddingException | IllegalBlockSizeException | UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { logger.error("Exception on encoding: {}", e); return null; } catch (final GeneralSecurityException e) { throw new IllegalStateException("Algorithms or unlimited crypto files not available", e); } }
Source:
<code>protected void ExecuteVdsBrokerCommand() { _result = null; if (getParameters().getStoragePoolId() != null) { <START> VDS vds = DbFacade.getInstance().getVdsDao().get(getParameters().getVdsId()); <END> if (FeatureSupported.saferGetAllTasksRequest(vds.getVdsGroupCompatibilityVersion())) { _result = getBroker().getAllTasksStatuses(getParameters().getStoragePoolId().toString()); } } if (_result == null) { _result = getBroker().getAllTasksStatuses(); } ProceedProxyReturnValue(); setReturnValue(ParseTaskStatusList(_result.TaskStatusList)); }</code><technical_language>Hi, I prefer if base class a method VdsDao getVdsDao (protected method) returns DbFacade.getInstance().getVdsDao This reason for this mock vds broker commands day</technical_language>

Target:
protected void ExecuteVdsBrokerCommand() { _result = null; if (getParameters().getStoragePoolId() != null) { if (FeatureSupported.saferGetAllTasksRequest(getVds().getVdsGroupCompatibilityVersion())) { _result = getBroker().getAllTasksStatuses(getParameters().getStoragePoolId().toString()); } } if (_result == null) { _result = getBroker().getAllTasksStatuses(); } ProceedProxyReturnValue(); setReturnValue(ParseTaskStatusList(_result.TaskStatusList)); }
Source:
<code>public OsiamLdapAuthenticationProvider createLdapAuthProvider() { if (isLdapConfigured) { createLdapToScimAttributeMapping(); DefaultSpringSecurityContextSource contextSource = createLdapContextSource(); BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource); bindAuthenticator.setUserDnPatterns(dnPatterns); bindAuthenticator.setUserAttributes(attributes); OsiamLdapUserContextMapper mapper = new OsiamLdapUserContextMapper(scimLdapAttributes); OsiamLdapAuthenticationProvider provider = new OsiamLdapAuthenticationProvider(bindAuthenticator, <START> new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase), mapper); <END> authenticationManager.getProviders().add(provider); return provider; } return null; }</code><technical_language>please object</technical_language>

Target:
public OsiamLdapAuthenticationProvider createLdapAuthProvider() { if (isLdapConfigured) { createLdapToScimAttributeMapping(); DefaultSpringSecurityContextSource contextSource = createLdapContextSource(); BindAuthenticator bindAuthenticator = new BindAuthenticator(contextSource); bindAuthenticator.setUserDnPatterns(dnPatterns); bindAuthenticator.setUserAttributes(attributes); OsiamLdapUserContextMapper mapper = new OsiamLdapUserContextMapper(scimLdapAttributes); DefaultLdapAuthoritiesPopulator authoritiesPopulator = new DefaultLdapAuthoritiesPopulator(contextSource, groupSearchBase); OsiamLdapAuthenticationProvider provider = new OsiamLdapAuthenticationProvider(bindAuthenticator, authoritiesPopulator, mapper); authenticationManager.getProviders().add(provider); return provider; } return null; }
Source:
<code><START> public String getTaskUrl(String reviewUrlToFind) { <END> for (Map.Entry<String, List<String>> mapping : taskReviewsMap.entrySet()) { int index = mapping.getValue().indexOf(reviewUrlToFind); if (index != -1) { return mapping.getKey(); } } return null; }</code><technical_language>This lookup is expensive. a map reviews tasks fast</technical_language>

Target:
public String getTaskUrl(String reviewUrlToFind) { for (Entry<String, String> mapping : taskReviewsMap.entries()) { int index = mapping.getValue().indexOf(reviewUrlToFind); if (index != -1) { return mapping.getKey(); } } return null; }
Source:
<code>private void completeTransaction(final TransactionInfo transactionInfo, CacheTopology cacheTopology) { final Collection<Address> affectedNodes = transactionInfo.getCommitNodes(cacheTopology); NotifyingNotifiableFuture<Map<Address, Response>> notifyingFuture = new NotifyingFutureImpl<>(); notifyingFuture.attachListener(new FutureListener<Map<Address, Response>>() { @Override public void futureDone(Future<Map<Address, Response>> future) { final GlobalTransaction globalTransaction = transactionInfo.getGlobalTransaction(); if (trace) { log.tracef("Future done for transaction %s", globalTransaction); } try { future.get(); } catch (Throwable e) { if (trace) { log.tracef(e, "Exception for transaction %s", globalTransaction); } return; } if (trace) { log.tracef("Performing cleanup for transaction %s", globalTransaction); } lockManager.unlock(transactionInfo.getLockedKeys(), globalTransaction); partialTransactions.remove(globalTransaction); TxCompletionNotificationCommand command = commandsFactory.buildTxCompletionNotificationCommand(null, globalTransaction); <START> rpcManager.invokeRemotely(null, command, rpcManager.getDefaultRpcOptions(false)); <END> } }); rpcManager.invokeRemotelyInFuture(notifyingFuture, affectedNodes, transactionInfo.buildCommand(commandsFactory, isVersioned), rpcManager.getDefaultRpcOptions(true)); }</code><technical_language>I guess StateProviderImpl check for transaction in PartitionHandlingImpl sending new nodes, I agree safest broadcast command everyone</technical_language>

Target:
private void completeTransaction(final TransactionInfo transactionInfo, CacheTopology cacheTopology) { rpcManager.invokeRemotelyAsync(transactionInfo.getCommitNodes(cacheTopology), transactionInfo.buildCommand(commandsFactory, isVersioned), rpcManager.getDefaultRpcOptions(true)) .whenComplete((responseMap, throwable) -> { final GlobalTransaction globalTransaction = transactionInfo.getGlobalTransaction(); if (trace) { log.tracef("Future done for transaction %s", globalTransaction); } if (throwable != null) { if (trace) { log.tracef(throwable, "Exception for transaction %s. Retry later.", globalTransaction); } return; } if (trace) { log.tracef("Future done for transaction %s. Response are %s", globalTransaction, responseMap); } for (Response response : responseMap.values()) { if (response == UnsureResponse.INSTANCE || response == CacheNotFoundResponse.INSTANCE) { if (trace) { log.tracef("Another partition or topology changed for transaction %s. Retry later.", globalTransaction); } return; } } if (trace) { log.tracef("Performing cleanup for transaction %s", globalTransaction); } lockManager.unlock(transactionInfo.getLockedKeys(), globalTransaction); partialTransactions.remove(globalTransaction); TxCompletionNotificationCommand command = commandsFactory.buildTxCompletionNotificationCommand(null, globalTransaction); rpcManager.invokeRemotely(null, command, rpcManager.getDefaultRpcOptions(false, DeliverOrder.NONE)); }); }
Source:
<code>protected boolean reconstructMaster() { newMasterStorageDomainId = getNewMasterId(); <START> proceedStorageDomainTreatmentByDomainType(getNewMaster(), false); <END> if (getParameters().isInactive() && !getStorageDomain().getId().equals(getNewMasterId())) { executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { setStorageDomainStatus(StorageDomainStatus.Inactive, getCompensationContext()); calcStoragePoolStatusByDomainsStatus(); getCompensationContext().stateChanged(); return null; } }); } if (_isLastMaster) { return stopSpm(); } boolean commandSucceeded = stopSpm(); final List<String> disconnectPoolFormats = Config.<List<String>> getValue( ConfigValues.DisconnectPoolOnReconstruct); if (commandSucceeded && disconnectPoolFormats.contains(getNewMaster().getStorageFormat().getValue())) { commandSucceeded = runVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getVds().getVdsSpmId()) ).getSucceeded(); } if (!commandSucceeded) { return false; } List<StoragePoolIsoMap> domains = getStoragePoolIsoMapDAO() .getAllForStoragePool(getStoragePool().getId()); setActionReturnValue(true); return runVdsCommand(VDSCommandType.ReconstructMaster, new ReconstructMasterVDSCommandParameters(getVds().getId(), getVds().getVdsSpmId(), getStoragePool().getId(), getStoragePool().getName(), getNewMasterId(), domains, getStoragePool().getMasterDomainVersion())).getSucceeded(); }</code><technical_language>newMasterStorageDomainId? (or removing newMasterStorageDomainId)</technical_language>

Target:
protected boolean reconstructMaster() { proceedStorageDomainTreatmentByDomainType(getNewMaster(), false); if (getParameters().isInactive() && !getStorageDomain().getId().equals(getNewMasterId())) { executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { setStorageDomainStatus(StorageDomainStatus.Inactive, getCompensationContext()); calcStoragePoolStatusByDomainsStatus(); getCompensationContext().stateChanged(); return null; } }); } if (_isLastMaster) { return stopSpm(); } boolean commandSucceeded = stopSpm(); final List<String> disconnectPoolFormats = Config.<List<String>> getValue( ConfigValues.DisconnectPoolOnReconstruct); if (commandSucceeded && disconnectPoolFormats.contains(getNewMaster().getStorageFormat().getValue())) { commandSucceeded = runVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getVds().getVdsSpmId()) ).getSucceeded(); } if (!commandSucceeded) { return false; } List<StoragePoolIsoMap> domains = getStoragePoolIsoMapDAO() .getAllForStoragePool(getStoragePool().getId()); setActionReturnValue(true); return runVdsCommand(VDSCommandType.ReconstructMaster, new ReconstructMasterVDSCommandParameters(getVds().getId(), getVds().getVdsSpmId(), getStoragePool().getId(), getStoragePool().getName(), getNewMasterId(), domains, getStoragePool().getMasterDomainVersion())).getSucceeded(); }
Source:
<code>public Object getMetaData(String fieldName) { if (fieldName.startsWith(ATTR_PREFIX)) { return root.getAttributeValue(null, getEntryFromCol(fieldName).substring(1)); } else if (fieldName.startsWith(ELEM_PREFIX)) { TreeElement child = root.getChild(getEntryFromCol(fieldName), 0); IAnswerData value = child.getValue(); if (value == null) { return ""; } else { return value.uncast().getString(); } } <START> return null; <END> }</code><technical_language>other implementations of getMetaData() throw IllegalArgumentException called a fieldName indexed column</technical_language>

Target:
public Object getMetaData(String fieldName) { if (fieldName.startsWith(ATTR_COL_PREFIX)) { return root.getAttributeValue(null, getElementOrAttributeFromSqlColumnName(fieldName).substring(ATTR_PREFIX_LENGTH)); } else if (fieldName.startsWith(ELEM_COL_PREFIX)) { TreeElement child = root.getChild(getElementOrAttributeFromSqlColumnName(fieldName), 0); if (child == null) { return null; } IAnswerData value = child.getValue(); if (value == null) { return null; } else { return value.uncast().getString(); } } throw new IllegalArgumentException("No metadata field " + fieldName + " in the indexed fixture storage table."); }
Source:
<code>public void getClassloaderFromAllDependenciesComplexTest() { Path path = Paths.get(".").resolve("src/test/projects/dummy_deps_complex"); AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.CLASSPATH_DEPS_AFTER_DECORATOR); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(path); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.ALTERNATE_USER_SETTINGS + alternateSettingsAbsPath, MavenConfig.DEPS_IN_MEMORY_BUILD_CLASSPATH}, Boolean.FALSE); CompilationResponse res = compiler.compile(req); assertThat(res.isSuccessful()).isTrue(); <START> assertThat(res.getDependencies().isEmpty()).isFalse(); <END> assertThat(res.getDependencies().size()).isEqualTo(7); }</code><technical_language>assertThat(collection).isNotEmpty() is shorter give error messages. 8x in this PR (Ctrl+f "isEmpty()).isFalse()")</technical_language>

Target:
public void getClassloaderFromAllDependenciesComplexTest() { Path path = Paths.get(".").resolve("target/test-classes/dummy_deps_complex"); AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.CLASSPATH_DEPS_AFTER_DECORATOR); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(path); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.ALTERNATE_USER_SETTINGS + alternateSettingsAbsPath, MavenConfig.DEPS_IN_MEMORY_BUILD_CLASSPATH}, Boolean.FALSE); CompilationResponse res = compiler.compile(req); assertThat(res.isSuccessful()).isTrue(); assertThat(res.getDependencies()).isNotEmpty(); assertThat(res.getDependencies()).hasSize(7); }
Source:
<code>public Optional<String> computeComment(final List<IBundle> presentBundles, IThrowable throwable) { if (packageAdmin == null) { return Optional.absent(); } List<String> problematicPackages = extractProblematicPackage(throwable); if (problematicPackages.isEmpty()) { return Optional.absent(); } Set<String> presentBundlesSymbolicNames = Sets.newHashSet(); for (IBundle presentBundle : presentBundles) { presentBundlesSymbolicNames.add(presentBundle.getName()); } StringBuilder comment = new StringBuilder(); <START> for (String problematicPackage : problematicPackages) { <END> comment.append(Formats.format(Messages.COMMENT_PROBLEMATIC_PACKAGE_ORIGIN_EXPORTS, problematicPackage)); ExportedPackage[] exportedPackages = packageAdmin.getExportedPackages(problematicPackage); if (ArrayUtils.isEmpty(exportedPackages)) { continue; } Multimap<org.osgi.framework.Bundle, org.osgi.framework.Bundle> exportersToImporters = HashMultimap.create(); for (ExportedPackage exportedPackage : exportedPackages) { org.osgi.framework.Bundle exportingBundle = exportedPackage.getExportingBundle(); if (!isPresent(exportingBundle)) { continue; } for (org.osgi.framework.Bundle importingBundle : exportedPackage.getImportingBundles()) { if (!isPresent(importingBundle)) { continue; } if (presentBundlesSymbolicNames.contains(importingBundle.getSymbolicName())) { exportersToImporters.put(exportingBundle, importingBundle); } } } if (exportersToImporters.isEmpty()) { continue; } for (Entry<org.osgi.framework.Bundle, Collection<org.osgi.framework.Bundle>> entry : exportersToImporters.asMap().entrySet()) { org.osgi.framework.Bundle exporter = entry.getKey(); Collection<org.osgi.framework.Bundle> importers = entry.getValue(); comment.append( Formats.format(Messages.COMMENT_PROBLEMATIC_PACKAGE_IMPORTS, exporter.getSymbolicName(), exporter.getVersion())); for (org.osgi.framework.Bundle importer : importers) { comment.append( Formats.format(Messages.COMMENT_PROBLEMATIC_PACKAGE_IMPORT, importer.getSymbolicName(), importer.getVersion())); } } } return Optional.of(comment.toString()); }</code><technical_language>split deeply nested for loops methods</technical_language>

Target:
public Optional<String> computeComment(final List<IBundle> presentBundles, IThrowable throwable) { if (packageAdmin == null) { return Optional.absent(); } List<String> problematicPackages = extractProblematicPackage(throwable); if (problematicPackages.isEmpty()) { return Optional.absent(); } Set<String> presentBundlesSymbolicNames = presentBundles.stream().map(bundle -> bundle.getName()).collect(Collectors.toSet()); StringBuilder commentBuilder = new StringBuilder(); for (String problematicPackage : problematicPackages) { Multimap<org.osgi.framework.Bundle, org.osgi.framework.Bundle> exportersToImporters = mapExportingToImportingBundles( presentBundlesSymbolicNames, problematicPackage); if (!exportersToImporters.isEmpty()) { appendProblematicPackageComment(problematicPackage, exportersToImporters, commentBuilder); } } String comment = commentBuilder.toString(); if (StringUtils.isEmpty(comment)) { return Optional.absent(); } else { return Optional.of(comment); } }
Source:
<code>private BundleNotFoundException unpackBundleNotFoundException(Throwable caught) { if (caught instanceof RuntimeException) { String message = caught.getMessage(); int patternStart = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START); <START> if (patternStart > 0) { <END> int patternEnd = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_END, patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length()); if (patternEnd > 0) { return new BundleNotFoundException( message.substring( patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length(), patternEnd)); } } } return null; }</code><technical_language>Please -1 found, index 0</technical_language>

Target:
private BundleNotFoundException unpackBundleNotFoundException(Throwable caught) { if (caught instanceof RuntimeException) { String message = caught.getMessage(); int patternStart = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START); if (patternStart > -1) { int patternEnd = message.indexOf(BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_END, patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length()); if (patternEnd > -1) { return new BundleNotFoundException( message.substring( patternStart + BUNDLE_NOT_FOUND_EXCEPTION_PATTERN_START.length(), patternEnd)); } } } return null; }
Source:
<code>private void validate(Scanner scanner, String[] expectedValues) { for (String expectedValue : expectedValues) { <START> assertThat(scanner.hasNext(), is(true)); <END> assertThat(scanner.next(), is(expectedValue)); } }</code><technical_language>want add a failure message this assertion includes expected value. failure message false expected true idea failed at</technical_language>

Target:
private void validate(Scanner scanner, String[] expectedValues) { for (String expectedValue : expectedValues) { assertThat( "Expected next value to be " + expectedValue + " but scanner.hasNext() returned false", scanner.hasNext(), is(true)); assertThat(scanner.next(), is(expectedValue)); } }
Source:
<code>private Set<byte[]> getKnownPayloadHashes() { Set<byte[]> excludedKeys; <START> if (seedNodeRepository != null && seedNodeRepository.isSeedNode(networkNode.getNodeAddress())) <END> excludedKeys = this.appendOnlyDataStoreService.getMap().keySet().stream() .map(e -> e.bytes) .collect(Collectors.toSet()); else excludedKeys = this.appendOnlyDataStoreService.getMap("since " + Version.VERSION).keySet().stream() .map(e -> e.bytes) .collect(Collectors.toSet()); Set<byte[]> excludedKeysFromPersistedEntryMap = this.map.keySet() .stream() .map(e -> e.bytes) .collect(Collectors.toSet()); excludedKeys.addAll(excludedKeysFromPersistedEntryMap); excludedKeys.add(getSpecialKey()); return excludedKeys; }</code><technical_language>Braces multi-line blocks helps readability in opinion</technical_language>

Target:
private Set<byte[]> getKnownPayloadHashes() { Set<byte[]> excludedKeys; boolean weAreASeedNode = seedNodeRepository != null && seedNodeRepository.isSeedNode(networkNode.getNodeAddress()); if (weAreASeedNode) { excludedKeys = getKeySetInBytes(this.appendOnlyDataStoreService.getMap()); } else { excludedKeys = getKeySetInBytes(this.appendOnlyDataStoreService.getMap("since " + Version.VERSION)); } Set<byte[]> excludedKeysFromPersistedEntryMap = getKeySetInBytes(this.map); excludedKeys.addAll(excludedKeysFromPersistedEntryMap); excludedKeys.add(getSpecialKey()); return excludedKeys; }
Source:
<code>public Collection<Partition<T>> updateBandwidth(Collection<Partition<T>> newpartitions, long currentBandwidth) { <START> LOG.info("Updating bandwidth of partitions."); <END> long newBandwidth = currentBandwidth / newpartitions.size(); for (Partition<T> partition : newpartitions) { partition.getPartitionedInstance().getBandwidthManager().setBandwidth(newBandwidth); } return newpartitions; }</code><technical_language>Is this logging necessary? add value</technical_language>

Target:
public Collection<Partition<T>> updateBandwidth(Collection<Partition<T>> newpartitions, long currentBandwidth) { long newBandwidth = currentBandwidth / newpartitions.size(); for (Partition<T> partition : newpartitions) { partition.getPartitionedInstance().getBandwidthManager().setBandwidth(newBandwidth); } LOG.info("Updating bandwidth of partitions to value: " + newBandwidth); return newpartitions; }
Source:
<code>public void addMembers(PerunSession sess, Group group, List<Member> members) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); for (Member member : members) { getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { <START> throw new PrivilegeException(sess, "addMember"); <END> } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if ("true".equals(attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMembers(sess, group, members); }</code><technical_language>"addMembers" in passed param reflect method name</technical_language>

Target:
public void addMembers(PerunSession sess, Group group, List<Member> members) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); for (Member member : members) { getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMembers"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if ("true".equals(attrSynchronizeEnabled.getValue()) || getGroupsManagerBl().isGroupInStructureSynchronizationTree(sess, group)) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMembers(sess, group, members); }
Source:
<code>public void checkSymbolExistence(SensorContextTester context, int line, int column, boolean mustExist) { Collection<TextRange> foundReferences = context.referencesForSymbolAt(componentKey, line, column); if (mustExist) { String message = "a symbol is expected to exist at line " + line + " and column " + column; <START> assertThat(foundReferences).as(message).isEmpty(); <END> } else { String message = "no symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isEmpty(); } }</code><technical_language>@ivandalbosco this assertion</technical_language>

Target:
public void checkSymbolExistence(SensorContextTester context, int line, int column, boolean mustExist) { Collection<TextRange> foundReferences = context.referencesForSymbolAt(componentKey, line, column); if (mustExist) { String message = "a symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isNotNull(); } else { String message = "no symbol is expected to exist at line " + line + " and column " + column; assertThat(foundReferences).as(message).isEmpty(); } }
Source:
<code>public void testTypeParameterTree() { Class c = Class.clas(Option.none().getClass()); Collection<Type> coll = c.classParameters().toCollection(); for (Type t: coll) { Class.typeParameterTree(t); <START> } <END> }</code><technical_language>Do want assert in this method</technical_language>

Target:
public void testTypeParameterTree() { Class c = Class.clas(Option.none().getClass()); Collection<Type> coll = c.classParameters().toCollection(); for (Type t: coll) { assertThat(Class.typeParameterTree(t).toString(), is("Tree(class fj.data.Option$None)")); } }
Source:
<code>public void dump(PrintWriter pw) { mLog.dump(null, pw, null); <START> ConnectivityModuleConnector.getInstance().dump(pw); <END> pw.println(); }</code><technical_language>NetworkStackClient alreay dump ConnectivityModuleConnector. Do need dump again? <LINK_0>"ConnectivityModuleConnector.getInstance().dump"&sq=package:aosp-master&g=0&l=331</technical_language>

Target:
public void dump(PrintWriter pw) { mLog.dump(null, pw, null); pw.println(); }
Source:
<code>public boolean delete() { <START> List<Lock> locks = new ArrayList<Lock>(); <END> lockRecursively(locks); try { List<ResourceNotification.Event> events = SimpleResourceWatcher.createEvents(this, ResourceNotification.Kind.ENTRY_DELETE); if (entry.delete()) { resourceWatcher.changed(new ResourceNotification(path(), ResourceNotification.Kind.ENTRY_DELETE, System.currentTimeMillis(), events)); return true; } else { return false; } } finally { for (Lock lock : locks) { lock.release(); } } }</code><technical_language>I is a good idiom for try-with-resources a collection? a Closeable Lock, a Closeable LockCollection Lock CollectionTree (for recursive closure)</technical_language>

Target:
public boolean delete() { List<Lock> locks = new ArrayList<Lock>(); lockRecursively(locks); try { List<ResourceNotification.Event> events = SimpleResourceNotificationDispatcher.createEvents(this, ResourceNotification.Kind.ENTRY_DELETE); if (entry.delete()) { resourceWatcher.changed(new ResourceNotification(path(), ResourceNotification.Kind.ENTRY_DELETE, System.currentTimeMillis(), events)); return true; } else { return false; } } finally { for (Lock lock : locks) { lock.release(); } } }
Source:
<code>private boolean hasIpv6Gateway(VdsNetworkInterface iface) { return <START> iface!= null <END> && !IpAddressPredicate.isUnspecifiedIpv6(iface.getIpv6Gateway()); }</code><technical_language>Is this check needed? is called test function this check</technical_language>

Target:
private boolean hasIpv6Gateway(VdsNetworkInterface iface) { return iface!= null && Ipv6UnspecifiedPredicate.INSTANCE.negate().test(iface.getIpv6Gateway()); }
Source:
<code>public void onItemClick(BoxItem item) { <START> BoxBrowseFragment browseFrag = getTopBrowseFragment(); <END> if (browseFrag != null) { browseFrag.onItemClick(item); } if (item instanceof BoxFolder) { handleBoxFolderClicked((BoxFolder) item); } }</code><technical_language>thinking it, I this trip behavior fragment is calling activity is calling fragment. I behavior is for fragment item click</technical_language>

Target:
public void onItemClick(BoxItem item) { if (item instanceof BoxFolder) { mCurrentBoxFolder = (BoxFolder) item; handleBoxFolderClicked(mCurrentBoxFolder); } }
Source:
<code>public void addNewField() { Field field = newFieldToAddProperty.getValue(); FieldViewModel model = new FieldViewModel(field, true, FieldPriority.IMPORTANT, selectedEntryTypesProperty.getValue()); typesWithFields.computeIfAbsent(selectedEntryTypesProperty.getValue(), key -> new ArrayList<>()).add(model); <START> fieldsForType.add(model); <END> }</code><technical_language>Reset newFieldToAddProperty empty, i.e. clear textfield adding</technical_language>

Target:
public void addNewField() { Field field = newFieldToAdd.getValue(); FieldViewModel model = new FieldViewModel(field, true, FieldPriority.IMPORTANT, selectedEntryTypes.getValue()); typesWithFields.computeIfAbsent(selectedEntryTypes.getValue(), key -> new ArrayList<>()).add(model); allFieldsForType.add(model); newFieldToAddProperty().setValue(null); }
Source:
<code>public ProjectAccess call() throws NoSuchProjectException, IOException, ConfigInvalidException { pc = open(); ProjectConfig config; MetaDataUpdate md = metaDataUpdateFactory.create(projectName); try { config = ProjectConfig.read(md); if (config.updateGroupNames(groupCache)) { md.setMessage("Update group names\n"); if (config.commit(md)) { projectCache.evict(config.getProject()); pc = open(); } } else if (config.getRevision() != null && !config.getRevision().equals( pc.getProjectState().getConfig().getRevision())) { projectCache.evict(config.getProject()); pc = open(); } } finally { md.close(); } List<AccessSection> local = new ArrayList<AccessSection>(); for (AccessSection section : config.getAccessSections()) { RefControl rc = pc.controlForRef(section.getRefPattern()); if (rc.isVisible() || rc.isOwner()) { local.add(section); } } final ProjectAccess detail = new ProjectAccess(); detail.setRevision(config.getRevision().name()); detail.setLocal(local); <START> detail.setOwnerOf(getOwnedRefs()); <END> if (projectName.equals(wildProject)) { detail.setInheritsFrom(null); } else if (config.getProject().getParent() != null) { detail.setInheritsFrom(config.getProject().getParent()); } else { detail.setInheritsFrom(wildProject); } return detail; }</code><technical_language>I fix is more like: if (ownerOf.isEmpty() && pc.isOwner()) { ownerOf.add(AccessSection.ALL); }</technical_language>

Target:
public ProjectAccess call() throws NoSuchProjectException, IOException, ConfigInvalidException { pc = open(); ProjectConfig config; MetaDataUpdate md = metaDataUpdateFactory.create(projectName); try { config = ProjectConfig.read(md); if (config.updateGroupNames(groupCache)) { md.setMessage("Update group names\n"); if (config.commit(md)) { projectCache.evict(config.getProject()); pc = open(); } } else if (config.getRevision() != null && !config.getRevision().equals( pc.getProjectState().getConfig().getRevision())) { projectCache.evict(config.getProject()); pc = open(); } } finally { md.close(); } List<AccessSection> local = new ArrayList<AccessSection>(); Set<String> ownerOf = new HashSet<String>(); for (AccessSection section : config.getAccessSections()) { RefControl rc = pc.controlForRef(section.getRefPattern()); if (rc.isOwner()) { local.add(section); ownerOf.add(section.getRefPattern()); } else if (rc.isVisible()) { local.add(section); } } if (ownerOf.isEmpty() && pc.isOwnerAnyRef()) { ownerOf.add(AccessSection.ALL); } final ProjectAccess detail = new ProjectAccess(); detail.setRevision(config.getRevision().name()); detail.setLocal(local); detail.setOwnerOf(ownerOf); if (projectName.equals(wildProject)) { detail.setInheritsFrom(null); } else if (config.getProject().getParent() != null) { detail.setInheritsFrom(config.getProject().getParent()); } else { detail.setInheritsFrom(wildProject); } return detail; }
Source:
<code>public Response saveAttachment(InputStream in, String name, String contentType, String docId, String docRev) { assertNotEmpty(in, "in"); assertNotEmpty(name, "name"); assertNotEmpty(contentType, "ContentType"); if (docId == null) { docId = generateUUID(); <START> } <END> final URI uri = new DatabaseURIHelper(dbUri).attachmentUri(docId, docRev, name); return couchDbClient.put(uri, in, contentType); }</code><technical_language>is desired behavior if docId is null is of length 0</technical_language>

Target:
public Response saveAttachment(InputStream in, String name, String contentType, String docId, String docRev) { assertNotEmpty(in, "in"); assertNotEmpty(name, "name"); assertNotEmpty(contentType, "ContentType"); if (docId == null) { docId = generateUUID(); assertNull(docRev, "docRev"); } else { assertNotEmpty(docId, "docId"); if (docRev != null) { assertNotEmpty(docRev, "docRev"); } } final URI uri = new DatabaseURIHelper(dbUri).attachmentUri(docId, docRev, name); return couchDbClient.put(uri, in, contentType); }