auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
LocalDate computeBestBeforeDate() { if (sysConfigBL.getBooleanValue(HUAttributeConstants.SYSCONFIG_AutomaticallySetBestBeforeDate, false)) { 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; } }

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:
private boolean isNotDuplicateMessage(String message) { for (String currentMessage : getMessages()) { if (StringUtils.equals(currentMessage, message)) { return false; } } return true; }

Target:
private boolean isNotDuplicateMessage(String message) { for (String currentMessage : getMessages()) { if (StringUtils.equalsIgnoreCase(currentMessage, message)) { return false; } } return true; }
Source:
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) { 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); }

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:
protected void onStart() { super.onStart(); user = SyncUser.currentUser(); 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); }

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:
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()); } } }

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:
private <T> Query<T> prioritizeAndLaneQuery(Query<T> query, Iterable<Segment> segments) { Set<SegmentServerSelector> segmentServerSelectors = new HashSet<>(); for (Segment s : segments) { segmentServerSelectors.add(new SegmentServerSelector(null, s.getId().toDescriptor())); } return scheduler.prioritizeAndLaneQuery(QueryPlus.wrap(query), segmentServerSelectors); }

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:
public synchronized void aggregate() { final IndexedInts keys = keySelector.getRow(); if (keys == null) { 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); } }

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:
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.fields = Collections.unmodifiableList( asList(b3Key, traceIdKey, spanIdKey, parentSpanIdKey, sampledKey, debugKey) ); this.injectFormats = new Format[] {factory.injectFormat}; this.kindToInjectFormats = factory.kindToInjectFormats; }

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:
public int close() { addBitsFast(1, 1); flush(); if (currentAddress >= outputLimit) { return 0; } return (int) ((currentAddress - outputAddress) + (bitCount > 0 ? 1 : 0)); }

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

Target:
public String toString() { return "DimensionExpression{" + "virtualColumn='" + virtualColumn + '\'' + ", outputName='" + outputName + '\'' + ", expression=" + expression + ", outputType=" + outputType + '}'; }
Source:
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); IntegrationResourceHolder resourceHolder = integrationSynchronization.getResourceHolder(); if (key != null) { resourceHolder.addAttribute(key, resource); } return resourceHolder; } } } return null; }

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:
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); } } StatisticsManager.nodeFor(onHeapStore).clean(); tierOperationStatistics.remove(onHeapStore); }

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:
protected long getRawID(Class<? extends OWLEntity> type) throws AutoIDException { throw new UnsupportedOperationException("Uenxpected Error"); }

Target:
protected long getRawID(Class<? extends OWLEntity> type) throws AutoIDException { throw new UnsupportedOperationException("Unexpected Error"); }
Source:
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) { createdTime = System.currentTimeMillis(); putTileCreateTime(file, tile.getXYZ()[2], tile.getXYZ()[0], tile.getXYZ()[1], createdTime); } tile.setCreated(createdTime); } else if (exists) { tile.setCreated(System.currentTimeMillis()); } return exists; }

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:
private void loadBeans() { try { Path moduleFolder = FileSystems.getDefault().getPath(modulePath); DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, "*.jar"); 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()); } }

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:
public String render(String markdownText) { LOGGER.debug("markdownText: {}", markdownText); Node document = parser.parse(markdownText); String html = renderer.render(document); LOGGER.info("Renderer HTML: ", html); return wrapWithMarkdownClassDiv(html); }

Target:
public String render(String markdownText) { Node document = parser.parse(markdownText); String html = renderer.render(document); return wrapWithMarkdownClassDiv(html); }
Source:
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); } if (!properties.get(PN_EXCLUDE_PAGES, false) && paths.size() > 0) { 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())); } }

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:
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); ((PublisherCallbackChannel) proxy).setAfterAckCallback(this::returnToCache, proxy); } else { returnToCache(proxy); } }

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:
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()) { throw new ArtifactStorageException(String.format("Checksum broken [%s] for artifact [%s]", checksumStr, artifactPath)); } checksumCacheManager.removeArtifactChecksum(artifactBasePath, checksumExtension); } }

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:
<R> List<R> executeAndGetFunctionResult(Function function, AbstractConfiguration configuration, CacheElementOperation operation, Set<DistributedMember> targetMembers) { if (targetMembers.size() == 0) { return Collections.emptyList(); } List<R> results = new ArrayList(); File file = null; RemoteStreamExporter exporter = null; if (configuration instanceof HasFile) { ManagementAgent agent = ((SystemManagementService) ManagementService.getExistingManagementService(cache)) .getManagementAgent(); exporter = agent.getRemoteStreamExporter(); file = ((HasFile) configuration).getFile(); } for (DistributedMember member : targetMembers) { RemoteInputStream remoteInputStream = null; if (file != null && exporter != null) { try { remoteInputStream = exporter .export(new SimpleRemoteInputStream(new FileInputStream(file.getAbsolutePath()))); } catch (Exception e) { raise(StatusCode.ILLEGAL_ARGUMENT, "Invalid file: " + file.getAbsolutePath()); } } Execution execution = FunctionService.onMember(member) .setArguments(Arrays.asList(configuration, operation, remoteInputStream)); ((AbstractExecution) execution).setIgnoreDepartedMembers(true); results.add(((List<R>) execution.execute(function).getResult()).get(0)); if (remoteInputStream != null) { try { remoteInputStream.close(true); } catch (IOException ex) { } } } return results; }

