auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Response toResponse(RuntimeException exception) { <START> String errorMessage = exception.getMessage(); <END> if (!isNullOrEmpty(errorMessage)) { DtoFactory dtoFactory = DtoFactory.getInstance(); ServiceError serviceError = dtoFactory.createDto(ServiceError.class).withMessage(errorMessage); return Response.serverError() .entity(dtoFactory.toJson(serviceError)) .type(MediaType.APPLICATION_JSON) .build(); } return Response.serverError().build(); }</code><technical_language>Findbug recommends usage of getlocalizedmessage instead of getMessage</technical_language>

Target:
public Response toResponse(RuntimeException exception) { final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); final String utcTime = dateFormat.format(new Date()); final String errorMessage = format("Internal Server Error occurred, error time: %s", utcTime); LOG.error(errorMessage, exception); ServiceError serviceError = DtoFactory.newDto(ServiceError.class).withMessage(errorMessage); return Response.serverError() .entity(DtoFactory.getInstance().toJson(serviceError)) .type(MediaType.APPLICATION_JSON) .build(); }
Source:
<code>public String createLogForAllAlarms() { String log = userID + "\nAdresse: " + userAddress + "\nListes des alarmes: \n"; if (alarms.isEmpty()) { <START> log += "There is no alarm for this user."; <END> } else { log += formatAlarms(); } return log; }</code><technical_language>Je pense la bonne grammaire en anglais c'est : "There alarms for this user"</technical_language>

Target:
public String createLogForAllAlarms() { String log = userID + "\nAddresse: " + userAddress + "\nAlarms' list: \n"; if (alarms.isEmpty()) { log += "There is no alarms for this user."; } else { log += formatAlarms(); } return log; }
Source:
<code>private TenancyProvider getTenancyProvider() throws DeploymentEnvironmentException { String platform = System.getenv(ENV_DEPLOYMENT_PLATFORM); if (platform == null || platform.equals("")) { throw new DeploymentEnvironmentException("Unable to identify the deployment platform"); } <START> if (platform.equalsIgnoreCase(DEPLOYMENT_KUBERNETES)) { <END> return new KubernetesTenancyProvider(); } else { throw new DeploymentEnvironmentException("Unsupported deployment platform: " + platform); } }</code><technical_language>this checked in other avoid NPEs ? consider a practice</technical_language>

Target:
private TenancyProvider getTenancyProvider() throws DeploymentEnvironmentException { String platform = System.getenv(ENV_DEPLOYMENT_PLATFORM); if (platform == null || platform.isEmpty()) { throw new DeploymentEnvironmentException("Unable to identify the deployment platform"); } if (DEPLOYMENT_KUBERNETES.equalsIgnoreCase(platform)) { return new KubernetesTenancyProvider(); } else { throw new DeploymentEnvironmentException("Unsupported deployment platform: " + platform); } }
Source:
<code>protected void endActionOnVmConfiguration() { <START> if (getVm() != null) { <END> if (getVm().getstatus() == VMStatus.ImageLocked) { VmHandler.unlockVm(getVm(), getCompensationContext()); } UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); } else { setCommandShouldBeLogged(false); log.warn("VmCommand::EndVmCommand: Vm is null - not performing EndAction on Vm"); } setSucceeded(true); }</code><technical_language>check if vm null here, verified in canDoAction executed, if VM disks VM deleted, I vm null</technical_language>

Target:
protected void endActionOnVmConfiguration() { if (getVm().getstatus() == VMStatus.ImageLocked) { VmHandler.unlockVm(getVm(), getCompensationContext()); } UpdateVmInSpm(getVm().getstorage_pool_id(), Arrays.asList(getVm())); setSucceeded(true); }
Source:
<code>public String getShortName() { <START> return "additionallinks"; <END> }</code><technical_language>"linkGroups" for consistency ext. service</technical_language>

Target:
public String getShortName() { return "linkgroups"; }
Source:
<code>LocalDate computeBestBeforeDate() { <START> if (sysConfigBL.getBooleanValue(HUAttributeConstants.SYSCONFIG_AutomaticallySetBestBeforeDate, false)) <END> { final PPOrderLineRow row = getSingleSelectedRow(); final I_PP_Order ppOrderPO = huPPOrderBL.getById(row.getOrderId()); final LocalDate datePromised = TimeUtil.asLocalDate(ppOrderPO.getDatePromised()); final ProductId productId = row.getProductId(); final int guaranteeDaysMin = productDAO.getProductGuaranteeDaysMinFallbackProductCategory(productId); if (guaranteeDaysMin <= 0) { return null; } return datePromised.plusDays(guaranteeDaysMin); } else { return null; } }</code><technical_language>IHUAttributeBL.isAuto..</technical_language>

Target:
LocalDate computeBestBeforeDate() { if (attributesBL.isAutomaticallySetBestBeforeDate()) { final PPOrderLineRow row = getSingleSelectedRow(); final int guaranteeDaysMin = productDAO.getProductGuaranteeDaysMinFallbackProductCategory(row.getProductId()); if (guaranteeDaysMin <= 0) { return null; } final I_PP_Order ppOrderPO = huPPOrderBL.getById(row.getOrderId()); final LocalDate datePromised = TimeUtil.asLocalDate(ppOrderPO.getDatePromised()); return datePromised.plusDays(guaranteeDaysMin); } else { return null; } }
Source:
<code>private boolean isNotDuplicateMessage(String message) { <START> for (String currentMessage : getMessages()) { <END> if (StringUtils.equals(currentMessage, message)) { return false; } } return true; }</code><technical_language>This function is presuming method caller is verifying "messages" is null prior called is ok for changes is happening if this private method is in this class in future pose issue</technical_language>

