auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public StorageModel(StorageModelBehavior behavior) { this.behavior = behavior; this.behavior.setModel(this); Frontend.getQueryStartedEvent().addListener(this); Frontend.getQueryCompleteEvent().addListener(this); <START> Frontend.SubscribeAdditonal(new VdcQueryType[] { VdcQueryType.Search, VdcQueryType.GetConfigurationValue, <END> VdcQueryType.GetStoragePoolsByStorageDomainId, VdcQueryType.GetStorageDomainsByStoragePoolId, VdcQueryType.GetLunsByVgId, VdcQueryType.GetAllVdsByStoragePool, VdcQueryType.DiscoverSendTargets, VdcQueryType.GetDeviceList, VdcQueryType.GetExistingStorageDomainList }); setName(new EntityModel()); setDescription(new EntityModel()); setDataCenter(new ListModel()); getDataCenter().getSelectedItemChangedEvent().addListener(this); setHost(new ListModel()); getHost().getSelectedItemChangedEvent().addListener(this); setFormat(new ListModel()); setAvailableStorageItems(new ListModel()); getAvailableStorageItems().getSelectedItemChangedEvent().addListener(this); AsyncDataProvider.GetLocalFSPath(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { StorageModel storageModel = (StorageModel) target; storageModel.localFSPath = (String) returnValue; } }, getHash())); }</code><technical_language>change subscribe subscribeQueries SubscribeAdditional subscribeAdditionalQueries</technical_language>

Target:
public StorageModel(StorageModelBehavior behavior) { this.behavior = behavior; this.behavior.setModel(this); Frontend.getQueryStartedEvent().addListener(this); Frontend.getQueryCompleteEvent().addListener(this); Frontend.subscribeAdditionalQueries(new VdcQueryType[] { VdcQueryType.Search, VdcQueryType.GetConfigurationValue, VdcQueryType.GetStoragePoolsByStorageDomainId, VdcQueryType.GetStorageDomainsByStoragePoolId, VdcQueryType.GetLunsByVgId, VdcQueryType.GetAllVdsByStoragePool, VdcQueryType.DiscoverSendTargets, VdcQueryType.GetDeviceList, VdcQueryType.GetExistingStorageDomainList }); setName(new EntityModel()); setDescription(new EntityModel()); setDataCenter(new ListModel()); getDataCenter().getSelectedItemChangedEvent().addListener(this); setHost(new ListModel()); getHost().getSelectedItemChangedEvent().addListener(this); setFormat(new ListModel()); setAvailableStorageItems(new ListModel()); getAvailableStorageItems().getSelectedItemChangedEvent().addListener(this); AsyncDataProvider.GetLocalFSPath(new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { StorageModel storageModel = (StorageModel) target; storageModel.localFSPath = (String) returnValue; } }, getHash())); }
Source:
<code>public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getstatus() != VDSStatus.Down) { <START> if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) <END> || lastUpdate + (1000 * Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds)) > System.currentTimeMillis()) { boolean result = false; if (vds.getstatus() != VDSStatus.Connecting && vds.getstatus() != VDSStatus.PreparingForMaintenance && vds.getstatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getstatus() == VDSStatus.NonResponsive || vds.getstatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.errorFormat( "VDS::handleNetworkException Server failed to respond, vds_id = {0}, vds_name = {1}, error = {2}", vds.getId(), vds.getvds_name(), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); if (ResourceManager.getInstance().getEventListener() != null) { ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } } return true; }</code><technical_language>TimeUnit.MILISSECONDS...</technical_language>

Target:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getstatus() != VDSStatus.Down) { if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || lastUpdate + (TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.TimeoutToResetVdsInSeconds))) > System.currentTimeMillis()) { boolean result = false; if (vds.getstatus() != VDSStatus.Connecting && vds.getstatus() != VDSStatus.PreparingForMaintenance && vds.getstatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getstatus() == VDSStatus.NonResponsive || vds.getstatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.errorFormat( "VDS::handleNetworkException Server failed to respond, vds_id = {0}, vds_name = {1}, error = {2}", vds.getId(), vds.getvds_name(), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); if (ResourceManager.getInstance().getEventListener() != null) { ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } } return true; }
Source:
<code>public static Drawable getDrawable(Context context, String activityName) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String currentIconPack = prefs.getString("icons-pack", "default"); if (!("default".equals(currentIconPack) <START> || "squircle".equals(currentIconPack) || "square".equals(currentIconPack) || "circle".equals(currentIconPack))) { <END> return null; } PackageManager pm = context.getPackageManager(); try { ComponentName cn = new ComponentName(GOOGLE_CALENDAR, activityName); Bundle metaData = pm.getActivityInfo(cn, PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES).metaData; Resources resourcesForApplication = pm.getResourcesForApplication(GOOGLE_CALENDAR); int dayResId = getDayResId(metaData, resourcesForApplication); if (dayResId != 0) { Drawable icon = resourcesForApplication.getDrawable(dayResId); if("default".equals(currentIconPack)){ return icon; } else { return DrawableUtils.handleAdaptiveIcons(context, icon); } } } catch (PackageManager.NameNotFoundException ignored) { } return null; }</code><technical_language>a method</technical_language>