Target:
<R> List<R> executeAndGetFunctionResult(Function function, AbstractConfiguration configuration, CacheElementOperation operation, Set<DistributedMember> targetMembers) { if (targetMembers.size() == 0) { return Collections.emptyList(); } List<R> results = new ArrayList(); File file = null; if (configuration instanceof HasFile) { file = ((HasFile) configuration).getFile(); } if (file == null) { Execution execution = FunctionService.onMembers(targetMembers) .setArguments(Arrays.asList(configuration, operation, null)); ((AbstractExecution) execution).setIgnoreDepartedMembers(true); ResultCollector rc = execution.execute(function); return (List<R>) rc.getResult(); } RemoteStreamExporter exporter = null; ManagementAgent agent = ((SystemManagementService) ManagementService.getExistingManagementService(cache)) .getManagementAgent(); exporter = agent.getRemoteStreamExporter(); for (DistributedMember member : targetMembers) { FileInputStream fileInputStream = null; SimpleRemoteInputStream inputStream = null; RemoteInputStream remoteInputStream = null; try { fileInputStream = new FileInputStream(file.getAbsolutePath()); inputStream = new SimpleRemoteInputStream(fileInputStream); remoteInputStream = exporter.export(inputStream); Execution execution = FunctionService.onMember(member) .setArguments(Arrays.asList(configuration, operation, remoteInputStream)); ((AbstractExecution) execution).setIgnoreDepartedMembers(true); results.add(((List<R>) execution.execute(function).getResult()).get(0)); } catch (IOException e) { raise(StatusCode.ILLEGAL_ARGUMENT, "Invalid file: " + file.getAbsolutePath()); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (inputStream != null) { inputStream.close(); } if (remoteInputStream != null) { remoteInputStream.close(true); } } catch (IOException ex) { } } } return results; }
Source:
private void acquireLockAndWait() { if (context.getLock() == null) { Map<String, Pair<String, String>> exclusiveLocks = getExclusiveLocks(); if (exclusiveLocks != null) { EngineLock lock = new EngineLock(exclusiveLocks, null); getLockManager().acquireLockWait(lock); context.withLock(lock); log.info("Lock-wait acquired to object '{}'", lock); } } }

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:
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), 8192); return new ObjectStream.Filter(type, size, in); }

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:
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 { is.close(); bos.close(); } }

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:
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(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() + "]"; }

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:
public List<StoragePoolTagVO> searchByIds(Long... stIds) { String batchCfg = _configDao.getValue("detail.batch.query.size"); 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; }

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:
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)) { throw new OnmsUpgradeException("The column 'eventParms' does not exists anymore"); } } 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); } }

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:
public HttpResponse getTagListFromStoreAsAnonymousUser() throws APIManagerIntegrationTestException { 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 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); } }

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:
protected @NonNull List<ILinkEvent> getLinkList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { return new ArrayList<>(); }

