auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected String doInBackground(String... params) { String path = params[0]; File downloadedImages = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + Uri.parse(path).getLastPathSegment()); int total = 0; int count = 0; try { URL url = new URL(path); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); imageLength = urlConnection.getContentLength(); boolean isFileCreated = downloadedImages.exists(); InputStream inputStream = new BufferedInputStream(url.openStream(), 8192); byte[] data = new byte[1024]; OutputStream outputStream = new FileOutputStream(downloadedImages); if (!isFileCreated) { isFileCreated = downloadedImages.createNewFile(); } while ((count = inputStream.read(data)) != -1) { total = total + count; outputStream.write(data, 0, count); calculatedProgress = (int) total * 100 / imageLength; publishProgress(total); } inputStream.close(); outputStream.close(); } catch (MalformedURLException e) { <START> e.printStackTrace(); <END> } catch (IOException e) { e.printStackTrace(); } return String.valueOf(downloadedImages); }</code><technical_language>Zlog.logException(e) here</technical_language>

Target:
protected String doInBackground(String... params) { String path = params[0]; File downloadedImages = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/" + Uri.parse(path).getLastPathSegment()); int total = 0; int count = 0; try { URL url = new URL(path); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); imageLength = urlConnection.getContentLength(); boolean isFileCreated = downloadedImages.exists(); InputStream inputStream = new BufferedInputStream(url.openStream(), 8192); byte[] data = new byte[1024]; OutputStream outputStream = new FileOutputStream(downloadedImages); if (!isFileCreated) { isFileCreated = downloadedImages.createNewFile(); } while ((count = inputStream.read(data)) != -1) { total = total + count; outputStream.write(data, 0, count); calculatedProgress = (int) total * 100 / imageLength; publishProgress(total); } inputStream.close(); outputStream.close(); } catch (MalformedURLException e) { ZLog.logException(e); } catch (IOException e) { ZLog.logException(e); } return String.valueOf(downloadedImages); }
Source:
<code>private boolean createPropertiesTable() { Statement sta; try { sta = conn.createStatement(); <START> String payload = "CREATE TABLE PROPERTIES (Name VARCHAR(100), Type VARCHAR(20), Value VARCHAR(50))"; <END> int count = sta.executeUpdate(payload); return true; } catch (SQLException e) { log.warn("Could not create the properties table! Properties will not be saved!!"); log.warn(e.toString()); e.printStackTrace(); } return false; }</code><technical_language>yeah uniqueness constraint</technical_language>

Target:
private boolean createPropertiesTable() { Statement sta; try { sta = conn.createStatement(); String payload = "CREATE TABLE PROPERTIES (Name VARCHAR(100), Type VARCHAR(20), Value VARCHAR(50), UNIQUE (Name))"; int count = sta.executeUpdate(payload); return true; } catch (SQLException e) { log.warn("Could not create the properties table! Properties will not be saved!!"); log.warn(e.toString()); e.printStackTrace(); } return false; }
Source:
<code>public Iterator<String> getGcCandidates(DataLevel level, String continuePoint) { if (level == DataLevel.ROOT) { byte[] json = context.getZooCache() .get(context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_GC_CANDIDATES); Stream<String> candidates = RootGcCandidates.fromJson(json).stream().sorted(); if (continuePoint != null && !continuePoint.isEmpty()) { candidates = candidates.dropWhile(candidate -> candidate.compareTo(continuePoint) <= 0); } return candidates.iterator(); } else if (level == DataLevel.METADATA || level == DataLevel.USER) { Range range = MetadataSchema.DeletesSection.getRange(); if (continuePoint != null && !continuePoint.isEmpty()) { String continueRow = MetadataSchema.DeletesSection.getRowPrefix() + SortSkew.getCode(continuePoint) + continuePoint; range = new Range(new Key(continueRow).followingKey(PartialKey.ROW), true, range.getEndKey(), range.isEndKeyInclusive()); } Scanner scanner; try { scanner = context.createScanner(level.metaTable(), Authorizations.EMPTY); } catch (TableNotFoundException e) { throw new RuntimeException(e); } scanner.setRange(range); return Iterators.transform(scanner.iterator(), <START> entry -> entry.getKey().getRow().toString().substring(getDeletePrefixLength())); <END> } else { throw new IllegalArgumentException(); } }</code><technical_language>This MetadataSchema.DeletesSection.decodeDeleteRow(entry.getKey().getRow()) similar</technical_language>

Target:
public Iterator<String> getGcCandidates(DataLevel level, String continuePoint) { if (level == DataLevel.ROOT) { byte[] json = context.getZooCache() .get(context.getZooKeeperRoot() + RootTable.ZROOT_TABLET_GC_CANDIDATES); Stream<String> candidates = RootGcCandidates.fromJson(json).stream().sorted(); if (continuePoint != null && !continuePoint.isEmpty()) { candidates = candidates.dropWhile(candidate -> candidate.compareTo(continuePoint) <= 0); } return candidates.iterator(); } else if (level == DataLevel.METADATA || level == DataLevel.USER) { Range range = MetadataSchema.DeletesSection.getRange(); if (continuePoint != null && !continuePoint.isEmpty()) { String continueRow = MetadataSchema.DeletesSection.encodeRow(continuePoint); range = new Range(new Key(continueRow).followingKey(PartialKey.ROW), true, range.getEndKey(), range.isEndKeyInclusive()); } Scanner scanner; try { scanner = context.createScanner(level.metaTable(), Authorizations.EMPTY); } catch (TableNotFoundException e) { throw new RuntimeException(e); } scanner.setRange(range); return Iterators.transform(scanner.iterator(), entry -> MetadataSchema.DeletesSection.decodeRow(entry.getKey().getRow().toString())); } else { throw new IllegalArgumentException(); } }
Source:
<code><START> public boolean barrierAnnouncement( <END> InputChannelInfo channelInfo, CheckpointBarrier announcedBarrier, int sequenceNumber) { checkState( sequenceNumberInAnnouncedChannels.put(channelInfo, sequenceNumber) == null, "Stream corrupt: Repeated barrierAnnouncement for same checkpoint on input " + channelInfo); return false; }</code><technical_language>nit: args line? valid for methods in this package</technical_language>

Target:
public void barrierAnnouncement( InputChannelInfo channelInfo, CheckpointBarrier announcedBarrier, int sequenceNumber) { Integer previousValue = sequenceNumberInAnnouncedChannels.put(channelInfo, sequenceNumber); checkState( previousValue == null, "Stream corrupt: Repeated barrierAnnouncement [%s] overwriting [%s] for the same checkpoint on input %s", announcedBarrier, sequenceNumber, channelInfo); }
Source:
<code>private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots = prepareSnapshotConfigurationsWithoutImage(diskImage.getId()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); <START> while (!imageTemplate.equals(currentGuid) && !currentGuid.equals(Guid.Empty)) { <END> RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "RemoveImageCommand::RemoveImageFromDB: 'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); for (Snapshot s : updatedSnapshots) { getSnapshotDao().update(s); } return null; } }); }</code><technical_language>inconsistent here. I readable if currentGuid argument i.e. !currentGuid.equals(imageTemplate) &&</technical_language>

Target:
private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); for (Snapshot s : updatedSnapshots) { getSnapshotDao().update(s); } return null; } }); }
Source:
<code>public boolean isIntentToAdd() { <START> return (getExtendedFlags() & INTENT_TO_ADD) == INTENT_TO_ADD; <END> }</code><technical_language>bit is set not, != 0 is a faster test here</technical_language>