Target:
private boolean isNotDuplicateMessage(String message) { for (String currentMessage : getMessages()) { if (StringUtils.equalsIgnoreCase(currentMessage, message)) { return false; } } return true; }
Source:
<code>protected Stream<InputSplit<List<CloudObjectLocation>>> getPrefixesSplitStream(@Nonnull SplitHintSpec splitHintSpec) { final Iterator<List<StorageObject>> splitIterator = splitHintSpec.split( storageObjectIterable().iterator(), storageObject -> { final BigInteger sizeInBigInteger = storageObject.getSize(); long sizeInLong; if (sizeInBigInteger == null) { sizeInLong = Long.MAX_VALUE; } else { try { sizeInLong = sizeInBigInteger.longValueExact(); } catch (ArithmeticException e) { <START> sizeInLong = Long.MAX_VALUE; <END> } } return new InputFileAttribute(sizeInLong); } ); return Streams.sequentialStreamFrom(splitIterator) .map(objects -> objects.stream().map(this::byteSourceFromStorageObject).collect(Collectors.toList())) .map(InputSplit::new); }</code><technical_language>this propagate exception instead? If get object a byte size stored in a long, wrong</technical_language>

Target:
protected Stream<InputSplit<List<CloudObjectLocation>>> getPrefixesSplitStream(@Nonnull SplitHintSpec splitHintSpec) { final Iterator<List<StorageObject>> splitIterator = splitHintSpec.split( storageObjectIterable().iterator(), storageObject -> { final BigInteger sizeInBigInteger = storageObject.getSize(); long sizeInLong; if (sizeInBigInteger == null) { sizeInLong = Long.MAX_VALUE; } else { try { sizeInLong = sizeInBigInteger.longValueExact(); } catch (ArithmeticException e) { LOG.warn( e, "The object [%s, %s] has a size [%s] out of the range of the long type. " + "The max long value will be used for its size instead.", storageObject.getBucket(), storageObject.getName(), sizeInBigInteger ); sizeInLong = Long.MAX_VALUE; } } return new InputFileAttribute(sizeInLong); } ); return Streams.sequentialStreamFrom(splitIterator) .map(objects -> objects.stream().map(this::byteSourceFromStorageObject).collect(Collectors.toList())) .map(InputSplit::new); }
Source:
<code>protected void onStart() { super.onStart(); user = SyncUser.currentUser(); <START> if (user == null) { return; } <END> SyncConfiguration config = new SyncConfiguration.Builder(user, REALM_URL) .initialData(new Realm.Transaction() { @Override public void execute(@Nonnull Realm realm) { realm.createObject(CRDTCounter.class, user.getIdentity()); } }) .build(); realm = Realm.getInstance(config); counterView.setText("-"); CRDTCounter counter = realm.where(CRDTCounter.class).equalTo("name", user.getIdentity()).findFirstAsync(); counter.addChangeListener(new RealmChangeListener<CRDTCounter>() { @Override public void onChange(@Nonnull CRDTCounter counter) { counterView.setText((!counter.isValid()) ? "-" : String.format(Locale.US, "%d", counter.getCount())); } }); session = SyncManager.getSession(config); session.addDownloadProgressListener(ProgressMode.INDEFINITELY, downloadListener); session.addUploadProgressListener(ProgressMode.INDEFINITELY, uploadListener); }</code><technical_language>I realise this is behaviour in a way, if this happened users stare a blank screen. In a real app throw a login screen log error fix it, in this example sense throw IllegalState here? In case, is a minor point</technical_language>

Target:
protected void onStart() { super.onStart(); user = getLoggedInUser(); if (user == null) { return; } SyncConfiguration config = new SyncConfiguration.Builder(user, REALM_URL) .initialData(new Realm.Transaction() { @Override public void execute(@Nonnull Realm realm) { realm.createObject(CRDTCounter.class, user.getIdentity()); } }) .build(); realm = Realm.getInstance(config); counterView.setText("-"); CRDTCounter counter = realm.where(CRDTCounter.class).equalTo("name", user.getIdentity()).findFirstAsync(); counter.addChangeListener(new RealmChangeListener<CRDTCounter>() { @Override public void onChange(@Nonnull CRDTCounter counter) { counterView.setText((!counter.isValid()) ? "-" : String.format(Locale.US, "%d", counter.getCount())); } }); session = SyncManager.getSession(config); session.addDownloadProgressListener(ProgressMode.INDEFINITELY, downloadListener); session.addUploadProgressListener(ProgressMode.INDEFINITELY, uploadListener); }
Source:
<code>private static String getActionSetId(AlgorithmName algorithmName, Configuration cfg) throws MappingNotDefinedException { String propertyValue = cfg.get(EXPORT_ACTION_SETID + EXPORT_ALGORITHM_PROPERTY_SEPARATOR + algorithmName.name()); if (StringUtils.isNotBlank(propertyValue) && !WorkflowRuntimeParameters.UNDEFINED_NONEMPTY_VALUE.equals(propertyValue)) { return propertyValue; } else { propertyValue = cfg.get(EXPORT_ACTION_SETID); if (StringUtils.isNotBlank(propertyValue) && !WorkflowRuntimeParameters.UNDEFINED_NONEMPTY_VALUE.equals(propertyValue)) { return propertyValue; } else { throw new MappingNotDefinedException( "no action set identifier defined " + "for algorithm: " + algorithmName.name()); <START> } <END> } }</code><technical_language>WorkflowRuntimeParameters.getParamValue</technical_language>

Target:
private static String getActionSetId(AlgorithmName algorithmName, Configuration cfg) throws MappingNotDefinedException { String actionSetId = WorkflowRuntimeParameters.getParamValue( EXPORT_ACTION_SETID + EXPORT_ALGORITHM_PROPERTY_SEPARATOR + algorithmName.name(), EXPORT_ACTION_SETID, cfg); if (actionSetId!=null) { return actionSetId; } else { throw new MappingNotDefinedException( "no action set identifier defined " + "for algorithm: " + algorithmName.name()); } }
Source:
<code>private <T> Query<T> prioritizeAndLaneQuery(Query<T> query, Iterable<Segment> segments) { Set<SegmentServerSelector> segmentServerSelectors = new HashSet<>(); for (Segment s : segments) { <START> segmentServerSelectors.add(new SegmentServerSelector(null, s.getId().toDescriptor())); <END> } return scheduler.prioritizeAndLaneQuery(QueryPlus.wrap(query), segmentServerSelectors); }</code><technical_language>add @Nullable constructor parameter of SegmentServerSelector getServer()</technical_language>