Target:
protected @Nullable List<ILinkEvent> getLinkList(long startTime, long endTime, long resolution, @NonNull IProgressMonitor monitor) { return new ArrayList<>(); }
Source:
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); } } if (clazz.equals(DruidModule.class)){ loadedDruidModules.addAll(retVal); } return retVal; }

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:
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()) { log.error("Failed to prestart VMs with reason {}", entry.getValue(), entry.getKey()); } } }

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:
public boolean filterOut(final SAMRecord record) { return readNameFilterSet.contains(record.getReadName()) != includeReads; }

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; }
Source:
public void testBuilderWithPopulatedFieldValues() { String expectedGoogleId = "dummyGoogleId"; String expectedEmail = "dummyEmail"; String expectedName = "dummyName"; String expectedInstitute = "dummyInstitute"; boolean expectedIsInstructor = true; Date expectedCreatedAt = new Date(98765); AccountAttributes observedAccountAttributes = AccountAttributes.builder() .withGoogleId(expectedGoogleId) .withEmail(expectedEmail) .withName(expectedName) .withInstitute(expectedInstitute) .withIsInstructor(expectedIsInstructor) .withCreatedAt(expectedCreatedAt) .withDefaultStudentProfileAttributes(expectedGoogleId) .build(); assertEquals(expectedGoogleId, observedAccountAttributes.getGoogleId()); assertEquals(expectedEmail, observedAccountAttributes.getEmail()); assertEquals(expectedCreatedAt, observedAccountAttributes.createdAt); assertEquals(expectedInstitute, observedAccountAttributes.getInstitute()); assertEquals(expectedIsInstructor, observedAccountAttributes.isInstructor()); assertEquals(expectedName, observedAccountAttributes.getName()); assertEquals(expectedGoogleId, observedAccountAttributes.studentProfile.googleId); }

Target:
public void testBuilderWithPopulatedFieldValues() { String expectedGoogleId = "dummyGoogleId"; String expectedEmail = "email@example.com"; String expectedName = "dummyName"; String expectedInstitute = "dummyInstitute"; boolean expectedIsInstructor = true; Date expectedCreatedAt = new Date(98765); AccountAttributes observedAccountAttributes = AccountAttributes.builder() .withGoogleId(expectedGoogleId) .withEmail(expectedEmail) .withName(expectedName) .withInstitute(expectedInstitute) .withIsInstructor(expectedIsInstructor) .withCreatedAt(expectedCreatedAt) .withDefaultStudentProfileAttributes(expectedGoogleId) .build(); assertEquals(expectedGoogleId, observedAccountAttributes.getGoogleId()); assertEquals(expectedEmail, observedAccountAttributes.getEmail()); assertEquals(expectedCreatedAt, observedAccountAttributes.createdAt); assertEquals(expectedInstitute, observedAccountAttributes.getInstitute()); assertEquals(expectedIsInstructor, observedAccountAttributes.isInstructor()); assertEquals(expectedName, observedAccountAttributes.getName()); assertEquals(expectedGoogleId, observedAccountAttributes.studentProfile.googleId); }
Source:
public void start() { try { final HttpJsonResponse pingResponse = httpJsonRequestFactory.fromUrl(apiEndpoint) .setMethod(HttpMethod.GET) .setTimeout(2000) .request(); if (pingResponse.getResponseCode() == HttpURLConnection.HTTP_OK) { return; } } catch (ApiException | IOException e) { LOG.error( e.getLocalizedMessage(), e); } LOG.error("The workspace agent has attempted to start, but it is unable to ping the Che server at " + apiEndpoint); LOG.error(WSocketEventBusClient.WORKSPACE_AGENT_STOPPED_MESSAGE); try { LOG.info("Workspace /etc/hosts: " + IoUtil.readAndCloseQuietly(new FileInputStream(new File("/etc/hosts")))); } catch (Exception e) { LOG.info(e.getLocalizedMessage(), e); } System.exit(0); }

Target:
public void start() { try { final HttpJsonResponse pingResponse = httpJsonRequestFactory.fromUrl(apiEndpoint) .setMethod(HttpMethod.GET) .setTimeout(2000) .request(); if (pingResponse.getResponseCode() == HttpURLConnection.HTTP_OK) { return; } } catch (ApiException | IOException e) { LOG.error( e.getLocalizedMessage(), e); } LOG.error("The workspace agent has attempted to start, but it is unable to ping the Che server at " + apiEndpoint); LOG.error("The workspace agent has been forcefully stopped. " + "This error happens when the agent cannot resolve the location of the Che server. " + "This error can usually be fixed with additional configuration settings in /conf/che.properties. " + "The Che server will stop this workspace after a short timeout. " + "You can get help by posting your config, stacktrace and workspace /etc/hosts below as a GitHub issue."); try { LOG.info("Workspace /etc/hosts: " + IoUtil.readAndCloseQuietly(new FileInputStream(new File("/etc/hosts")))); } catch (Exception e) { LOG.info(e.getLocalizedMessage(), e); } System.exit(0); }