Target:
public static Drawable getDrawable(Context context, String activityName) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String currentIconPack = prefs.getString("icons-pack", "default"); if (!("default".equals(currentIconPack) || DrawableUtils.isIconsPackAdaptive(currentIconPack))) { return null; } PackageManager pm = context.getPackageManager(); try { ComponentName cn = new ComponentName(GOOGLE_CALENDAR, activityName); Bundle metaData = pm.getActivityInfo(cn, PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES).metaData; Resources resourcesForApplication = pm.getResourcesForApplication(GOOGLE_CALENDAR); int dayResId = getDayResId(metaData, resourcesForApplication); if (dayResId != 0) { Drawable icon = resourcesForApplication.getDrawable(dayResId); if("default".equals(currentIconPack)){ return icon; } else { return DrawableUtils.handleAdaptiveIcons(context, icon); } } } catch (PackageManager.NameNotFoundException ignored) { } return null; }
Source:
<code>private OsiamConnector(Builder builder) { String clientId = builder.clientId; String clientSecret = builder.clientSecret; <START> String clientRedirectUri = builder.clientRedirectUri; <END> String authServiceEndpoint = authServiceEndpoint(builder.authServiceEndpoint, builder.combinedEndpoint); if (!Strings.isNullOrEmpty(authServiceEndpoint)) { AuthService.Builder authServiceBuilder = new AuthService.Builder(authServiceEndpoint); if (clientId != null) { authServiceBuilder = authServiceBuilder.setClientId(clientId); } if (clientSecret != null) { authServiceBuilder = authServiceBuilder.setClientSecret(clientSecret); } if (clientRedirectUri != null) { authServiceBuilder = authServiceBuilder.setClientRedirectUri(clientRedirectUri); } authService = authServiceBuilder.build(); } String resourceServiceEndpoint = resourceServiceEndpoint(builder.resourceServiceEndpoint, builder.combinedEndpoint); if (!Strings.isNullOrEmpty(resourceServiceEndpoint)) { userService = new OsiamUserService.Builder(resourceServiceEndpoint).build(); groupService = new OsiamGroupService.Builder(resourceServiceEndpoint).build(); } }</code><technical_language>I need local variables anymore</technical_language>

Target:
private OsiamConnector(Builder builder) { String authServiceEndpoint = authServiceEndpoint(builder.authServiceEndpoint, builder.combinedEndpoint); if (!Strings.isNullOrEmpty(authServiceEndpoint)) { AuthService.Builder authServiceBuilder = new AuthService.Builder(authServiceEndpoint); if (builder.clientId != null) { authServiceBuilder = authServiceBuilder.setClientId(builder.clientId); } if (builder.clientSecret != null) { authServiceBuilder = authServiceBuilder.setClientSecret(builder.clientSecret); } if (builder.clientRedirectUri != null) { authServiceBuilder = authServiceBuilder.setClientRedirectUri(builder.clientRedirectUri); } authService = authServiceBuilder.build(); } String resourceServiceEndpoint = resourceServiceEndpoint(builder.resourceServiceEndpoint, builder.combinedEndpoint); if (!Strings.isNullOrEmpty(resourceServiceEndpoint)) { userService = new OsiamUserService.Builder(resourceServiceEndpoint).build(); groupService = new OsiamGroupService.Builder(resourceServiceEndpoint).build(); } }
Source:
<code>public int run(String[] arg0) throws Exception { final int port = getConf().getInt(TRACE_SERVER_HTTP_PORT_KEY, DEFAULT_HTTP_PORT); BasicConfigurator.configure(); final String home = getConf().get(TRACE_SERVER_HTTP_JETTY_HOME_KEY, DEFAULT_HTTP_HOME); <START> String webappDirLocation = DEFAULT_WEBAPP_DIR_LOCATION; <END> Server server = new Server(port); WebAppContext root = new WebAppContext(); URL webAppDir = Thread.currentThread().getContextClassLoader().getResource(webappDirLocation); if (webAppDir == null) { throw new RuntimeException(String.format("No %s directory was found into the JAR file", webappDirLocation)); } root.setContextPath(home); root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml"); root.setResourceBase(webAppDir.toURI().toString()); root.setParentLoaderPriority(true); server.setHandler(root); server.start(); server.join(); return 0; }</code><technical_language>Suggest dropping webappDirLocation DEFAULT_WEBAPP_DIR_LOCATION this is configurable anyways</technical_language>

Target:
public int run(String[] arg0) throws Exception { final int port = getConf().getInt(TRACE_SERVER_HTTP_PORT_KEY, DEFAULT_HTTP_PORT); BasicConfigurator.configure(); final String home = getConf().get(TRACE_SERVER_HTTP_JETTY_HOME_KEY, DEFAULT_HTTP_HOME); Server server = new Server(port); WebAppContext root = new WebAppContext(); URL webAppDir = Thread.currentThread().getContextClassLoader().getResource(DEFAULT_WEBAPP_DIR_LOCATION); if (webAppDir == null) { throw new RuntimeException(String.format("No %s directory was found into the JAR file", DEFAULT_WEBAPP_DIR_LOCATION)); } root.setContextPath(home); root.setDescriptor(DEFAULT_WEBAPP_DIR_LOCATION + "/WEB-INF/web.xml"); root.setResourceBase(webAppDir.toURI().toString()); root.setParentLoaderPriority(true); server.setHandler(root); server.start(); server.join(); return 0; }
Source:
<code>public boolean isValid(List<VdsNetworkInterface> value, ConstraintValidatorContext context) { Collection<String> staticIps = new HashSet<String>(); for (VdsNetworkInterface networkInterface : value) { String address = networkInterface.getAddress(); if (networkInterface.getBootProtocol() == NetworkBootProtocol.StaticIp <START> && address != null && !"".equals(address)) { <END> if (staticIps.contains(networkInterface.getAddress())) { return false; } else { staticIps.add(networkInterface.getAddress()); } } } return true; }</code><technical_language>change address.isEmpty();</technical_language>

Target:
public boolean isValid(List<VdsNetworkInterface> value, ConstraintValidatorContext context) { Collection<String> staticIps = new HashSet<String>(); for (VdsNetworkInterface networkInterface : value) { String address = networkInterface.getAddress(); if (networkInterface.getBootProtocol() == NetworkBootProtocol.StaticIp && address != null && !address.isEmpty()) { if (staticIps.contains(networkInterface.getAddress())) { return false; } else { staticIps.add(networkInterface.getAddress()); } } } return true; }
Source:
<code>static File gunzip(File zipFile) throws Exception { File outputFile = new File(stripGzSuffix(zipFile.getAbsolutePath())); byte[] buffer = new byte[1024]; try { GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(zipFile)); FileOutputStream out = new FileOutputStream(outputFile); int len; while ((len = gzis.read(buffer)) > 0) { out.write(buffer, 0, len); } gzis.close(); out.close(); return outputFile; } catch (IOException e) { LOG.error("fail to gunzip file: " + zipFile, e); <START> throw new Exception("fail to gunzip file" + zipFile); <END> } }</code><technical_language>Exception message contains original IOException</technical_language>