Target:
private <T> Query<T> prioritizeAndLaneQuery(Query<T> query, Iterable<Segment> segments) { Set<SegmentServerSelector> segmentServerSelectors = new HashSet<>(); for (Segment s : segments) { segmentServerSelectors.add(new SegmentServerSelector(s.getId().toDescriptor())); } return scheduler.prioritizeAndLaneQuery(QueryPlus.wrap(query), segmentServerSelectors); }
Source:
<code>public synchronized void aggregate() { final IndexedInts keys = keySelector.getRow(); <START> if (keys == null) { <END> return; } final double[] values = new double[valueSelectors.size()]; int valueIndex = 0; for (final BaseDoubleColumnValueSelector valueSelector : valueSelectors) { values[valueIndex++] = valueSelector.getDouble(); } for (int i = 0; i < keys.size(); i++) { final String key = keySelector.lookupName(keys.get(i)); sketch.update(key, values); } }</code><technical_language>happen, this block removed</technical_language>

Target:
public void aggregate() { final IndexedInts keys = keySelector.getRow(); for (int i = 0; i < valueSelectors.length; i++) { values[i] = valueSelectors[i].getDouble(); } synchronized (this) { for (int i = 0, keysSize = keys.size(); i < keysSize; i++) { final String key = keySelector.lookupName(keys.get(i)); sketch.update(key, values); } } }
Source:
<code>B3Propagation(KeyFactory<K> keyFactory, Factory factory) { this.b3Key = keyFactory.create("b3"); this.traceIdKey = keyFactory.create(TRACE_ID_NAME); this.spanIdKey = keyFactory.create(SPAN_ID_NAME); this.parentSpanIdKey = keyFactory.create(PARENT_SPAN_ID_NAME); this.sampledKey = keyFactory.create(SAMPLED_NAME); this.debugKey = keyFactory.create(FLAGS_NAME); <START> this.fields = Collections.unmodifiableList( <END> asList(b3Key, traceIdKey, spanIdKey, parentSpanIdKey, sampledKey, debugKey) ); this.injectFormats = new Format[] {factory.injectFormat}; this.kindToInjectFormats = factory.kindToInjectFormats; }</code><technical_language>this need updated</technical_language>

Target:
B3Propagation(KeyFactory<K> keyFactory, Factory factory) { this.b3Key = keyFactory.create("b3"); this.traceIdKey = keyFactory.create(TRACE_ID_NAME); this.spanIdKey = keyFactory.create(SPAN_ID_NAME); this.parentSpanIdKey = keyFactory.create(PARENT_SPAN_ID_NAME); this.sampledKey = keyFactory.create(SAMPLED_NAME); this.debugKey = keyFactory.create(FLAGS_NAME); this.injectFormats = new Format[] {factory.injectFormat}; this.kindToInjectFormats = factory.kindToInjectFormats; boolean injectsMulti = factory.injectFormat.equals(Format.MULTI); boolean injectsSingle = !injectsMulti; for (Format[] formats : kindToInjectFormats.values()) { for (Format format : formats) { if (format.equals(Format.MULTI)) injectsMulti = true; if (!format.equals(Format.MULTI)) injectsSingle = true; } } if (injectsMulti && injectsSingle) { this.fields = Collections.unmodifiableList( asList(b3Key, traceIdKey, spanIdKey, parentSpanIdKey, sampledKey, debugKey) ); } else if (injectsMulti) { this.fields = Collections.unmodifiableList( asList(traceIdKey, spanIdKey, parentSpanIdKey, sampledKey, debugKey) ); } else { this.fields = Collections.singletonList(b3Key); } }
Source:
<code>public int close() { addBitsFast(1, 1); flush(); if (currentAddress >= outputLimit) { <START> return 0; END> } return (int) ((currentAddress - outputAddress) + (bitCount > 0 ? 1 : 0)); }</code><technical_language>this happen is error? throw exception</technical_language>

Target:
public int close() { addBitsFast(1, 1); flush(); checkState(currentAddress < outputLimit, "Overflow detected"); return (int) ((currentAddress - outputAddress) + (bitCount > 0 ? 1 : 0)); }
Source:
<code>public String toString() { return "DimensionExpression{" + "virtualColumn='" + virtualColumn + '\'' + <START> "outputName='" + outputName + '\'' + <END> ", expression=" + expression + ", outputType=" + outputType + '}'; }</code><technical_language>Missing a , here</technical_language>

Target:
public String toString() { return "DimensionExpression{" + "virtualColumn='" + virtualColumn + '\'' + ", outputName='" + outputName + '\'' + ", expression=" + expression + ", outputType=" + outputType + '}'; }
Source:
<code>private IntegrationResourceHolder bindResourceHolderIfNecessary(String key, Object resource) { if (this.transactionSynchronizationFactory != null && resource != null && TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronization synchronization = this.transactionSynchronizationFactory.create(resource); <START> if (synchronization != null) { <END> TransactionSynchronizationManager.registerSynchronization(synchronization); if (synchronization instanceof IntegrationResourceHolderSynchronization) { IntegrationResourceHolderSynchronization integrationSynchronization = ((IntegrationResourceHolderSynchronization) synchronization); integrationSynchronization.setShouldUnbindAtCompletion(false); IntegrationResourceHolder resourceHolder = integrationSynchronization.getResourceHolder(); if (key != null) { resourceHolder.addAttribute(key, resource); } return resourceHolder; } } } return null; }</code><technical_language>simply move this if statement. instance of test return false for null</technical_language>