Target:
public boolean isIntentToAdd() { return (getExtendedFlags() & INTENT_TO_ADD) != 0; }
Source:
<code>private static boolean insideCondition(SyntaxToken token) { Tree treeWithCondition = CheckUtils.getFirstAncestor(token, Kind.IF_STATEMENT, Kind.WHILE_STATEMENT, Kind.DO_WHILE_STATEMENT, Kind.FOR_STATEMENT, Kind.CONDITIONAL_EXPRESSION); <START> <END> Tree condition = condition(treeWithCondition); return condition != null && ((JavaScriptTree) condition).isAncestorOf((JavaScriptTree) token); }</code><technical_language>I check for a null treeWithCondition return false passing condition method a nullable</technical_language>

Target:
private static boolean insideCondition(SyntaxToken token) { Tree treeWithCondition = CheckUtils.getFirstAncestor(token, Kind.IF_STATEMENT, Kind.WHILE_STATEMENT, Kind.DO_WHILE_STATEMENT, Kind.FOR_STATEMENT, Kind.CONDITIONAL_EXPRESSION); if (treeWithCondition == null) { return false; } Tree condition = condition(treeWithCondition); return condition != null && ((JavaScriptTree) condition).isAncestorOf((JavaScriptTree) token); }
Source:
<code>private List<String> getCellValues(Row row) { <START> List<String> values = new ArrayList<>(); <END> for (Cell cell : row) { values.add(cell.getStringCellValue()); } return values; }</code><technical_language>Iterables.transform</technical_language>

Target:
private List<String> getCellValues(Row row) { return Lists.newArrayList(Iterables.transform(row, Cell::getStringCellValue)); }
Source:
<code>private boolean isFromCurrentScope(VariableIdentifierTree variableIdentifierTree) { SyntaxToken variableToken = variableIdentifierTree.token(); <START> Scope currentScope = scopes.peek(); <END> return currentScope != null && currentScope.getSymbols(Symbol.Kind.VARIABLE).stream() .filter(symbol -> currentScope.equals(symbol.scope())) .flatMap(symbol -> symbol.usages().stream()) .anyMatch(variableToken::equals); }</code><technical_language>support visitMethodDeclaration</technical_language>

Target:
private boolean isFromCurrentScope(VariableIdentifierTree variableIdentifierTree) { SyntaxToken variableToken = variableIdentifierTree.token(); Scope currentScope = scopes.peek(); return currentScope != null && currentScope.getSymbols(Symbol.Kind.VARIABLE).stream() .filter(symbol -> !(symbol.hasModifier("static") || symbol.hasModifier("global"))) .filter(symbol -> currentScope.equals(symbol.scope())) .flatMap(symbol -> symbol.usages().stream()) .anyMatch(variableToken::equals); }
Source:
<code>public static String getAppHome() { <START> String appHome = System.getenv("ORIENTEER_APP_HOME"); <END> return Strings.isEmpty(appHome) ? "./" : appHome; }</code><technical_language>Why, btw ORIENTEER_APP_HOME, ORIENTEER_HOME</technical_language>

Target:
public static String getAppHome() { String appHome = System.getenv(ENV_ORIENTEER_HOME); return Strings.isEmpty(appHome) ? "./" : appHome; }
Source:
<code>private ReplChangeManager(Configuration conf) throws MetaException { try { if (!inited) { if (MetastoreConf.getBoolVar(conf, ConfVars.REPLCMENABLED)) { ReplChangeManager.enabled = true; ReplChangeManager.conf = conf; Path cmroot = new Path(MetastoreConf.getVar(conf, ConfVars.REPLCMDIR)); FileSystem cmFs = cmroot.getFileSystem(conf); if (!cmFs.exists(cmroot)) { cmFs.mkdirs(cmroot); cmFs.setPermission(cmroot, new FsPermission("700")); } <START> cmRootMapping.put(NO_ENCRYPTION, cmroot); <END> UserGroupInformation usergroupInfo = UserGroupInformation.getCurrentUser(); msUser = usergroupInfo.getShortUserName(); msGroup = usergroupInfo.getPrimaryGroupName(); } inited = true; } } catch (IOException e) { throw new MetaException(StringUtils.stringifyException(e)); } }</code><technical_language>check if default path is encrypted ..then store NO_ENCRYPTION</technical_language>