Target:
static File gunzip(File zipFile) { File outputFile = new File(stripGzSuffix(zipFile.getAbsolutePath())); byte[] buffer = new byte[1024]; try { GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(zipFile)); FileOutputStream out = new FileOutputStream(outputFile); int len; while ((len = gzis.read(buffer)) > 0) { out.write(buffer, 0, len); } gzis.close(); out.close(); return outputFile; } catch (IOException e) { LOG.error("fail to gunzip file: " + zipFile, e); } return null; }
Source:
<code><START> public static void createGlobalInstance(Context c) { <END> if (sInstance != null) { return; } sInstance = new ClientPrefs(c); }</code><technical_language>I generally singletons synchronized. ClientPrefs is instantiated in place anyway, single threaded, this is more of a nit</technical_language>

Target:
public static synchronized void createGlobalInstance(Context c) { if (sInstance != null) { return; } sInstance = new ClientPrefs(c); }
Source:
<code>public void persists_new_components_as_private_if_root_does_not_exist_yet_out_of_functional_transaction() { treeRootHolder.setRoot( builder(PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY) .setName("Project") .addChildren( builder(Component.Type.MODULE, 2).setUuid("BCDE").setKey("MODULE") .setName("Module") .addChildren( builder(Component.Type.DIRECTORY, 3).setUuid("DEFG").setKey("DIR") .setPath("Directory") .addChildren( builder(FILE, 4).setUuid("CDEF").setKey("FILE") .setPath("file") .build()) .build()) .build()) .build()); underTest.execute(); <START> Stream.of("ABCD", "BCDE", "BCDE", "BCDE") <END> .forEach(uuid -> assertThat(dbClient.componentDao().selectByUuid(dbTester.getSession(), uuid).get().isPrivate()).isFalse()); }</code><technical_language>Stream.of("ABCD", "BCDE", "DEFG", "CDEF")</technical_language>

Target:
public void persists_new_components_as_private_if_root_does_not_exist_yet_out_of_functional_transaction() { treeRootHolder.setRoot(createSampleProjectComponentTree("ABCD", PROJECT_KEY)); underTest.execute(); Stream.of("ABCD", "BCDE", "DEFG", "CDEF") .forEach(uuid -> assertThat(dbClient.componentDao().selectByUuid(dbTester.getSession(), uuid).get().isPrivate()).isFalse()); }
Source:
<code>protected void <START> eventHandle(@NonNull <END> ITmfEvent event) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); if(ss == null) { return; } String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); long t = event.getTimestamp().toNanos(); if(Objects.equals(phase, "N")) { int quark = ss.getQuarkAbsoluteAndAdd(event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME), event.getContent().getFieldValue(String.class, ITraceEventConstants.ID) ); ss.modifyAttribute(t, "", quark); } if(Objects.equals(phase, "D")) { int quark = ss.getQuarkAbsoluteAndAdd(event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME), event.getContent().getFieldValue(String.class, ITraceEventConstants.ID) ); ss.modifyAttribute(t, TmfStateValue.nullValue(), quark); } if(Objects.equals(phase, "O")) { int quark = ss.getQuarkAbsoluteAndAdd(event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME), event.getContent().getFieldValue(String.class, ITraceEventConstants.ID) ); ss.modifyAttribute(t, String.valueOf(TraceEventAspects.ARGS_ASPECT.resolve(event)), quark); } }</code><technical_language>formatting</technical_language>

Target:
protected void eventHandle(@NonNull ITmfEvent event) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); if (ss == null) { return; } String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); long t = event.getTimestamp().toNanos(); if (Objects.equals(phase, TraceEventPhases.objectCreated())) { int quark = ss.getQuarkAbsoluteAndAdd(event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME), event.getContent().getFieldValue(String.class, ITraceEventConstants.ID)); ss.modifyAttribute(t, "", quark); } if (Objects.equals(phase, TraceEventPhases.objectSnapshot())) { int quark = ss.getQuarkAbsoluteAndAdd(event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME), event.getContent().getFieldValue(String.class, ITraceEventConstants.ID)); ss.modifyAttribute(t, TmfStateValue.nullValue(), quark); } if (Objects.equals(phase, TraceEventPhases.objectDestroyed())) { int quark = ss.getQuarkAbsoluteAndAdd(event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME), event.getContent().getFieldValue(String.class, ITraceEventConstants.ID)); ss.modifyAttribute(t, String.valueOf(TraceEventAspects.ARGS_ASPECT.resolve(event)), quark); } }
Source:
<code>public void accept(Event<UpscaleClusterRequest> event) { LOGGER.debug("UpscaleClusterHandler for {}", event.getData().getResourceId()); Instant start = Instant.now(); UpscaleClusterRequest request = event.getData(); UpscaleClusterResult result; try { clusterUpscaleService.installServicesOnNewHosts(request.getResourceId(), request.getHostGroupName()); result = new UpscaleClusterResult(request); } catch (Exception e) { result = new UpscaleClusterResult(e.getMessage(), e, request); } finally { <START> LOGGER.debug("UpscaleClusterHandler for finished in {}ms", event.getData().getResourceId(), Duration.between(start, Instant.now()).toMillis()); <END> } eventBus.notify(result.selector(), new Event<>(event.getHeaders(), result)); }</code><technical_language>finally omitted</technical_language>