Target:
private IntegrationResourceHolder bindResourceHolderIfNecessary(String key, Object resource) { if (this.transactionSynchronizationFactory != null && resource != null && TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronization synchronization = this.transactionSynchronizationFactory.create(resource); if (synchronization != null) { TransactionSynchronizationManager.registerSynchronization(synchronization); if (synchronization instanceof IntegrationResourceHolderSynchronization) { IntegrationResourceHolderSynchronization integrationSynchronization = ((IntegrationResourceHolderSynchronization) synchronization); integrationSynchronization.setShouldUnbindAtCompletion(false); if (!TransactionSynchronizationManager.hasResource(resource)) { TransactionSynchronizationManager.bindResource(resource, integrationSynchronization.getResourceHolder()); } } } Object resourceHolder = TransactionSynchronizationManager.getResource(resource); if (resourceHolder instanceof IntegrationResourceHolder) { IntegrationResourceHolder integrationResourceHolder = (IntegrationResourceHolder) resourceHolder; if (key != null) { integrationResourceHolder.addAttribute(key, resource); } return integrationResourceHolder; } } return null; }
Source:
<code>public void releaseStore(Store<?, ?> resource) { List<Copier> copiers = createdStores.remove(resource); if (copiers == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } final OnHeapStore onHeapStore = (OnHeapStore)resource; close(onHeapStore); CopyProvider copyProvider = serviceProvider.getService(CopyProvider.class); for (Copier copier: copiers) { try { copyProvider.releaseCopier(copier); } catch (Exception e) { throw new IllegalStateException("Exception while releasing Copier instance.", e); } } <START> StatisticsManager.nodeFor(onHeapStore).clean(); <END> tierOperationStatistics.remove(onHeapStore); }</code><technical_language>code throw, this line block releasing Copiers</technical_language>

Target:
public void releaseStore(Store<?, ?> resource) { List<Copier> copiers = createdStores.remove(resource); if (copiers == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } final OnHeapStore onHeapStore = (OnHeapStore)resource; close(onHeapStore); StatisticsManager.nodeFor(onHeapStore).clean(); tierOperationStatistics.remove(onHeapStore); CopyProvider copyProvider = serviceProvider.getService(CopyProvider.class); for (Copier copier: copiers) { try { copyProvider.releaseCopier(copier); } catch (Exception e) { throw new IllegalStateException("Exception while releasing Copier instance.", e); } } }
Source:
<code><START> protected long getRawID(Class<? extends OWLEntity> type) throws AutoIDException { <END> throw new UnsupportedOperationException("Uenxpected Error"); }</code><technical_language>If this class extend AbstractIDGenerator more, this method removed</technical_language>

Target:
protected long getRawID(Class<? extends OWLEntity> type) throws AutoIDException { throw new UnsupportedOperationException("Unexpected Error"); }
Source:
<code>public boolean get(TileObject tile) throws StorageException { Utils.updateLogId("GET-" + tile.toString()); File file = fileManager.getFile(tile); Utils.debug(LOGGER, "Tile mapped to file '%s'.", file); initDatabaseFileIfNeeded(file, tile.getLayerName(), tile.getBlobFormat()); boolean exists = connectionManager.doWork(file, true, connection -> { MBTilesFile mbtiles = GeoToolsMbtilesUtils.getMBTilesFile(connection, file); try { MBTilesTile gtTile = mbtiles.loadTile(tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); if (gtTile.getData() != null) { tile.setBlob(Utils.byteArrayToResource(gtTile.getData())); Utils.debug(LOGGER, "Tile found on file '%s'.", file); return true; } } catch (Exception exception) { throw Utils.exception(exception, "Error loading tile '%s' from MBTiles file '%s'.", tile, file); } Utils.debug(LOGGER, "Tile not found on file '%s'.", file); return false; }); if (exists && useCreateTime) { Long createdTime = getTileCreateTime(file, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); if (createdTime == null) { <START> createdTime = System.currentTimeMillis(); <END> putTileCreateTime(file, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1], createdTime); } tile.setCreated(createdTime); } else if (exists) { tile.setCreated(System.currentTimeMillis()); } return exists; }</code><technical_language>Thinking out loud, more sense file creation time, modified file time</technical_language>

Target:
public boolean get(TileObject tile) throws StorageException { File file = fileManager.getFile(tile); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' mapped to file '%s'.", tile, file)); } initDatabaseFileIfNeeded(file, tile.getLayerName(), tile.getBlobFormat()); boolean exists = connectionManager.doWork(file, true, connection -> { MBTilesFile mbtiles = GeoToolsMbtilesUtils.getMBTilesFile(connection, file); try { MBTilesTile gtTile = mbtiles.loadTile(tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); if (gtTile.getData() != null) { tile.setBlob(Utils.byteArrayToResource(gtTile.getData())); if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' found on file '%s'.", tile, file)); } return true; } } catch (Exception exception) { throw Utils.exception(exception, "Error loading tile '%s' from MBTiles file '%s'.", tile, file); } if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Tile '%s' not found on file '%s'.", tile, file)); } return false; }); if (exists && useCreateTime) { Long createdTime = getTileCreateTime(file, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1]); if (createdTime == null) { createdTime = file.lastModified(); putTileCreateTime(file, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1], createdTime); } tile.setCreated(createdTime); } else if (exists) { tile.setCreated(System.currentTimeMillis()); } return exists; }
Source:
<code>private void loadBeans() { try { Path moduleFolder = FileSystems.getDefault().getPath(modulePath); <START> DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, "*.jar"); <END> for (Path f : stream) { JarFile jarFile = new JarFile(f.toString()); if (hasFrontendFiles(jarFile)) { Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = {new URL("jar:file:" + f.toString() + "!/")}; URLClassLoader cl = URLClassLoader.newInstance(urls); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if (je.isDirectory() || !je.getName().endsWith("Form.class")) { continue; } String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); Class c = cl.loadClass(className); String beanName = className.substring(className.lastIndexOf(".") + 1).trim(); FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); session.getServletContext().setAttribute(beanName, c.newInstance()); } } } } 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 loadBeans() { Path moduleFolder = FileSystems.getDefault().getPath(modulePath); try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, "*.jar")) { for (Path f : stream) { try (JarFile jarFile = new JarFile(f.toString())) { if (hasFrontendFiles(jarFile)) { Enumeration<JarEntry> e = jarFile.entries(); URL[] urls = {new URL("jar:file:" + f.toString() + "!/") }; URLClassLoader cl = URLClassLoader.newInstance(urls); while (e.hasMoreElements()) { JarEntry je = e.nextElement(); if (je.isDirectory() || !je.getName().endsWith("Form.class")) { continue; } String className = je.getName().substring(0, je.getName().length() - 6); className = className.replace('/', '.'); Class c = cl.loadClass(className); String beanName = className.substring(className.lastIndexOf(".") + 1).trim(); FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); session.getServletContext().setAttribute(beanName, c.newInstance()); } } } } } catch (Exception e) { logger.error("Classpath could not be accessed", e.getMessage()); } }
Source:
<code>public String render(String markdownText) { LOGGER.debug("markdownText: {}", markdownText); Node document = parser.parse(markdownText); String html = renderer.render(document); <START> LOGGER.info("Renderer HTML: ", html); <END> return wrapWithMarkdownClassDiv(html); }</code><technical_language>LOGGER.debug - this long</technical_language>