Target:
private ReplChangeManager(Configuration conf) throws MetaException { try { if (!inited) { if (MetastoreConf.getBoolVar(conf, ConfVars.REPLCMENABLED)) { ReplChangeManager.enabled = true; ReplChangeManager.conf = conf; cmRootDir = MetastoreConf.getVar(conf, ConfVars.REPLCMDIR); encryptedCmRootDir = MetastoreConf.getVar(conf, ConfVars.REPLCMENCRYPTEDDIR); fallbackNonEncryptedCmRootDir = MetastoreConf.getVar(conf, ConfVars.REPLCMFALLBACKNONENCRYPTEDDIR); Path cmroot = new Path(cmRootDir); createCmRoot(cmroot); FileSystem cmRootFs = cmroot.getFileSystem(conf); HdfsEncryptionShim pathEncryptionShim = hadoopShims .createHdfsEncryptionShim(cmRootFs, conf); Path cmRootEncrypted = new Path(encryptedCmRootDir); if (cmRootEncrypted.isAbsolute()) { throw new MetaException(ConfVars.REPLCMENCRYPTEDDIR.getHiveName() + " should be a relative path"); } if (pathEncryptionShim.isPathEncrypted(cmroot)) { String encryptionZonePath = cmRootFs.getUri() + pathEncryptionShim.getEncryptionZoneForPath(cmroot).getPath(); encryptionZones.put(encryptionZonePath, cmRootDir); } else { encryptionZones.put(NO_ENCRYPTION, cmRootDir); } UserGroupInformation usergroupInfo = UserGroupInformation.getCurrentUser(); msUser = usergroupInfo.getShortUserName(); msGroup = usergroupInfo.getPrimaryGroupName(); } inited = true; } } catch (IOException e) { throw new MetaException(StringUtils.stringifyException(e)); } }
Source:
<code>public boolean validPdpAddress(String employeeId) { Person employee = findPerson(employeeId); boolean validPerson = validPerson(employee); boolean validAddress = validPerson; if (validPerson) { String state = employee.getAddressStateProvinceCodeUnmasked(); String country = employee.getAddressCountryCodeUnmasked(); if (StringUtils.isBlank(state) && StringUtils.isBlank(country)) { validAddress = false; LOG.error("validPdpAddress, " + employee.getName() + " does not have a Country Code or a State/Province code."); } else { if (LOG.isDebugEnabled()) { <START> LOG.debug("validPdpAddress, The employee " + employee.getName() + " had a country code or state code." ); <END> } } } return validAddress; }</code><technical_language>state country logged</technical_language>

Target:
public boolean validPdpAddress(String employeeId) { Person employee = findPerson(employeeId); boolean validPerson = validPerson(employee); boolean validAddress = validPerson; if (validPerson) { String state = employee.getAddressStateProvinceCodeUnmasked(); String country = employee.getAddressCountryCodeUnmasked(); if (StringUtils.isBlank(state) && StringUtils.isBlank(country)) { validAddress = false; LOG.error("validPdpAddress, " + employee.getName() + " does not have a Country Code or a State/Province code."); } else { if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder("validPdpAddress, The employee "); sb.append(employee.getName()).append(" has a valid PDP address. The state code was '").append(state); sb.append("' and the country code was '").append(country).append("'."); LOG.debug(sb.toString()); } } } return validAddress; }
Source:
<code><START> protected Stream<ScheduledJob> allJobsWithEveryAnnotation() { <END> return Arrays.stream(this.jobs) .filter(job -> job.getClass().isAnnotationPresent(Every.class)) .map(job -> { Class<? extends Job> clazz = job.getClass(); Every everyAnnotation = clazz.getAnnotation(Every.class); boolean requestRecovery = everyAnnotation.requestRecovery(); boolean storeDurably = everyAnnotation.storeDurably(); String value = everyAnnotation.value(); if (value.isEmpty() || value.matches("\\$\\{.*\\}")) { value = readDurationFromConfig(everyAnnotation, clazz, configuration); log.info(clazz + " is configured in the config file to run every " + value); } long milliSeconds = TimeParserUtil.parseDuration(value); SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInMilliseconds(milliSeconds); int repeatCount = everyAnnotation.repeatCount(); applyRepeatCount(repeatCount, scheduleBuilder); MisfirePolicy misfirePolicy = everyAnnotation.misfirePolicy(); applyMisfirePolicy(misfirePolicy, scheduleBuilder); DateTime start = extractStart(clazz); int priority = everyAnnotation.priority(); Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder) .startAt(start.toDate()) .withPriority(priority) .build(); JobKey jobKey = createJobKey(everyAnnotation.jobName(), job); String message = extractMessage(clazz, jobKey); return new ScheduledJob(jobKey, clazz, trigger, requestRecovery, storeDurably, message); }); }</code><technical_language>Method allJobsWithEveryAnnotation 29 lines of code (exceeds 25 allowed). Consider refactoring</technical_language>

Target:
protected Stream<ScheduledJob> allJobsWithEveryAnnotation() { return Arrays.stream(this.jobs) .filter(job -> job.getClass().isAnnotationPresent(Every.class)) .map(job -> { Class<? extends Job> clazz = job.getClass(); Every everyAnnotation = clazz.getAnnotation(Every.class); long interval = getInterval(clazz, everyAnnotation); SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInMilliseconds(interval); int repeatCount = everyAnnotation.repeatCount(); applyRepeatCount(repeatCount, scheduleBuilder); MisfirePolicy misfirePolicy = everyAnnotation.misfirePolicy(); applyMisfirePolicy(misfirePolicy, scheduleBuilder); DateTime start = extractStart(clazz); int priority = everyAnnotation.priority(); Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder) .startAt(start.toDate()) .withPriority(priority) .build(); JobKey jobKey = createJobKey(everyAnnotation.jobName(), job); String message = extractMessage(clazz, jobKey); boolean requestRecovery = everyAnnotation.requestRecovery(); boolean storeDurably = everyAnnotation.storeDurably(); return new ScheduledJob(jobKey, clazz, trigger, requestRecovery, storeDurably, message); }); }
Source:
<code>private boolean isLastKilledQueryGone() { boolean lastKilledQueryIsGone = (lastKilledQuery == null); <START> if (!lastKilledQueryIsGone) { <END> ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); if (generalPool != null) { lastKilledQueryIsGone = generalPool.getQueryMemoryReservations().containsKey(lastKilledQuery); } } return lastKilledQueryIsGone; }</code><technical_language>Invert this returns early</technical_language>