Target:
public void accept(Event<UpscaleClusterRequest> event) { LOGGER.debug("UpscaleClusterHandler for {}", event.getData().getResourceId()); Instant start = Instant.now(); UpscaleClusterRequest request = event.getData(); UpscaleClusterResult result; try { clusterUpscaleService.installServicesOnNewHosts(request.getResourceId(), request.getHostGroupName(), request.isRepair(), request.isRestartServices()); result = new UpscaleClusterResult(request); } catch (Exception e) { result = new UpscaleClusterResult(e.getMessage(), e, request); } finally { LOGGER.debug("UpscaleClusterHandler for finished in {}ms", event.getData().getResourceId(), Duration.between(start, Instant.now()).toMillis()); } eventBus.notify(result.selector(), new Event<>(event.getHeaders(), result)); }
Source:
<code>private void loadFrontendFilesIntoCore() { Path moduleFolder = FileSystems.getDefault().getPath(modulePath); try { <START> DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, "*.jar"); <END> for (Path f : stream) { File loc = new File(f.toString()); JarFile jarFile = new JarFile(loc); if (hasFrontendFiles(jarFile)) { Path systemTempFolder = FileSystems.getDefault().getPath(System.getProperty("java.io.tmpdir")); Path temporaryFolder = Files.createTempDirectory(systemTempFolder, TEMP_DIR_PREFIX); String temporaryFolderName = Paths.get(temporaryFolder.toUri()).toAbsolutePath().toString(); File tempFolderFile = new File(temporaryFolderName); tempFolderFile.deleteOnExit(); extractFrontEndFiles(loc.getAbsolutePath(), temporaryFolderName); String moduleName = extractModuleName(temporaryFolderName); if (!moduleName.isEmpty()) { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); String filePath = session.getServletContext().getRealPath(File.separator + PAGES_FOLDER) + File.separator + moduleName; FileUtils.deleteDirectory(new File(filePath)); String resourceFolder = String.join(File.separator, Arrays.asList(temporaryFolderName, META_INF_FOLDER, RESOURCES_FOLDER)); copyFrontEndFiles(resourceFolder, filePath); FileUtils.deleteDirectory(tempFolderFile); } else { logger.info("No module found in JarFile '" + jarFile.getName() + "'."); } } } } catch (Exception e) { logger.error("Classpath could not be accessed", e.getMessage()); } }</code><technical_language>Class DirectoryStream implements Closeable / Autocloseable interface means try-with-resources-statement here. This stream object is closed in current implementation is other good reason change it</technical_language>

Target:
private void loadFrontendFilesIntoCore() { Path moduleFolder = FileSystems.getDefault().getPath(modulePath); try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, "*.jar")) { for (Path f : stream) { File loc = new File(f.toString()); try (JarFile jarFile = new JarFile(loc)) { if (hasFrontendFiles(jarFile)) { Path temporaryFolder = Files.createTempDirectory(SYSTEM_TEMP_FOLDER, TEMP_DIR_PREFIX); File tempDir = new File(Paths.get(temporaryFolder.toUri()).toAbsolutePath().toString()); extractFrontEndFiles(loc.getAbsolutePath(), tempDir); String moduleName = extractModuleName(tempDir); if (!moduleName.isEmpty()) { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); String filePath = session.getServletContext().getRealPath(File.separator + PAGES_FOLDER) + File.separator + moduleName; FileUtils.deleteDirectory(new File(filePath)); String resourceFolder = String.join(File.separator, Arrays.asList(tempDir.getAbsolutePath(), META_INF_FOLDER, RESOURCES_FOLDER)); copyFrontEndFiles(resourceFolder, filePath); } else { logger.info("No module found in JarFile '" + jarFile.getName() + "'."); } FileUtils.deleteDirectory(tempDir); } } } } catch (Exception e) { logger.error("Classpath could not be accessed", e.getMessage()); } }
Source:
<code>public List<String> getClasses() { makeFilter(); <START> String testClassDirectoryPath = StringUtils.join(new String[] {targetDir, "target", "test-classes"}, File.separator); <END> scanner.setBasedir(testClassDirectoryPath); scanner.setCaseSensitive(true); scanner.scan(); List<String> ret = new ArrayList<>(); for(String s: scanner.getIncludedFiles()){ ret.add(s.replaceAll("/", ".").replaceAll("\\.class","")); } return ret; }</code><technical_language>a StringBuffer, Guava write a custom utility method String Join</technical_language>

Target:
public List<String> getClasses() { makeFilter(); final String testClassPath = new PathBuilder().path(targetDir).path("target").path("test-classes").buildFilePath(); scanner.setBasedir(testClassPath); scanner.setCaseSensitive(true); scanner.scan(); List<String> ret = new ArrayList<>(); for(String s: scanner.getIncludedFiles()){ ret.add(s.replaceAll("/", ".").replaceAll("\\.class","")); } return ret; }
Source:
<code>private T findUniqueResult() { <START> if (collection.size() == 1) { <END> return collection.iterator().next(); } return uniqueResult; }</code><technical_language>Ternary if</technical_language>