Target:
public String render(String markdownText) { Node document = parser.parse(markdownText); String html = renderer.render(document); return wrapWithMarkdownClassDiv(html); }
Source:
<code>public final void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException { final ResourceResolver resourceResolver = request.getResourceResolver(); final boolean preview = Boolean.parseBoolean(request.getParameter("preview")); log.debug("Preview mode: {}", preview); final ValueMap properties = this.getProperties(request); this.customPrefix = properties.get(PN_ASSET_PREFIX, String.class); this.pageExclusionPatterns = generatePatterns(properties.get(PN_PAGE_EXCLUSIONS, new String[]{})); this.assetExclusionPatterns = generatePatterns(properties.get(PN_ASSET_EXCLUSIONS, new String[]{})); try { final String pagePath = properties.get(PN_PAGE_PATH, String.class); final List<PathFilterSet> paths; if (StringUtils.isBlank(pagePath)) { paths = Collections.emptyList(); } else { paths = this.findAssetPaths(resourceResolver, pagePath); } <START> if (!properties.get(PN_EXCLUDE_PAGES, false) && paths.size() > 0) { <END> PathFilterSet pageFilter = new PathFilterSet(pagePath); if (excludedPages.size() > 0) { for (String excludedPath : excludedPages) { pageFilter.addExclude(new DefaultPathFilter(excludedPath)); } } paths.add(0, pageFilter); } doPackaging(request, response, preview, properties, paths); } catch (RepositoryException ex) { log.error("Repository error while creating Asset Package", ex); response.getWriter().print(packageHelper.getErrorJSON(ex.getMessage())); } catch (IOException ex) { log.error("IO error while creating Asset Package", ex); response.getWriter().print(packageHelper.getErrorJSON(ex.getMessage())); } }</code><technical_language>For code consistency readability, sense put lines 111-119 a findPagePaths function similar findAssetPaths? odd delegate for other</technical_language>

Target:
public final void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException { final ResourceResolver resourceResolver = request.getResourceResolver(); final boolean preview = Boolean.parseBoolean(request.getParameter("preview")); log.debug("Preview mode: {}", preview); final ValueMap properties = this.getProperties(request); AssetPackageUtil assetPackageUtil = new AssetPackageUtil(properties, resourceResolver); try { doPackaging(request, response, preview, properties, assetPackageUtil.getPackageFilterPaths()); } catch (RepositoryException ex) { log.error("Repository error while creating Asset Package", ex); response.getWriter().print(packageHelper.getErrorJSON(ex.getMessage())); } catch (IOException ex) { log.error("IO error while creating Asset Package", ex); response.getWriter().print(packageHelper.getErrorJSON(ex.getMessage())); } }
Source:
<code>private void logicalClose(ChannelProxy proxy) throws Exception { if (this.target == null) { return; } if (this.target != null && !this.target.isOpen()) { synchronized (this.targetMonitor) { if (this.target != null && !this.target.isOpen()) { if (this.target instanceof PublisherCallbackChannel) { this.target.close(); } if (this.channelList.contains(proxy)) { this.channelList.remove(proxy); } this.target = null; return; } } } if (CachingConnectionFactory.this.active && this.publisherConfirms && proxy instanceof PublisherCallbackChannel) { this.theConnection.channelsAwaitingAcks.add(proxy); <START> ((PublisherCallbackChannel) proxy).setAfterAckCallback(this::returnToCache, proxy); <END> } else { returnToCache(proxy); } }</code><technical_language>This a bit awkward, I guess choice PublisherCallbackChannelImpl is ChannelProxy instance. I able this in processAck(). Correct</technical_language>