Target:
private boolean isLastKilledQueryGone() { if (lastKilledQuery == null) { return true; } ClusterMemoryPool generalPool = pools.get(GENERAL_POOL); if (generalPool == null) { return false; } return generalPool.getQueryMemoryReservations().containsKey(lastKilledQuery); }
Source:
<code>protected FeedbackSessionAttributes extractFeedbackSessionData() { FeedbackSessionAttributes newSession = new FeedbackSessionAttributes(); newSession.setCourseId(getRequestParamValue(Const.ParamsNames.COURSE_ID)); newSession.setFeedbackSessionName(SanitizationHelper.sanitizeTitle( getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME))); newSession.setFeedbackSessionType(FeedbackSessionType.STANDARD); <START> newSession = setTime(newSession); <END> String paramTimeZone = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_TIMEZONE); if (paramTimeZone != null) { try { newSession.setTimeZone(Double.parseDouble(paramTimeZone)); } catch (NumberFormatException nfe) { log.warning("Failed to parse time zone parameter: " + paramTimeZone); } } String paramGracePeriod = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_GRACEPERIOD); try { newSession.setGracePeriod(Integer.parseInt(paramGracePeriod)); } catch (NumberFormatException nfe) { log.warning("Failed to parse graced period parameter: " + paramGracePeriod); } String type = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_RESULTSVISIBLEBUTTON); newSession = setResultsVisibleFromTime(newSession, type); type = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_SESSIONVISIBLEBUTTON); newSession = setSessionVisibleFromTime(newSession, type); newSession = setEmail(newSession); return newSession; }</code><technical_language>I need return newSession time call a set* method</technical_language>

Target:
protected FeedbackSessionAttributes extractFeedbackSessionData() { FeedbackSessionAttributes newSession = new FeedbackSessionAttributes(); newSession.setCourseId(getRequestParamValue(Const.ParamsNames.COURSE_ID)); newSession.setFeedbackSessionName(SanitizationHelper.sanitizeTitle( getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME))); newSession.setFeedbackSessionType(FeedbackSessionType.STANDARD); setTime(newSession); setTimeZone(newSession); setGracePeriod(newSession); setResultsVisibleFromTime(newSession); setSessionVisibleFromTime(newSession); setEmail(newSession); return newSession; }
Source:
<code>public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable { if (ctx.isOriginLocal()) { if (forceRemoteReadForFunctionalCommands && !command.hasAnyFlag(FlagBitSets.SKIP_XSITE_BACKUP)) { CompletableFuture<Void> cf = remoteGetAll(ctx, command, command.getAffectedKeys(), RemoteGetAllForWriteHandler.INSTANCE); if (cf == null) { <START> return invokeNext(ctx, command); <END> } else { return asyncInvokeNext(ctx, command, cf); } } else { return handleFunctionalReadManyCommand(ctx, command, readWriteManyHelper); } } else { return handleTxWriteManyCommand(ctx, command, command.getAffectedKeys(), readWriteManyHelper::copyForLocal); } }</code><technical_language>remoteGetAll() return a CompletableFutures.completedNull(), need if</technical_language>