Target:
private T findUniqueResult() { return collection.size() == 1 ? collection.iterator().next() : null; }
Source:
<code>private QueryIterator concreteSubject(Binding binding, Node s, Node score, Node literal, StrMatch match, ExecutionContext execCxt) { if (!s.isURI()) { log.warn("Subject not a URI: " + s) ; return IterLib.noResults(execCxt) ; } String qs = match.getQueryString() ; List<TextHit> x = query(match.getProperty(), match.getQueryString(), -1, execCxt) ; if ( x == null ) return IterLib.noResults(execCxt) ; <START> List<TextHit> r = new LinkedList(); <END> for (TextHit hit : x ) { if (hit.getNode().equals(s)) { r.add(hit); } } return resultsToQueryIterator(binding, s, score, literal, r, execCxt); }</code><technical_language>this style more, do this a filter: List<TextHit> r = x.stream().filter(hit -> hit.getNode().equals(s)).collect(Collectors.toList());</technical_language>

Target:
private QueryIterator concreteSubject(Binding binding, Node s, Node score, Node literal, StrMatch match, ExecutionContext execCxt) { if (!s.isURI()) { log.warn("Subject not a URI: " + s) ; return IterLib.noResults(execCxt) ; } String qs = match.getQueryString() ; List<TextHit> x = query(match.getProperty(), match.getQueryString(), -1, execCxt) ; if ( x == null ) return IterLib.noResults(execCxt) ; List<TextHit> r = x.stream().filter(hit -> hit.getNode().equals(s)).collect(Collectors.toList()); return resultsToQueryIterator(binding, s, score, literal, r, execCxt); }
Source:
<code>public boolean isForeignKey(RelOptTable fromTable, List<Integer> fromColumns, RelOptTable toTable, List<Integer> toColumns) { final JdbcTable jdbcTable = fromTable.unwrap(JdbcTable.class); return withBuilder(jdbcTable.jdbcSchema, (cluster, relOptSchema, jdbcSchema, relBuilder) -> { final RelOptTable.ToRelContext toRelContext = ViewExpanders.simpleContext(cluster); <START> relBuilder.push(fromTable.toRel(toRelContext)) <END> .filter(fromColumns.stream() .map(column -> relBuilder.call(SqlStdOperatorTable.IS_NOT_NULL, relBuilder.field(column))) .collect(Collectors.toList())) .project(relBuilder.fields(fromColumns)) .push(toTable.toRel(toRelContext)) .project(relBuilder.fields(toColumns)) .minus(false, 2) .aggregate(relBuilder.groupKey(), relBuilder.count()); final String sql = toSql(relBuilder.build(), jdbcSchema.dialect); final DataSource dataSource = jdbcTable.jdbcSchema.getDataSource(); try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { if (!resultSet.next()) { throw new AssertionError(); } return resultSet.getInt(1) == 0; } catch (SQLException e) { throw handle(e, sql); } }); }</code><technical_language>leave some error message throwing error</technical_language>

Target:
public boolean isForeignKey(RelOptTable fromTable, List<Integer> fromColumns, RelOptTable toTable, List<Integer> toColumns) { final JdbcTable jdbcTable = fromTable.unwrap(JdbcTable.class); return withBuilder(jdbcTable.jdbcSchema, (cluster, relOptSchema, jdbcSchema, relBuilder) -> { final RelOptTable.ToRelContext toRelContext = ViewExpanders.simpleContext(cluster); relBuilder.push(fromTable.toRel(toRelContext)) .filter(fromColumns.stream() .map(column -> relBuilder.call(SqlStdOperatorTable.IS_NOT_NULL, relBuilder.field(column))) .collect(Collectors.toList())) .project(relBuilder.fields(fromColumns)) .push(toTable.toRel(toRelContext)) .project(relBuilder.fields(toColumns)) .minus(false, 2) .aggregate(relBuilder.groupKey(), relBuilder.count()); final String sql = toSql(relBuilder.build(), jdbcSchema.dialect); final DataSource dataSource = jdbcTable.jdbcSchema.getDataSource(); try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql)) { if (!resultSet.next()) { throw new AssertionError("expected exactly 1 row: " + sql); } final int count = resultSet.getInt(1); if (resultSet.next()) { throw new AssertionError("expected exactly 1 row: " + sql); } return count == 0; } catch (SQLException e) { throw handle(e, sql); } }); }
Source:
<code>public void process(final Exchange exchange) { try { final SMSMessage smsMessage = exchange.getIn().getBody(SMSMessage.class); if (smsMessage == null) { <START> throw new NullPointerException(); <END> } LOG.trace("Validating SMSMessage instance provided: {}", smsMessage.toString()); final Set<ConstraintViolation<SMSMessage>> constraintViolations = getValidator().validate(smsMessage); if (constraintViolations.size() > 0) { final StringBuffer msg = new StringBuffer(); for (final ConstraintViolation<SMSMessage> cv : constraintViolations) { msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(), cv.getMessage())); } throw new InvalidPayloadException(msg.toString()); } LOG.trace("SMSMessage instance is valid: {}", smsMessage.toString()); final CMMessage cmMessage = new CMMessage(smsMessage.getPhoneNumber(), smsMessage.getMessage()); LOG.debug("CMMessage instance build from valid SMSMessage instance"); if (smsMessage.getFrom() == null || smsMessage.getFrom().isEmpty()) { String df = getConfiguration().getDefaultFrom(); cmMessage.setSender(df); LOG.debug("Dynamic sender is set to default dynamic sender: {}", df); } cmMessage.setIdAsString(smsMessage.getId()); cmMessage.setUnicodeAndMultipart(getConfiguration().getDefaultMaxNumberOfParts()); sender.send(cmMessage); log.debug("Request accepted by CM Host: {}", cmMessage.toString()); } catch (final NullPointerException e) { final String m = "Check Message body - Has to be an SMSMessage instance"; log.error(m, e); exchange.setException(new InvalidPayloadException(m)); } catch (final RuntimeException e) { log.error("Message cannot be sent ", e); exchange.setException(e); } }</code><technical_language>do throw this exception, instead getMandatoryBody</technical_language>