Target:
private void logicalClose(ChannelProxy proxy) throws Exception { if (this.target == null) { return; } if (this.target != null && !this.target.isOpen()) { synchronized (this.targetMonitor) { if (this.target != null && !this.target.isOpen()) { if (this.target instanceof PublisherCallbackChannel) { this.target.close(); } if (this.channelList.contains(proxy)) { this.channelList.remove(proxy); } this.target = null; return; } } } if (CachingConnectionFactory.this.active && this.publisherConfirms && proxy instanceof PublisherCallbackChannel) { this.theConnection.channelsAwaitingAcks.put(this.target, proxy); ((PublisherCallbackChannel) proxy).setAfterAckCallback(c -> { returnToCache(this.theConnection.channelsAwaitingAcks.remove(c)); }); } else { returnToCache(proxy); } }
Source:
<code>private void validateUploadedChecksumAgainstCache(byte[] checksum, URI artifactPathId, Repository repository) throws ArtifactStorageException { logger.debug("Received checksum: {}", new String(checksum, StandardCharsets.UTF_8)); String artifactPath = artifactPathId.toString(); String artifactBasePath = artifactPath.substring(0, artifactPath.lastIndexOf('.')); String checksumExtension = artifactPath.substring(artifactPath.lastIndexOf('.') + 1, artifactPath.length()); if (!matchesChecksum(checksum, artifactBasePath, checksumExtension)) { String checksumStr = new String(checksum, StandardCharsets.UTF_8); logger.error("The checksum for is invalid!", artifactPath, checksumStr); if (repository.isStrictChecksum()) { <START> throw new ArtifactStorageException(String.format("Checksum broken [%s] for artifact [%s]", checksumStr, artifactPath)); <END> } checksumCacheManager.removeArtifactChecksum(artifactBasePath, checksumExtension); } }</code><technical_language>please change this to: throw new ArtifactStorageException(String.format("Invalid checksum [%s] for artifact [%s]", checksumStr, artifactPath)); Thanks! :)</technical_language>

Target:
private void validateUploadedChecksumAgainstCache(byte[] checksum, URI artifactPathId, Repository repository) throws ArtifactStorageException { logger.debug("Received checksum: {}", new String(checksum, StandardCharsets.UTF_8)); String artifactPath = artifactPathId.toString(); String artifactBasePath = artifactPath.substring(0, artifactPath.lastIndexOf('.')); String checksumExtension = artifactPath.substring(artifactPath.lastIndexOf('.') + 1, artifactPath.length()); if (!matchesChecksum(checksum, artifactBasePath, checksumExtension)) { String checksumStr = new String(checksum, StandardCharsets.UTF_8); logger.error("The checksum for is invalid!", artifactPath, checksumStr); if (repository.isStrictChecksumValidation()) { throw new ArtifactStorageException(String.format("Invalid checksum [%s] for artifact [%s]", checksumStr, artifactPath)); } checksumCacheManager.removeArtifactChecksum(artifactBasePath, checksumExtension); } }
Source:
<code>private void acquireLockAndWait() { if (context.getLock() == null) { Map<String, Pair<String, String>> exclusiveLocks = getExclusiveLocks(); if (exclusiveLocks != null) { <START> EngineLock lock = new EngineLock(exclusiveLocks, null); <END> getLockManager().acquireLockWait(lock); context.withLock(lock); log.info("Lock-wait acquired to object '{}'", lock); } } }</code><technical_language>wait long here, useful a log attempt please</technical_language>

Target:
private void acquireLockAndWait() { if (context.getLock() == null) { Map<String, Pair<String, String>> exclusiveLocks = getExclusiveLocks(); if (exclusiveLocks != null) { EngineLock lock = new EngineLock(exclusiveLocks, null); log.info("Before acquiring and wait lock '{}'", lock); getLockManager().acquireLockWait(lock); context.withLock(lock); log.info("Lock-wait acquired to object '{}'", lock); } } }
Source:
<code>public ObjectStream openStream() throws MissingObjectException, IOException { DfsReader ctx = new DfsReader(db); InputStream in; try { in = new PackInputStream(pack, objectOffset + headerLength, ctx); } catch (IOException packGone) { try { ObjectId obj = pack.findObjectForOffset(ctx, objectOffset); return ctx.open(obj, type).openStream(); } finally { ctx.release(); } } in = new BufferedInputStream( new InflaterInputStream( in, ctx.inflater(), 8192), <START> 8192); <END> return new ObjectStream.Filter(type, size, in); }</code><technical_language>reason for 8192 here</technical_language>

Target:
public ObjectStream openStream() throws MissingObjectException, IOException { DfsReader ctx = new DfsReader(db); InputStream in; try { in = new PackInputStream(pack, objectOffset + headerLength, ctx); } catch (IOException packGone) { try { ObjectId obj = pack.findObjectForOffset(ctx, objectOffset); return ctx.open(obj, type).openStream(); } finally { ctx.release(); } } int bufsz = 8192; in = new BufferedInputStream( new InflaterInputStream(in, ctx.inflater(), bufsz), bufsz); return new ObjectStream.Filter(type, size, in); }
Source:
<code>private static byte[] readAllBytesFromStream(final InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final byte[] buffer = new byte[1024]; int read = 0; while ((read = is.read(buffer)) != -1) { bos.write(buffer, 0, read); } return bos.toByteArray(); } finally { <START> is.close(); <END> bos.close(); } }</code><technical_language>calling is.close() produce exception. Please define: private static void safeClose(final Closeable c) { if (c != null) try { c.close(); } catch (Throwable ignored) {}; } instead of InputStream.close() method</technical_language>

Target:
private static byte[] readAllBytesFromStream(final InputStream is) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final byte[] buffer = new byte[1024]; int read = 0; while ((read = is.read(buffer)) != -1) { bos.write(buffer, 0, read); } return bos.toByteArray(); } finally { safeClose(is); safeClose(bos); } }
Source:
<code>public String toString() { <START> return "OutputParams [aid=" + getAid() + ", avidemux=" + isAvidemux() + ", cleanup=" + isCleanup() + ", forceFps=" + getForceFps() <END> + ", forceType=" + getForceType() + ", fromFrame=" + getFromFrame() + ", header=" + Arrays.toString(getHeader()) + ", hidebuffer=" + isHidebuffer() + ", input_pipes=" + Arrays.toString(getInput_pipes()) + ", log=" + isLog() + ", losslessaudio=" + isLosslessaudio() + ", lossyaudio=" + isLossyaudio() + ", maxBufferSize=" + getMaxBufferSize() + ", mediaRenderer=" + getMediaRenderer() + ", minBufferSize=" + getMinBufferSize() + ", minFileSize=" + getMinFileSize() + ", no_videoencode=" + isNo_videoencode() + ", outputByteArrayStreamBufferSize= " + getOutputByteArrayStreamBufferSize() + ", noexitcheck=" + isNoexitcheck() + ", output_pipes=" + Arrays.toString(getOutput_pipes()) + ", secondread_minsize=" + getSecondread_minsize() + ", shift_scr=" + isShift_scr() + ", sid=" + getSid() + ", stdin=" + getStdin() + ", timeend=" + getTimeend() + ", timeseek=" + getTimeseek() + ", toFrame=" + getToFrame() + ", waitbeforestart=" + getWaitbeforestart() + ", workDir=" + getWorkDir() + ", env=" + getEnv() + "]"; }</code><technical_language>before? More readable</technical_language>