Target:
public Object visitReadWriteManyCommand(InvocationContext ctx, ReadWriteManyCommand command) throws Throwable { if (ctx.isOriginLocal()) { if (forceRemoteReadForFunctionalCommands && !command.hasAnyFlag(FlagBitSets.SKIP_XSITE_BACKUP)) { CompletableFuture<Void> cf = remoteGetAll(ctx, command, command.getAffectedKeys(), RemoteGetAllForWriteHandler.INSTANCE); return asyncInvokeNext(ctx, command, cf); } else { return handleFunctionalReadManyCommand(ctx, command, readWriteManyHelper); } } else { return handleTxWriteManyCommand(ctx, command, command.getAffectedKeys(), readWriteManyHelper::copyForLocal); } }
Source:
<code>public void display(OutputStream out) { final PrintWriter stdout; try { stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM lacks UTF-8 encoding", e); } Map<String, PluginInfo> output = Maps.newTreeMap(); List<Plugin> plugins = pluginLoader.getPlugins(); Collections.sort(plugins, new Comparator<Plugin>() { @Override public int compare(Plugin a, Plugin b) { return a.getName().compareTo(b.getName()); } }); if (!format.isJson()) { stdout.format("%-30s %-10s\n", "Name", "Version"); stdout .print("----------------------------------------------------------------------\n"); } for (Plugin p : plugins) { PluginInfo info = new PluginInfo(); <START> info.name = p.getName(); <END> info.version = p.getVersion(); if (format.isJson()) { output.put(info.name, info); } else { stdout.format("%-30s %-10s\n", info.name, Strings.nullToEmpty(info.version)); } } if (format.isJson()) { format.newGson().toJson(output, new TypeToken<Map<String, PluginInfo>>() {}.getType(), stdout); stdout.print('\n'); } stdout.flush(); }</code><technical_language>unnecessary line, drop this</technical_language>

Target:
public void display(OutputStream out) { final PrintWriter stdout; try { stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("JVM lacks UTF-8 encoding", e); } Map<String, PluginInfo> output = Maps.newTreeMap(); List<Plugin> plugins = Lists.newArrayList(pluginLoader.getPlugins()); Collections.sort(plugins, new Comparator<Plugin>() { @Override public int compare(Plugin a, Plugin b) { return a.getName().compareTo(b.getName()); } }); if (!format.isJson()) { stdout.format("%-30s %-10s\n", "Name", "Version"); stdout .print("----------------------------------------------------------------------\n"); } for (Plugin p : plugins) { PluginInfo info = new PluginInfo(); info.version = p.getVersion(); if (format.isJson()) { output.put(p.getName(), info); } else { stdout.format("%-30s %-10s\n", p.getName(), Strings.nullToEmpty(info.version)); } } if (format.isJson()) { format.newGson().toJson(output, new TypeToken<Map<String, PluginInfo>>() {}.getType(), stdout); stdout.print('\n'); } stdout.flush(); }
Source:
<code>public void saveFile() throws IOException { <START> File file = new File("src/test/resources/metadata/testmetaOldFormat.xml"); <END> testMetaOldFormat = FileLoader.readFileToByteArray(file); }</code><technical_language>Again, IOUtils</technical_language>

Target:
public void saveFile() throws IOException { File file = new File("src/test/resources/metadata/testmetaOldFormat.xml"); testMetaOldFormat = IOUtils.toByteArray(file.toURI()); }
Source:
<code>PackageBinding addPackage(PackageBinding packageBinding, boolean checkForSplit) { if (packageBinding.isDeclaredIn(this)) { char[] packageName = packageBinding.readableName(); if (checkForSplit && this.environment.useModuleSystem) { char[][] declaringModuleNames = null; if (isUnnamed()) { IModuleAwareNameEnvironment moduleEnv = (IModuleAwareNameEnvironment) this.environment.nameEnvironment; declaringModuleNames = moduleEnv.getUniqueModulesDeclaringPackage(new char[][] {packageName}, ANY); } packageBinding = combineWithPackagesFromOtherRelevantModules(packageBinding, packageBinding.compoundName, declaringModuleNames); } this.declaredPackages.put(packageName, <START> packageBinding.getVisibleFor(this, true, true )); <END> if (packageBinding.parent == null) { this.environment.knownPackages.put(packageName, packageBinding); } } return packageBinding; }</code><technical_language>In theory getVisibleFor return a SplitPackageBinding, this break invariant declaredPackages them. surrounding packageBinding.isDeclaredIn(this) ensures this happen (assuming bug in SPB.getVisibleFor is fixed). obvious, packageBinding.getIncarnation(this) instead, returns a SBP returns a non-null result of surrounding if(...)</technical_language>

Target:
PackageBinding addPackage(PackageBinding packageBinding, boolean checkForSplit) { if (packageBinding.isDeclaredIn(this)) { char[] packageName = packageBinding.readableName(); if (checkForSplit && this.environment.useModuleSystem) { char[][] declaringModuleNames = null; if (isUnnamed()) { IModuleAwareNameEnvironment moduleEnv = (IModuleAwareNameEnvironment) this.environment.nameEnvironment; declaringModuleNames = moduleEnv.getUniqueModulesDeclaringPackage(new char[][] {packageName}, ANY); } packageBinding = combineWithPackagesFromOtherRelevantModules(packageBinding, packageBinding.compoundName, declaringModuleNames); } this.declaredPackages.put(packageName, packageBinding.getIncarnation(this)); if (packageBinding.parent == null) { this.environment.knownPackages.put(packageName, packageBinding); } } return packageBinding; }
Source:
<code>private boolean rollbackOtherTransaction(long startTs, TransactionService transactionService) { try { transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS); transactionOutcomeMetrics.markRollbackOtherTransaction(); return true; } catch (KeyAlreadyExistsException e) { <START> return false; <END> } }</code><technical_language>drop DEBUG</technical_language>

Target:
private boolean rollbackOtherTransaction(long startTs, TransactionService transactionService) { try { transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS); transactionOutcomeMetrics.markRollbackOtherTransaction(); return true; } catch (KeyAlreadyExistsException e) { log.debug("This isn't a bug but it should be very infrequent. Two transactions tried to roll back someone" + " else's request with start: {}", SafeArg.of("startTs", startTs), new TransactionFailedRetriableException( "Two transactions tried to roll back someone else's request with start: " + startTs, e)); return false; } }
Source:
<code>public void showError(CommandSender sender, Throwable throwable, String commandLabel) { sender.sendMessage(tl("errorWithMessage", throwable.getMessage())); if (ess.getSettings().isDebug()) { <START> ess.getLogger().log(Level.INFO, tl("errorCallingCommand", commandLabel), throwable); <END> throwable.printStackTrace(); } }</code><technical_language>Logger::info work</technical_language>

Target:
public void showError(CommandSender sender, Throwable throwable, String commandLabel) { sender.sendMessage(tl("errorWithMessage", throwable.getMessage())); if (ess.getSettings().isDebug()) { logger.log(Level.INFO, tl("errorCallingCommand", commandLabel), throwable); throwable.printStackTrace(); } }
Source:
<code>private void maybeReasignAlias(Node assign) { String alias = null; <START> for (Node child = assign.getFirstChild(); child != null; child = child.getFirstChild()) { <END> if (child.isName()) { alias = child.getString(); } } if (aliasToProvidedNamespace.containsKey(alias)) { String providedNamespace = aliasToProvidedNamespace.get(alias); String suffix = assign.getFirstChild().getQualifiedName().substring(alias.length()); Node qName = NodeUtil.newQName(compiler, providedNamespace + suffix); assign.replaceChild(assign.getFirstChild(), qName); } }</code><technical_language>case this cover covered previously</technical_language>

Target:
private void maybeReasignAlias(Node assign) { String alias = null; for (Node child = assign.getFirstChild(); child != null; child = child.getFirstChild()) { if (child.isName()) { alias = child.getQualifiedName(); } } if (aliasToProvidedNamespace.containsKey(alias)) { String providedNamespace = aliasToProvidedNamespace.get(alias); String suffix = assign.getFirstChild().getQualifiedName().substring(alias.length()); Node qName = NodeUtil.newQName(compiler, providedNamespace + suffix); assign.replaceChild(assign.getFirstChild(), qName); } }
Source:
<code>@Override public void run() throws InterruptedException { Row row; <START> List values = new ArrayList(); <END> while ((row = source.receive()) != null) { values.add(row.getValues()); } row = Row.of(ImmutableList.copyOf(values)); sink.send(row); }</code><technical_language>List<Object> ArrayList<></technical_language>