Target:
public void process(final Exchange exchange) throws Exception { final SMSMessage smsMessage = exchange.getIn().getMandatoryBody(SMSMessage.class); log.trace("Validating SMSMessage instance provided: {}", smsMessage.toString()); final Set<ConstraintViolation<SMSMessage>> constraintViolations = getValidator().validate(smsMessage); if (constraintViolations.size() > 0) { final StringBuffer msg = new StringBuffer(); for (final ConstraintViolation<SMSMessage> cv : constraintViolations) { msg.append(String.format("- Invalid value for %s: %s", cv.getPropertyPath().toString(), cv.getMessage())); } log.debug(msg.toString()); throw new InvalidPayloadRuntimeException(exchange, SMSMessage.class); } log.trace("SMSMessage instance is valid: {}", smsMessage.toString()); final CMMessage cmMessage = new CMMessage(smsMessage.getPhoneNumber(), smsMessage.getMessage()); log.debug("CMMessage instance build from valid SMSMessage instance"); if (smsMessage.getFrom() == null || smsMessage.getFrom().isEmpty()) { String df = getConfiguration().getDefaultFrom(); cmMessage.setSender(df); log.debug("Dynamic sender is set to default dynamic sender: {}", df); } cmMessage.setIdAsString(smsMessage.getId()); cmMessage.setUnicodeAndMultipart(getConfiguration().getDefaultMaxNumberOfParts()); sender.send(cmMessage); log.debug("Request accepted by CM Host: {}", cmMessage.toString()); }
Source:
<code>public void init() { LOG.info("Initializing side input stores."); <START> Map<SystemStreamPartition, String> fileOffsets = getFileOffsets(); LOG.info("File offsets for the task {}: {}", taskName, fileOffsets); <END> initializeStoreDirectories(); }</code><technical_language>is this used? is for logging purposes</technical_language>

Target:
public void init() { LOG.info("Initializing side input stores."); initializeStoreDirectories(); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConsumerRateInfo that = (ConsumerRateInfo) o; <START> return Objects.equals(consumerId, that.consumerId) && <END> Objects.equals(maxRate, that.maxRate) && Objects.equals(history, that.history); }</code><technical_language>if this needs identified, i need is consumerId. changes in history create a totally object replace other in map i.e.</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConsumerRateInfo that = (ConsumerRateInfo) o; return Objects.equals(consumerId, that.consumerId); }
Source:
<code>public void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } MimePart part = new MimePart(name, body, boundary, mimeParts.isEmpty()); mimeParts.add(part); long size = part.size(); <START> if (size < 0) { <END> length = -1; } else if (length >= 0) { length += size; } }</code><technical_language>size != -1 -1 is explicit value. If passes a negative behavior is undefined (which is fine)</technical_language>

Target:
public void addPart(String name, TypedOutput body) { if (name == null) { throw new NullPointerException("Part name must not be null."); } if (body == null) { throw new NullPointerException("Part body must not be null."); } MimePart part = new MimePart(name, body, boundary, mimeParts.isEmpty()); mimeParts.add(part); long size = part.size(); if (size == -1) { length = -1; } else if (length != -1) { length += size; } }
Source:
<code>public void testOverriddenAttributesMustMatchInType() { validator.validate( new DummyEntityWithZipCode( "foobar" ) ); <START> fail( "Wrong attribute override in composite constraint. An Exception should have been thrown." ); <END> }</code><technical_language>I find fail w/o try/catch misleading. IMO is try/catch _ expectedExceptions _</technical_language>

Target:
public void testOverriddenAttributesMustMatchInType() { validator.validate( new DummyEntityWithZipCode( "foobar" ) ); }
Source:
<code>public double similarity(MatrixRow a, MatrixRow b) { int na = a.getNumCols(); int nb = b.getNumCols(); int intersect = 0; int i = 0, j = 0; <START> int ca = a.getColIndex(i); <END> int cb = b.getColIndex(j); if((i != 0 || j != 0)) { while (i < na && j < nb) { if (ca < cb) { i++; ca = a.getColIndex(i); } else if (ca > cb) { j++; cb = b.getColIndex(j); } else { i++; j++; intersect++; ca = a.getColIndex(i); cb = b.getColIndex(j); } } } return SimUtils.googleSimilarity(na, nb, intersect, numPages); }</code><technical_language>This throw out of bounds index if 0 columns. return 0 if of vectors length 0</technical_language>

Target:
public double similarity(MatrixRow a, MatrixRow b) { int na = a.getNumCols(); int nb = b.getNumCols(); int intersect = 0; int i = 0, j = 0; if((na == 0 || nb == 0)) { return 0; } int ca = a.getColIndex(i); int cb = b.getColIndex(j); while (i < na && j < nb) { if (ca < cb) { i++; ca = a.getColIndex(i); } else if (ca > cb) { j++; cb = b.getColIndex(j); } else { i++; j++; intersect++; ca = a.getColIndex(i); cb = b.getColIndex(j); } } return SimUtils.googleSimilarity(na, nb, intersect, numPages); }
Source:
<code>public void seekToUs(long positionUs) { boolean result; lastSeekPositionUs = positionUs; if (isWithinLastChunk(positionUs)) { result = sampleQueue.skipToLastKeyframe(positionUs); } else { result = sampleQueue.skipToKeyframeBefore(positionUs); } <START> boolean seekInsideBuffer = (!isPendingReset()) && (result == true); <END> if (seekInsideBuffer) { while (mediaChunks.size() > 1 && mediaChunks.get(1).getFirstSampleIndex() <= sampleQueue.getReadIndex()) { mediaChunks.removeFirst(); } } else { pendingResetPositionUs = positionUs; loadingFinished = false; mediaChunks.clear(); if (loader.isLoading()) { loader.cancelLoading(); } else { sampleQueue.reset(true); } } }</code><technical_language>I changes more complicated need be. add a boolean argument skipToKeyframeBefore determines allowed skip keyframe if position argument exceeds timestamp in queue. change need in skipToKeyframeBefore check this boolean argument part of check: if (timeUs > largestQueuedTimestampUs) { return C.POSITION_UNSET; } here, simply do: boolean seekInsideBuffer = !isPendingReset() && sampleQueue.skipToKeyframeBefore(positionUs, isWithinLastChunk(positionUs)); revert of this change, achieving optimization. preferable a single argument version of skipToKeyframeBefore calls skipToKeyframeBefore(position, false), avoid change other calling sites</technical_language>