Target:
public String toString() { return "OutputParams [aid=" + getAid() + ", avidemux=" + isAvidemux() + ", cleanup=" + isCleanup() + ", forceFps=" + getForceFps()+ ", forceType=" + getForceType() + ", fromFrame=" + getFromFrame() + ", header=" + Arrays.toString(getHeader()) + ", hidebuffer=" + isHideBuffer() + ", input_pipes=" + Arrays.toString(getInputPipes()) + ", log=" + isLog() + ", losslessaudio=" + isLosslessAudio() + ", lossyaudio=" + isLossyAudio() + ", maxBufferSize=" + getMaxBufferSize() + ", mediaRenderer=" + getMediaRenderer() + ", minBufferSize=" + getMinBufferSize() + ", minFileSize=" + getMinFileSize() + ", no_videoencode=" + isNoVideoEncode() + ", outputByteArrayStreamBufferSize= " + getOutputByteArrayStreamBufferSize() + ", noexitcheck=" + isNoExitCheck() + ", output_pipes=" + Arrays.toString(getOutputPipes()) + ", secondread_minsize=" + getSecondReadMinSize() + ", shift_scr=" + isShiftSscr() + ", sid=" + getSid() + ", stdin=" + getStdIn() + ", timeend=" + getTimeEnd() + ", timeseek=" + getTimeSeek() + ", toFrame=" + getToFrame() + ", waitbeforestart=" + getWaitBeforeStart() + ", workDir=" + getWorkDir() + ", env=" + getEnv() + "]"; }
Source:
<code>public List<StoragePoolTagVO> searchByIds(Long... stIds) { <START> String batchCfg = _configDao.getValue("detail.batch.query.size"); <END> final int detailsBatchSize = batchCfg != null ? Integer.parseInt(batchCfg) : 2000; List<StoragePoolTagVO> uvList = new ArrayList<StoragePoolTagVO>(); int curr_index = 0; if (stIds.length > detailsBatchSize) { while ((curr_index + detailsBatchSize) <= stIds.length) { Long[] ids = new Long[detailsBatchSize]; for (int k = 0, j = curr_index; j < curr_index + detailsBatchSize; j++, k++) { ids[k] = stIds[j]; } SearchCriteria<StoragePoolTagVO> sc = StoragePoolIdsSearch.create(); sc.setParameters("idIN", (Object[])ids); List<StoragePoolTagVO> vms = searchIncludingRemoved(sc, null, null, false); if (vms != null) { uvList.addAll(vms); } curr_index += detailsBatchSize; } } if (curr_index < stIds.length) { int batch_size = (stIds.length - curr_index); Long[] ids = new Long[batch_size]; for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { ids[k] = stIds[j]; } SearchCriteria<StoragePoolTagVO> sc = StoragePoolIdsSearch.create(); sc.setParameters("idIN", (Object[])ids); List<StoragePoolTagVO> vms = searchIncludingRemoved(sc, null, null, false); if (vms != null) { uvList.addAll(vms); } } return uvList; }</code><technical_language>@nvazquez extracting lines 95-97 a method? Then, test cases some doc for it. Especially for 2000 magic number there</technical_language>

Target:
public List<StoragePoolTagVO> searchByIds(Long... stIds) { final int detailsBatchSize = getDetailsBatchSize(); List<StoragePoolTagVO> uvList = new ArrayList<StoragePoolTagVO>(); int curr_index = 0; while ((curr_index + detailsBatchSize) <= stIds.length) { searchForStoragePoolIdsInternal(curr_index, detailsBatchSize, stIds, uvList); curr_index += detailsBatchSize; } if (curr_index < stIds.length) { int batch_size = (stIds.length - curr_index); searchForStoragePoolIdsInternal(curr_index, batch_size, stIds, uvList); } return uvList; }
Source:
<code>public void preExecute() throws OnmsUpgradeException { try (final Connection connection = DataSourceFactory.getInstance().getConnection()) { final Statement preExecutionStatement = connection.createStatement(); try (final ResultSet preExecutionResultSet = preExecutionStatement.executeQuery("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name='events' AND column_name='eventparms')")) { preExecutionResultSet.next(); if (!preExecutionResultSet.getBoolean(1)) { <START> throw new OnmsUpgradeException("The column 'eventParms' does not exists anymore"); <END> } } catch (SQLException e) { e.printStackTrace(); throw new OnmsUpgradeException("Error checking for column 'eventParms'", e); } } catch (SQLException e) { throw new OnmsUpgradeException("Error opening database connection", e); } }</code><technical_language>rephrase this as: 'eventParms' column longer exists</technical_language>

Target:
public void preExecute() throws OnmsUpgradeException { try (final Connection connection = DataSourceFactory.getInstance().getConnection()) { final Statement preExecutionStatement = connection.createStatement(); try (final ResultSet preExecutionResultSet = preExecutionStatement.executeQuery("SELECT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'events') AND attname = 'eventparms')")) { preExecutionResultSet.next(); if (!preExecutionResultSet.getBoolean(1)) { throw new OnmsUpgradeException("The 'eventParms' column no longer exists"); } } catch (SQLException e) { e.printStackTrace(); throw new OnmsUpgradeException("Error checking for column 'eventParms'", e); } } catch (SQLException e) { throw new OnmsUpgradeException("Error opening database connection", e); } }
Source:
<code>public HttpResponse getTagListFromStoreAsAnonymousUser() throws APIManagerIntegrationTestException { try { HttpResponse httpResponse = HttpClient.doPost( new URL(backendURL + "/site/blocks/tag/tag-cloud/ajax/list.jag?action=getAllTags" + <START> "&tenant=carbon.super"), <END> "", requestHeaders); if (new JSONObject(httpResponse.getData()).getBoolean("error")) { throw new APIManagerIntegrationTestException("Error when getting tag list as anonymous user"); } return httpResponse; } catch (IOException ioE) { throw new APIManagerIntegrationTestException( "Exception when retrieve the tag list as anonymous user. Error: " + ioE.getMessage(), ioE); } catch (JSONException e) { throw new APIManagerIntegrationTestException("Response message is not JSON Response" + ". Error: " + e.getMessage(), e); } }</code><technical_language>yiu merge line</technical_language>