Target:
@Override public void run() throws InterruptedException { Row row; List<Object[]> values = new ArrayList<>(); while ((row = source.receive()) != null) { values.add(row.getValues()); } row = Row.of(ImmutableList.copyOf(values)); sink.send(row); }
Source:
<code>public Map<String, Set<DocumentReference>> updateAndSaveDocFromRequest( DocumentReference docRef) { Collection<XWikiDocument> xdocs = Collections.<XWikiDocument>emptyList(); try { xdocs = getDocFormCommand().updateDocFromMap(docRef, getContext().getRequest().getParameterMap(), getContext()); <START> return saveXWikiDocCollection(xdocs); <END> } catch (XWikiException xwe) { LOGGER.error("Exception in getDocFormCommand().updateDocFromMap()", xwe); } return Collections.emptyMap(); }</code><technical_language>Add rights checks this point call saveXWikiDocCollection docFormCommand if rights given. need rights-checks is a call comming scripts. In other situation a direct call out of a java process (even a request, a value/key map) do want additionally check for access rights</technical_language>

Target:
public Map<String, Set<DocumentReference>> updateAndSaveDocFromRequest( DocumentReference docRef) { Collection<XWikiDocument> xdocs = Collections.<XWikiDocument>emptyList(); try { xdocs = getDocFormCommand().updateDocFromMap(docRef, getContext().getRequest().getParameterMap(), getContext()); return checkRightsAndSaveXWikiDocCollection(xdocs); } catch (XWikiException xwe) { LOGGER.error("Exception in getDocFormCommand().updateDocFromMap()", xwe); } return Collections.emptyMap(); }
Source:
<code>public void rvvLockedAfterKeysAreLockedAndUnlockRVVBeforeKeys() throws Exception { PutAllPRMessage message = spy(new PutAllPRMessage(bucketId, 1, false, false, false, null)); message.addEntry(entryData); doReturn(keys).when(message).getKeysToBeLocked(); when(bucketRegion.waitUntilLocked(keys)).thenReturn(true); when(bucketRegion.doLockForPrimary(false)).thenThrow(new PrimaryBucketException()); doNothing().when(bucketRegion).lockRVVForBulkOp(); doNothing().when(bucketRegion).unlockRVVForBulkOp(); InternalCache cache = mock(InternalCache.class); InternalDistributedSystem ids = mock(InternalDistributedSystem.class); when(bucketRegion.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(ids); when(ids.getOffHeapStore()).thenReturn(null); <START> try { message.doLocalPutAll(partitionedRegion, mock(InternalDistributedMember.class), 1); fail("Expect PrimaryBucketException"); } catch (Exception e) { assertThat(e instanceof PrimaryBucketException); } <END> InOrder inOrder = inOrder(bucketRegion); inOrder.verify(bucketRegion).waitUntilLocked(keys); inOrder.verify(bucketRegion).lockRVVForBulkOp(); inOrder.verify(bucketRegion).unlockRVVForBulkOp(); inOrder.verify(bucketRegion).removeAndNotifyKeys(keys); }</code><technical_language>This replaced assertThatThrownBy(() -> message.doLocalPutAll(partitionedRegion, mock(InternalDistributedMember.class), 1)).isInstanceOf(PrimaryBucketException.class); a bit neater</technical_language>

Target:
public void rvvLockedAfterKeysAreLockedAndUnlockRVVBeforeKeys() throws Exception { PutAllPRMessage message = spy(new PutAllPRMessage(bucketId, 1, false, false, false, null)); message.addEntry(entryData); doReturn(keys).when(message).getKeysToBeLocked(); when(bucketRegion.waitUntilLocked(keys)).thenReturn(true); when(bucketRegion.doLockForPrimary(false)).thenThrow(new PrimaryBucketException()); doNothing().when(bucketRegion).lockRVVForBulkOp(); doNothing().when(bucketRegion).unlockRVVForBulkOp(); InternalCache cache = mock(InternalCache.class); InternalDistributedSystem ids = mock(InternalDistributedSystem.class); when(bucketRegion.getCache()).thenReturn(cache); when(cache.getDistributedSystem()).thenReturn(ids); when(ids.getOffHeapStore()).thenReturn(null); assertThatThrownBy( () -> message.doLocalPutAll(partitionedRegion, mock(InternalDistributedMember.class), 1)) .isInstanceOf(PrimaryBucketException.class); InOrder inOrder = inOrder(bucketRegion); inOrder.verify(bucketRegion).waitUntilLocked(keys); inOrder.verify(bucketRegion).lockRVVForBulkOp(); inOrder.verify(bucketRegion).unlockRVVForBulkOp(); inOrder.verify(bucketRegion).removeAndNotifyKeys(keys); }
Source:
<code>public static ServiceRegistrar createServiceRegistrar(final Path path, final String address, final String domain) { final ServiceRegistrarFactory factory; if (path == null) { factory = createFactory(); } else { factory = createFactory(path); } if (address != null) { log.info("Creating service registrar with address: {}", address); return factory.create(address); <START> } else if (domain != null && !domain.equals("")) { <END> log.info("Creating service registrar for domain: {}", domain); return domain.equals("localhost") ? factory.create("tcp://localhost:4999") : factory.createForDomain(domain); } else { log.info("No address nor domain configured, not creating service registrar."); return new NopServiceRegistrar(); } }</code><technical_language>isNullOrEmpty</technical_language>

Target:
public static ServiceRegistrar createServiceRegistrar(final Path path, final String address, final String domain) { final ServiceRegistrarFactory factory; if (path == null) { factory = createFactory(); } else { factory = createFactory(path); } if (address != null) { log.info("Creating service registrar with address: {}", address); return factory.create(address); } else if (!Strings.isNullOrEmpty(domain)) { log.info("Creating service registrar for domain: {}", domain); return domain.equals("localhost") ? factory.create("tcp://localhost:4999") : factory.createForDomain(domain); } else { log.info("No address nor domain configured, not creating service registrar."); return new NopServiceRegistrar(); } }
Source:
<code>public void marshal(ITypeMarshalBuffer buffer) throws CoreException { short firstBytes = ITypeMarshalBuffer.ARRAY_TYPE; int flags= 0; long nval= -1; IValue val= null; if (isConst()) flags |= 0x01; if (isVolatile()) flags |= 0x02; if (isRestrict()) flags |= 0x04; if (isStatic()) flags |= 0x08; <START> if (isVariableLength()) flags |= 0x10; <END> if (flags != 0) { firstBytes |= ITypeMarshalBuffer.FLAG1; } val= getSize(); if (val != null) { firstBytes |= ITypeMarshalBuffer.FLAG2; Long num= val.numericalValue(); if (num != null) { nval= num; if (nval >= 0) { firstBytes |= ITypeMarshalBuffer.FLAG3; } } } buffer.putShort(firstBytes); if (flags != 0) { buffer.putByte((byte) flags); } if (nval >= 0) { buffer.putLong(nval); } else if (val != null) { buffer.marshalValue(val); } buffer.marshalType(getType()); }</code><technical_language>flags combined firstBytes enough room there</technical_language>

Target:
public void marshal(ITypeMarshalBuffer buffer) throws CoreException { short firstBytes = ITypeMarshalBuffer.ARRAY_TYPE; long nval= -1; IValue val= null; if (isConst()) firstBytes |= ITypeMarshalBuffer.FLAG1; if (isVolatile()) firstBytes |= ITypeMarshalBuffer.FLAG2; if (isRestrict()) firstBytes |= ITypeMarshalBuffer.FLAG3; if (isStatic()) firstBytes |= ITypeMarshalBuffer.FLAG4; if (isVariableLength()) firstBytes |= ITypeMarshalBuffer.FLAG5; val= getSize(); if (val != null) { firstBytes |= ITypeMarshalBuffer.FLAG6; Long num= val.numericalValue(); if (num != null) { nval= num; if (nval >= 0) { firstBytes |= ITypeMarshalBuffer.FLAG7; } } } buffer.putShort(firstBytes); if (nval >= 0) { buffer.putLong(nval); } else if (val != null) { buffer.marshalValue(val); } buffer.marshalType(getType()); }
Source:
<code>public static <T extends Cborable> Pair<FragmentedPaddedCipherText, List<FragmentWithHash>> build(SymmetricKey from, T secret, int paddingBlockSize, int maxFragmentSize, Hasher hasher) { if (paddingBlockSize < 1) throw new IllegalStateException("Invalid padding block size: " + paddingBlockSize); byte[] nonce = from.createNonce(); byte[] cipherText = from.encrypt(pad(secret.serialize(), paddingBlockSize), nonce); if (cipherText.length <= 4096 + TweetNaCl.SECRETBOX_OVERHEAD_BYTES) { FragmentWithHash frag = new FragmentWithHash(new Fragment(cipherText), hasher.identityHash(cipherText, true)); return new Pair<>(new FragmentedPaddedCipherText(nonce, Collections.singletonList(frag.hash)), Collections.singletonList(frag)); } byte[][] split = split(cipherText, maxFragmentSize); <START> List<FragmentWithHash> frags = Arrays.asList(split).stream() <END> .map(d -> new FragmentWithHash(new Fragment(d), hasher.hash(d, true))) .collect(Collectors.toList()); List<Multihash> hashes = frags.stream() .map(f -> f.hash) .collect(Collectors.toList()); return new Pair<>(new FragmentedPaddedCipherText(nonce, hashes), frags); }</code><technical_language>nit: Stream.of(spilt)</technical_language>

Target:
public static <T extends Cborable> Pair<FragmentedPaddedCipherText, List<FragmentWithHash>> build(SymmetricKey from, T secret, int paddingBlockSize, int maxFragmentSize, Hasher hasher) { if (paddingBlockSize < 1) throw new IllegalStateException("Invalid padding block size: " + paddingBlockSize); byte[] nonce = from.createNonce(); byte[] cipherText = from.encrypt(pad(secret.serialize(), paddingBlockSize), nonce); if (cipherText.length <= 4096 + TweetNaCl.SECRETBOX_OVERHEAD_BYTES) { FragmentWithHash frag = new FragmentWithHash(new Fragment(cipherText), hasher.identityHash(cipherText, true)); return new Pair<>(new FragmentedPaddedCipherText(nonce, Collections.singletonList(frag.hash)), Collections.singletonList(frag)); } byte[][] split = split(cipherText, maxFragmentSize); List<FragmentWithHash> frags = Arrays.stream(split) .map(d -> new FragmentWithHash(new Fragment(d), hasher.hash(d, true))) .collect(Collectors.toList()); List<Multihash> hashes = frags.stream() .map(f -> f.hash) .collect(Collectors.toList()); return new Pair<>(new FragmentedPaddedCipherText(nonce, hashes), frags); }
Source:
<code>public void handle(ExecutionContext context) { <START> NotFound reportMessage = new NotFound(System.currentTimeMillis()); <END> reportMessage.setRequestId(context.request().id()); reportMessage.setClientRequest(new io.gravitee.reporter.api.common.Request()); reportMessage.getClientRequest().setMethod(context.request().method()); reportMessage.getClientRequest().setUri(context.request().uri()); reportMessage.getClientRequest().setHeaders(new HttpHeaders(context.request().headers())); reporterService.report(reportMessage); next.handle(context); }</code><technical_language>I understand purpose of this. need create a dedicated Reportable for unmapped request ? I prefer of Metrics object for setting a dummy api-id (as for unknown application (id = 1)). WDYT</technical_language>

Target:
public void handle(ExecutionContext context) { Metrics metrics = context.request().metrics(); metrics.setApi(UNKNOWN_SERVICE); metrics.setApplication(UNKNOWN_SERVICE); if (logEnabled) { Buffer payload = Buffer.buffer(); context.request().bodyHandler(payload::appendBuffer).endHandler(aVoid -> { Log log = new Log(System.currentTimeMillis()); log.setRequestId(context.request().id()); log.setClientRequest(new io.gravitee.reporter.api.common.Request()); log.getClientRequest().setMethod(context.request().method()); log.getClientRequest().setUri(context.request().uri()); log.getClientRequest().setHeaders(new HttpHeaders(context.request().headers())); log.getClientRequest().setBody(payload.toString()); metrics.setLog(log); reporterService.report(metrics); next.handle(context); }); } else { reporterService.report(metrics); next.handle(context); } }
Source:
<code><START> public void testOnSwitch() throws Exception { <END> final Diagram diagram = mock(Diagram.class); final String defSetId = "defSetId"; final String shapeDefId = "shapeDefId"; tested.onSwitch(diagram, defSetId, shapeDefId); verify(view, times(1)).showLoading(); verify(view, times(1)).hideBusyIndicator(); verify(sessionEditorPresenter, times(1)).destroy(); verify(sessionEditorPresenter, times(1)).open(any(ProjectDiagram.class), any(SessionPresenter.SessionPresenterCallback.class)); }</code><technical_language>Exception is thrown</technical_language>

Target:
public void testOnSwitch() { final Diagram diagram = mock(Diagram.class); final String defSetId = "defSetId"; final String shapeDefId = "shapeDefId"; tested.onSwitch(diagram, defSetId, shapeDefId); verify(view, times(1)).showLoading(); verify(view, times(1)).hideBusyIndicator(); verify(sessionEditorPresenter, times(1)).destroy(); verify(sessionEditorPresenter, times(1)).open(any(ProjectDiagram.class), any(SessionPresenter.SessionPresenterCallback.class)); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ArcGISScene scene = new ArcGISScene(); scene.setBasemap(Basemap.createNationalGeographic()); mSceneView = findViewById(R.id.sceneView); mSceneView.setScene(scene); final Surface surface = new Surface(); ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource( getString(R.string.elevation_image_service)); surface.getElevationSources().add(elevationSource); scene.setBaseSurface(surface); Point initialLocation = new Point(-119.94891542688772, 46.75792111605992, 3183, mSceneView.getSpatialReference()); Camera camera = new Camera(initialLocation, 0, 7, 70, 0); mSceneView.setViewpointCamera(camera); mExaggerationValueText = findViewById(R.id.exaggerationSeekBarValueText); final SeekBar mExaggerationSeekBar = findViewById(R.id.exaggerationSeekBar); mExaggerationSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { <START> mExaggerationValueText.setText(String.valueOf((float) progress)); <END> surface.setElevationExaggeration((float) progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }</code><technical_language>need cast a float</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSceneView = findViewById(R.id.sceneView); ArcGISScene scene = new ArcGISScene(Basemap.Type.NATIONAL_GEOGRAPHIC); mSceneView.setScene(scene); final Surface surface = new Surface(); ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource(getString(R.string.elevation_image_service_url)); surface.getElevationSources().add(elevationSource); scene.setBaseSurface(surface); Point initialLocation = new Point(-119.94891542688772, 46.75792111605992, 3183, mSceneView.getSpatialReference()); Camera camera = new Camera(initialLocation, 0, 7, 70, 0); mSceneView.setViewpointCamera(camera); final TextView exaggerationTextView = findViewById(R.id.exaggerationValueTextView); final SeekBar exaggerationSeekBar = findViewById(R.id.exaggerationSeekBar); exaggerationSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { exaggerationTextView.setText(String.valueOf(progress)); surface.setElevationExaggeration(progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); }
Source:
<code>public ITmfTrace getTraceAsStub2() { ITmfTrace trace = null; final URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(fDirectory + File.separator + fPath), null); try { File test = new File(FileLocator.toFileURL(location).toURI()); trace = new TmfTraceStub2(test.toURI().getPath(), ITmfTrace.DEFAULT_TRACE_CACHE_SIZE, false, null); TmfSignalManager.deregister(trace); } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); <START> } catch (TmfTraceException e) { <END> throw new RuntimeException(e); } return trace; }</code><technical_language>exceptions handled way, clause: } catch (URISyntaxException | IOException | TmfTraceException e) { throw new IllegalStateException(e); } (don't RuntimeException directly, IllegalStateException is basically Sonar happy ;) )</technical_language>

Target:
public ITmfTrace getTraceAsStub2() { ITmfTrace trace = null; final URL location = FileLocator.find(TmfCoreTestPlugin.getDefault().getBundle(), new Path(fDirectory + File.separator + fPath), null); try { File test = new File(FileLocator.toFileURL(location).toURI()); trace = new TmfTraceStub2(test.toURI().getPath(), ITmfTrace.DEFAULT_TRACE_CACHE_SIZE, false, null); TmfSignalManager.deregister(trace); } catch (URISyntaxException | IOException | TmfTraceException e) { throw new IllegalStateException(e); } return trace; }
Source:
<code>private Builder(MetricRegistry registry) { this.registry = registry; this.clock = Clock.defaultClock(); this.prefix = null; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; <START> this.disabledMetricTypes = Collections.emptySet(); <END> }</code><technical_language>If disabledMetricTypes is EnumSet, EnumSet.noneOf</technical_language>

Target:
private Builder(MetricRegistry registry) { this.registry = registry; this.clock = Clock.defaultClock(); this.prefix = null; this.rateUnit = TimeUnit.SECONDS; this.durationUnit = TimeUnit.MILLISECONDS; this.filter = MetricFilter.ALL; this.disabledMetricTypes = EnumSet.noneOf(MetricTypes.class); }