Target:
public void seekToUs(long positionUs) { boolean result; lastSeekPositionUs = positionUs; if (isWithinLastChunk(positionUs)) { result = sampleQueue.skipToLastKeyframe(positionUs); } else { result = sampleQueue.skipToKeyframeBefore(positionUs); } boolean seekInsideBuffer = !isPendingReset() && sampleQueue.skipToKeyframeBefore(positionUs, isWithinLastChunk(positionUs)); if (seekInsideBuffer) { while (mediaChunks.size() > 1 && mediaChunks.get(1).getFirstSampleIndex() <= sampleQueue.getReadIndex()) { mediaChunks.removeFirst(); } } else { pendingResetPositionUs = positionUs; loadingFinished = false; mediaChunks.clear(); if (loader.isLoading()) { loader.cancelLoading(); } else { sampleQueue.reset(true); } } }
Source:
<code>public boolean addDependency(DynamicPomDependency dep, Path pomPath) { if (dep == null || !isGroupIDValid(dep) || !isArtifactIDValid(dep)) { return false; } <START> boolean result = false; <END> try { boolean internalArtifact = isInternalArtifact(dep); org.uberfire.java.nio.file.Path filePath = Paths.get(pomPath.toURI()); Model model = getPOMModel(filePath); List<Dependency> depsFromPom = model.getDependencies(); Map<String, String> keys = getKeysFromDependencies(depsFromPom); String keyDep = getKeyFromDynamicDependency(dep); if (!keys.containsKey(keyDep)) { Dependency pomDep = getMavenPomDep(dep, internalArtifact, getKieVersionFromPom(dep, depsFromPom)); model.getDependencies().add(pomDep); result = true; } else { for (Dependency modelDep : depsFromPom) { if (modelDep.getGroupId().equals(dep.getGroupID()) && modelDep.getArtifactId().equals(dep.getArtifactID())) { if (internalArtifact) { modelDep.setVersion(getKieVersionFromPom(dep, depsFromPom)); } else { modelDep.setVersion(keys.get(keyDep)); } } } } if (result) { writePOMModelOnFS(filePath, model); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); result = false; } return result; }</code><technical_language>I need a name for this. i.e. pomUpdated</technical_language>

Target:
public boolean addDependency(DynamicPomDependency dep, Path pomPath) { if (dep == null || !isGroupIDValid(dep) || !isArtifactIDValid(dep)) { return false; } boolean pomUpdated = false; try { boolean internalArtifact = isInternalArtifact(dep); org.uberfire.java.nio.file.Path filePath = Paths.get(pomPath.toURI()); Model model = getPOMModel(filePath); List<Dependency> depsFromPom = model.getDependencies(); Map<String, String> keys = getKeysFromDependencies(depsFromPom); String keyDep = getKeyFromDynamicDependency(dep); if (!keys.containsKey(keyDep)) { Dependency pomDep = getMavenPomDep(dep, internalArtifact, getKieVersionFromPom(dep, depsFromPom)); model.getDependencies().add(pomDep); pomUpdated = true; } if (pomUpdated) { writePOMModelOnFS(filePath, model); } } catch (Exception ex) { logger.error(ex.getMessage(), ex); pomUpdated = false; } return pomUpdated; }
Source:
<code>private void sawDelete() { if (isPartialCompaction) { switch (deleteHandlingAction) { case LOG_ERROR: try { <START> loggedMsgCache.get(this.getClass().getName(), new Callable<Long>() { <END> @Override public Long call() throws Exception { log.error("Combiner of type " + this.getClass().getSimpleName() + " saw a delete during a partial compaction. This could cause undesired results. See ACCUMULO-2232. Will not log subsequent occurences for at least 1 hour."); return 42L; } }); } catch (ExecutionException e) { throw new RuntimeException(e); } break; case THROW_EXCEPTION: throw new IllegalStateException("Saw a delete during a partial compaction. This could cause undesired results. See ACCUMULO-2232."); case IGNORE: break; case REDUCE_ON_FULL_COMPACTION_ONLY: default: throw new IllegalStateException("Unexpected case occurred in code, please file a bug " + deleteHandlingAction); } } }</code><technical_language>first, I thought Callable<Void> better, apparently CacheBuilder that, Callable<Boolean>, more readable Boolean.TRUE inserted cache denote a log message occurred. (Unless integer denote times logged suppressing repeats some threshold, 5.)</technical_language>

Target:
private void sawDelete() { if (isMajorCompaction && !reduceOnFullCompactionOnly) { try { loggedMsgCache.get(this.getClass().getName(), new Callable<Boolean>() { @Override public Boolean call() throws Exception { sawDeleteLog.error("Combiner of type " + this.getClass().getSimpleName() + " saw a delete during a partial compaction. This could cause undesired results. See ACCUMULO-2232. Will not log subsequent occurences for at least 1 hour."); return Boolean.TRUE; } }); } catch (ExecutionException e) { throw new RuntimeException(e); } } }
Source:
<code>public void process(PipelineConfig pipelineConfig) { <START> ParamResolver resolver = new ParamResolver(new ParamSubstitutionHandlerFactory(new ParamsConfig()), fieldCache); <END> resolver.resolve(pipelineConfig); }</code><technical_language>Pull this constructor</technical_language>