Target:
public HttpResponse getTagListFromStoreAsAnonymousUser() throws Exception { try { HttpResponse httpResponse = HttpClient.doPost( new URL(backendURL + "/site/blocks/tag/tag-cloud/ajax/list.jag?action=getAllTags" + "&tenant=carbon.super"), "", requestHeaders); if (new JSONObject(httpResponse.getData()).getBoolean("error")) { throw new Exception("Error when getting tag list as anonymous user"); } return httpResponse; } catch (IOException ioE) { throw new Exception( "Exception when retrieve the tag list as anonymous user. Error: " + ioE.getMessage(), ioE); } catch (JSONException e) { throw new Exception("Response message is not JSON Response. Error: " + e.getMessage(), e); } }
Source:
<code><START> protected @NonNull List<ILinkEvent> getLinkList(long startTime, long endTime, <END> long resolution, @NonNull IProgressMonitor monitor) { return new ArrayList<>(); }</code><technical_language>allow null for event list monitor cancelled, for link list</technical_language>

Target:
protected @Nullable List<ILinkEvent> getLinkList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { return new ArrayList<>(); }
Source:
<code>public synchronized static <T> List<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) { final TeslaAether aether = getAetherClient(config); List<T> retVal = Lists.newArrayList(); if (config.searchCurrentClassloader()) { for (T module : ServiceLoader.load(clazz, Initialization.class.getClassLoader())) { log.info("Adding local module[%s]", module.getClass()); retVal.add(module); } } for (String coordinate : config.getCoordinates()) { log.info("Loading extension[%s] for class[%s]", coordinate, clazz.getName()); try { URLClassLoader loader = getClassLoaderForCoordinates(aether, coordinate); final ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz, loader); for (T module : serviceLoader) { log.info("Adding extension module[%s] for class[%s]", module.getClass(), clazz.getName()); retVal.add(module); } } catch (Exception e) { throw Throwables.propagate(e); } } <START> if (clazz.equals(DruidModule.class)){ <END> loadedDruidModules.addAll(retVal); } return retVal; }</code><technical_language>this is append new modules a list time getFromExtensions is called, fully fix problem pull req</technical_language>

Target:
public synchronized static <T> Collection<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) { final TeslaAether aether = getAetherClient(config); Set<T> retVal = Sets.newHashSet(); if (config.searchCurrentClassloader()) { for (T module : ServiceLoader.load(clazz, Initialization.class.getClassLoader())) { log.info("Adding local module[%s]", module.getClass()); retVal.add(module); } } for (String coordinate : config.getCoordinates()) { log.info("Loading extension[%s] for class[%s]", coordinate, clazz.getName()); try { URLClassLoader loader = getClassLoaderForCoordinates(aether, coordinate); final ServiceLoader<T> serviceLoader = ServiceLoader.load(clazz, loader); for (T module : serviceLoader) { log.info("Adding extension module[%s] for class[%s]", module.getClass(), clazz.getName()); retVal.add(module); } } catch (Exception e) { throw Throwables.propagate(e); } } extensionsMap.put(clazz, retVal); return retVal; }
Source:
<code>private void logResultOfPrestartVms(int prestartedVmsCounter, int numOfVmsToPrestart, Guid vmPoolId, Map<String, Set<Guid>> failureReasonsForVms) { if (prestartedVmsCounter > 0) { log.info("Prestarted VMs out of the required, in VmPool '{}'", prestartedVmsCounter, numOfVmsToPrestart, vmPoolId); } else { log.error("Failed to prestart any VMs for VmPool '{}'", vmPoolId); } if (prestartedVmsCounter < numOfVmsToPrestart) { for (Map.Entry<String, Set<Guid>> entry : failureReasonsForVms.entrySet()) { <START> log.error("Failed to prestart VMs with reason {}", <END> entry.getValue(), entry.getKey()); } } }</code><technical_language>I agree 'info' level is 'error' level high think? a warning do it</technical_language>

Target:
private void logResultOfPrestartVms(int prestartedVmsCounter, int numOfVmsToPrestart, Guid vmPoolId, Map<String, Set<Guid>> failureReasonsForVms) { if (prestartedVmsCounter > 0) { log.info("Prestarted VMs out of the required, in VmPool '{}'", prestartedVmsCounter, numOfVmsToPrestart, vmPoolId); } else { log.warn("Failed to prestart any VMs for VmPool '{}'", vmPoolId); } if (prestartedVmsCounter < numOfVmsToPrestart) { for (Map.Entry<String, Set<Guid>> entry : failureReasonsForVms.entrySet()) { log.warn("Failed to prestart VMs with reason {}", entry.getValue(), entry.getKey()); } } }
Source:
<code>public boolean filterOut(final SAMRecord record) { <START> return readNameFilterSet.contains(record.getReadName()) != includeReads; <END> }</code><technical_language>While this version is more compact, I is more confusing -- draw a truth table confirm behavior is in cases</technical_language>

Target:
public boolean filterOut(final SAMRecord record) { if (includeReads) { if (readNameFilterSet.contains(record.getReadName())) { return false; } } else { if (!readNameFilterSet.contains(record.getReadName())) { return false; } } return true; }