Target:
public void process(PipelineConfig pipelineConfig) { resolver.resolve(pipelineConfig); }
Source:
<code><START> public void actionUpdateAttributeTypes(AttributeType typeNew) { <END> String currentAttribute = attribute; if (model.getInputConfig() != null && model.getInputConfig().getInput() != null) { DataHandle handle = model.getInputConfig().getInput().getHandle(); if (handle != null) { for (int i = 0; i < handle.getNumColumns(); i++) { String attribute = handle.getAttributeName(i); AttributeType type = model.getInputDefinition().getAttributeType(attribute); if (type != typeNew) { for (int k = 0; k < COMBO1_TYPES.length; k++) { if (typeNew == COMBO1_TYPES[k]) { cmbType.select(k); this.attribute = attribute; actionAttributeTypeChanged(); } } } } } } this.attribute = currentAttribute; }</code><technical_language>Please implement this class LayoutAttributeSettings</technical_language>

Target:
public void actionUpdateAttributeTypes(AttributeType typeNew) { if (model.getInputConfig() != null && model.getInputConfig().getInput() != null) { DataHandle handle = model.getInputConfig().getInput().getHandle(); if (handle != null) { for (int i = 0; i < handle.getNumColumns(); i++) { String attribute = handle.getAttributeName(i); AttributeType type = model.getInputDefinition().getAttributeType(attribute); if (type != typeNew) { actionAttributeTypeChanged(attribute, typeNew); } } } } }
Source:
<code>void setUp() { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl(MYSQL_CONTAINER.getJdbcUrl()); dataSource.setUser(MYSQL_CONTAINER.getUsername()); dataSource.setPassword(MYSQL_CONTAINER.getPassword()); try { testSubject = createEngine(dataSource); } catch (Exception e) { <START> throw new TestAbortedException("Ignoring this test, as no valid MySQL instance is configured", e); <END> } }</code><technical_language>current approach able remove this try-catch block, right? applies for other 2 tests</technical_language>

Target:
void setUp() throws SQLException { MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl(MYSQL_CONTAINER.getJdbcUrl()); dataSource.setUser(MYSQL_CONTAINER.getUsername()); dataSource.setPassword(MYSQL_CONTAINER.getPassword()); testSubject = createEngine(dataSource); }
Source:
<code><START> public FetchCommand setCheckFetchedObjects(boolean checkFetchedObjects) { <END> this.checkFetchedObjects = checkFetchedObjects; return this; }</code><technical_language>Missing checkCallable()</technical_language>

Target:
public FetchCommand setCheckFetchedObjects(boolean checkFetchedObjects) { checkCallable(); this.checkFetchedObjects = checkFetchedObjects; return this; }
Source:
<code>public String getSource(LogEntry logentry) { <START> return logentry.getSource().getName(); <END> }</code><technical_language>change this</technical_language>

Target:
public String getSource(LogEntry logentry) { return logentry.getSource().getUuid(); }
Source:
<code>public CoupleMbusDeviceByChannelResponseDto(final ChannelElementValuesDto channelElementValues) { <START> super(); <END> this.channelElementValues = channelElementValues; }</code><technical_language>calling super() constructor here? Remove statement</technical_language>

Target:
public CoupleMbusDeviceByChannelResponseDto(final ChannelElementValuesDto channelElementValues) { this.channelElementValues = channelElementValues; }
Source:
<code>public void getCodeSystemByShortNameFromAllRepositoreis() { final CodeSystems existingCodeSystem = CodeSystemRequests.prepareSearchCodeSystemsInAllRepositories() .filterById(SNOMEDCT) .build() .execute(Services.context()); assertEquals(existingCodeSystem.getTotal(), 1); assertEquals(SNOMEDCT, Iterables.getOnlyElement(existingCodeSystem.getItems()).getShortName()); <START> final CodeSystems nonExistentCodeSystem = CodeSystemRequests.prepareSearchCodeSystemsInAllRepositories() <END> .filterById("not a valid code system short name") .build() .execute(Services.context()); assertEquals(nonExistentCodeSystem.getTotal(), 0); }</code><technical_language>This is a separate test case, please move test method</technical_language>

Target:
public void getCodeSystemByShortNameFromAllRepositoreis() { final String shortName = "ShortName"; final String oid = "Oid"; assertCodeSystemCreated(shortName, oid); final CodeSystems existingCodeSystem = CodeSystemRequests.prepareSearchAllCodeSystems() .filterById(shortName) .build() .execute(Services.context()); assertThat(existingCodeSystem.getItems()).hasSize(1); assertThat(existingCodeSystem.getItems().get(0).getShortName()).isEqualTo(shortName); }
Source:
<code>public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try { int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { <START> JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject <END> .class); String error = errorResponse.getAsJsonPrimitive ("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive ("reason").getAsString(); if (!"credentials_expired".equals(error)) { throw new HttpConnectionInterceptorException(error, reason); } } catch (JsonParseException e) { throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } case HttpURLConnection.HTTP_UNAUTHORIZED: cookie = getCookie(connection.getURL()); if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } break; default: break; } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }</code><technical_language>read stream a bufferedreader</technical_language>

Target:
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try { boolean renewCookie = false; int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject .class); String error = errorResponse.getAsJsonPrimitive ("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive ("reason").getAsString(); if (!"credentials_expired".equals(error)) { throw new HttpConnectionInterceptorException(error, reason); } else { renewCookie = true; } } catch (JsonParseException e) { throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: renewCookie = true; break; default: break; } if (renewCookie) { cookie = getCookie(connection.getURL()); if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }