auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void unassignTransportProvider(List<DatastreamTask> taskList) { Validate.notNull(taskList, "null task"); Set<KafkaProducerWrapper<byte[], byte[]>> producers = new HashSet<>(); for (DatastreamTask task : taskList) { if (_transportProviders.containsKey(task)) { KafkaTransportProvider transportProvider = _transportProviders.remove(task); producers.addAll(transportProvider.getProducers()); } else { LOG.warn("Trying to unassign already unassigned transport provider for task {}.", task); } } producers.forEach(p -> p.unassignTask(taskList)); }

Target:
public void unassignTransportProvider(List<DatastreamTask> taskList) { Validate.notNull(taskList, "null task list"); Set<KafkaProducerWrapper<byte[], byte[]>> producers = new HashSet<>(); for (DatastreamTask task : taskList) { if (_transportProviders.containsKey(task)) { KafkaTransportProvider transportProvider = _transportProviders.remove(task); producers.addAll(transportProvider.getProducers()); } else { LOG.warn("Trying to unassign already unassigned transport provider for task {}.", task); } } producers.forEach(p -> p.unassignTasks(taskList)); }
Source:
public MySQLConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<MetadataStorageTablesConfig> dbTables) { super(config, dbTables); final BasicDataSource datasource = getDatasource(); datasource.setDriverClassLoader(getClass().getClassLoader()); datasource.setDriverClassName("com.mysql.jdbc.Driver"); datasource.setConnectionInitSqls(ImmutableList.of("SET sql_mode='ANSI_QUOTES'")); this.dbi = new DBI(datasource); log.info("Configured MySQL as the metadata storage"); }

Target:
public MySQLConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<MetadataStorageTablesConfig> dbTables) { super(config, dbTables); final BasicDataSource datasource = getDatasource(); datasource.setDriverClassLoader(getClass().getClassLoader()); datasource.setDriverClassName("com.mysql.jdbc.Driver"); datasource.setConnectionInitSqls(ImmutableList.of("SET sql_mode='ANSI_QUOTES'")); this.dbi = new DBI(datasource); log.info("Configured MySQL as metadata storage"); }
Source:
void notifySessionError(String nativeErrorCategory, int nativeErrorCode, String errorMessage) { if (errorHandler == null) { return; } ErrorCode errCode = ErrorCode.fromNativeError(nativeErrorCategory, nativeErrorCode); if (errCode == ErrorCode.CLIENT_RESET) { RealmConfiguration backupRealmConfiguration = configuration.forErrorRecovery(errorMessage); clientResetHandler.onClientReset(this, new ClientResetRequiredError(errCode, "A Client Reset is required. " + "Read more here: <LINK_0>", configuration, backupRealmConfiguration)); } else { AppException wrappedError; if (errCode == ErrorCode.UNKNOWN) { wrappedError = new AppException(nativeErrorCategory, nativeErrorCode, errorMessage); } else { wrappedError = new AppException(errCode, errorMessage); } errorHandler.onError(this, wrappedError); } }

Target:
void notifySessionError(String nativeErrorCategory, int nativeErrorCode, String errorMessage) { if (errorHandler == null) { return; } ErrorCode errCode = ErrorCode.fromNativeError(nativeErrorCategory, nativeErrorCode); if (errCode == ErrorCode.CLIENT_RESET) { RealmConfiguration backupRealmConfiguration = configuration.forErrorRecovery(errorMessage); clientResetHandler.onClientReset(this, new ClientResetRequiredError(appNativePointer, errCode, "A Client Reset is required. " + "Read more here: <LINK_0>", configuration, backupRealmConfiguration)); } else { AppException wrappedError; if (errCode == ErrorCode.UNKNOWN) { wrappedError = new AppException(nativeErrorCategory, nativeErrorCode, errorMessage); } else { wrappedError = new AppException(errCode, errorMessage); } errorHandler.onError(this, wrappedError); } }
Source:
public void UtcDateStringToLocaDateMultiThread() throws InterruptedException { final Thread[] threads = new Thread[8]; final Checker[] checkers = new Checker[threads.length]; for (int i = 0; i < threads.length; i++) { checkers[i] = new Checker("1984/06/19 14:25:11", 456503111000L, 100000); threads[i] = new Thread(checkers[i], "ovf-checker-" + i); threads[i].start(); } for (Thread thread : threads) { thread.join(); } for (Checker checker : checkers) { Assert.assertEquals(0, checker.errors); } }

Target:
public void UtcDateStringToLocaDateMultiThread() throws InterruptedException { final Thread[] threads = new Thread[8]; final Checker[] checkers = new Checker[threads.length]; for (int i = 0; i < threads.length; i++) { checkers[i] = new Checker("1984/06/19 14:25:11", 456503111000L, 100000); threads[i] = new Thread(checkers[i], "ovf-checker-" + i); threads[i].start(); } for (Thread thread : threads) { thread.join(); } for (Checker checker : checkers) { assertEquals(0, checker.errors); } }
Source:
protected void assertCompileTime(final long shortTime, final double factor, final long longTime) { assertThat(longTime+" should be less than "+factor+"x the compile time of "+shortTime, longTime < factor*shortTime); }

Target:
protected void assertCompileTime(final long shortTime, final double factor, final long longTime) { assertTrue(longTime+" should be less than "+factor+"x the compile time of "+shortTime, longTime < factor*shortTime); }
Source:
public DockerImage build(String image, File dir, @CheckForNull File log) throws IOException, InterruptedException { String tag = getDockerFileHash(dir); String full = image + ":" + tag; if (cmd("images").add(image).popen().verifyOrDieWith("failed to query the status of the image").trim().contains(" " + tag + " ")) { return new DockerImage(full); } ProcessBuilder buildCmd = cmd("build").add("-t", full, dir).build(); if (log != null) { buildCmd.redirectError(log).redirectOutput(log); } else { buildCmd.redirectError(ProcessBuilder.Redirect.INHERIT).redirectOutput(ProcessBuilder.Redirect.INHERIT); } if (buildCmd.start().waitFor() != 0) { throw new Error("Failed to start image: " + tag); } return new DockerImage(full); }

Target:
public DockerImage build(String image, File dir, @CheckForNull File log) throws IOException, InterruptedException { String tag = getDockerFileHash(dir); String full = image + ":" + tag; if (cmd("images").add(image).popen().verifyOrDieWith("failed to query the status of the image").trim().contains(" " + tag + " ")) { return new DockerImage(full); } CommandBuilder buildCmd = cmd("build").add("-t", full, dir); ProcessBuilder processBuilder = buildCmd.build(); if (log != null) { processBuilder.redirectError(log).redirectOutput(log); } else { processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT).redirectOutput(ProcessBuilder.Redirect.INHERIT); } StringBuilder sb = new StringBuilder("Building Docker image `").append(buildCmd.toString()).append("`"); if (log != null) { sb.append(": logfile is at ").append(log); } System.out.println(sb.toString()); if (processBuilder.start().waitFor() != 0) { throw new Error("Failed to build image: " + tag); } return new DockerImage(full); }
Source:
public void execute() { if (debug != null) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.DEBUG); rootLogger.debug("Initialized debug logging"); } MesosCluster cluster = getCluster(); if (cluster != null) { output.println("Cluster " + cluster.getClusterId() + " is already running"); return; } ClusterArchitecture clusterArchitecture = getClusterArchitecture(); startedCluster = new MesosCluster(clusterArchitecture); startedCluster.start(); startedCluster.waitForState(state -> state != null); startedCluster.printServiceUrls(output); ClusterRepository.saveClusterFile(startedCluster); }

Target:
public void execute() { if (debug != null) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.DEBUG); LOGGER.debug("Initialized debug logging"); } MesosCluster cluster = getCluster(); if (cluster != null) { output.println("Cluster " + cluster.getClusterId() + " is already running"); return; } ClusterArchitecture clusterArchitecture = getClusterArchitecture(); startedCluster = new MesosCluster(clusterArchitecture); startedCluster.start(); startedCluster.waitForState(state -> state != null); startedCluster.printServiceUrls(output); ClusterRepository.saveClusterFile(startedCluster); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.calendarName == null) ? 0 : this.calendarName.hashCode()); result = prime * result + ((this.activatePassiveCalendarTime == null) ? 0 : this.activatePassiveCalendarTime.hashCode()); result = prime * result + ((this.seasonProfileList == null) ? 0 : this.seasonProfileList.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.calendarName.hashCode(); result = prime * result + this.activatePassiveCalendarTime.hashCode(); result = prime * result + this.seasonProfileList.hashCode(); return result; }
Source:
private void updateExistingAndNewVolumes(Guid clusterId, Map<Guid, GlusterVolumeEntity> volumesMap) { VDSGroup cluster = getClusterDao().get(clusterId); for (Entry<Guid, GlusterVolumeEntity> entry : volumesMap.entrySet()) { GlusterVolumeEntity volume = entry.getValue(); log.debug("Analyzing volume '{}'", volume.getName()); GlusterVolumeEntity existingVolume = getVolumeDao().getById(entry.getKey()); if (existingVolume == null) { try { createVolume(volume); } catch (Exception e) { log.error("Could not save volume in database: {}", volume.getName(), e.getMessage()); log.debug("Exception", e); } } else { try { log.debug("Volume '{}' exists in engine. Checking if it needs to be updated.", existingVolume.getName()); updateVolume(existingVolume, volume); } catch (Exception e) { log.error("Error while updating volume '{}': {}", volume.getName(), e.getMessage()); log.debug("Exception", e); } } if (GlusterFeatureSupported.glusterSnapshot(cluster.getCompatibilityVersion()) && cluster.isGlusterCliBasedSchedulingOn() && (Config.<String> getValue(ConfigValues.GlusterMetaVolumeName)).equalsIgnoreCase(volume.getName())) { VdcReturnValueBase returnValue = getBackend().runInternalAction(VdcActionType.DisableGlusterCliSnapshotScheduleInternal, new DisableGlusterCliSnapshotScheduleParameters(volume.getId(), false), ExecutionHandler.createInternalJobContext()); if (!returnValue.getSucceeded()) { log.warn("Unbale to set volume snapshot scheduling flag to gluster CLI scheduler"); } else { logUtil.logVolumeMessage(volume, AuditLogType.GLUSTER_CLI_SNAPSHOT_SCHEDULE_DISABLED); } } } }

Target:
private void updateExistingAndNewVolumes(Guid clusterId, Map<Guid, GlusterVolumeEntity> volumesMap) { VDSGroup cluster = getClusterDao().get(clusterId); for (Entry<Guid, GlusterVolumeEntity> entry : volumesMap.entrySet()) { GlusterVolumeEntity volume = entry.getValue(); log.debug("Analyzing volume '{}'", volume.getName()); GlusterVolumeEntity existingVolume = getVolumeDao().getById(entry.getKey()); if (existingVolume == null) { try { createVolume(volume); } catch (Exception e) { log.error("Could not save volume in database: {}", volume.getName(), e.getMessage()); log.debug("Exception", e); } } else { try { log.debug("Volume '{}' exists in engine. Checking if it needs to be updated.", existingVolume.getName()); updateVolume(existingVolume, volume); } catch (Exception e) { log.error("Error while updating volume '{}': {}", volume.getName(), e.getMessage()); log.debug("Exception", e); } } if (GlusterFeatureSupported.glusterSnapshot(cluster.getCompatibilityVersion()) && cluster.isGlusterCliBasedSchedulingOn() && (Config.<String> getValue(ConfigValues.GlusterMetaVolumeName)).equalsIgnoreCase(volume.getName())) { VdcReturnValueBase returnValue = getBackend().runInternalAction(VdcActionType.DisableGlusterCliSnapshotScheduleInternal, new GlusterVolumeActionParameters(volume.getId(), false), ExecutionHandler.createInternalJobContext()); if (!returnValue.getSucceeded()) { log.warn("Unbale to set volume snapshot scheduling flag to gluster CLI scheduler"); } else { logUtil.logVolumeMessage(volume, AuditLogType.GLUSTER_CLI_SNAPSHOT_SCHEDULE_DISABLED); } } } }
Source:
public DropwizardEmitter( DropwizardEmitterConfig config, ObjectMapper mapper, List<Emitter> alertEmitters ) { this.alertEmitters = alertEmitters; this.config = config; this.reporters = config.getReporters(); this.converter = new DropwizardConverter(mapper, config.getDimensionMapPath()); this.gagues = Collections.synchronizedMap(new GaugesCache<>(config.getMaxGaugeCount())); }

Target:
public DropwizardEmitter( DropwizardEmitterConfig config, ObjectMapper mapper, List<Emitter> alertEmitters ) { this.alertEmitters = alertEmitters; this.config = config; this.reporters = config.getReporters(); this.converter = new DropwizardConverter(mapper, config.getDimensionMapPath()); final Cache<String, Metric> metricsRegistryCache = Caffeine.newBuilder() .recordStats() .maximumSize(config.getMaxMetricsRegistrySize()) .build(); metricsRegistry = new MetricRegistry() { @Override protected ConcurrentMap<String, Metric> buildMap() { return metricsRegistryCache.asMap(); } }; }
Source:
public static void waitFor(final Runnable runnable, final long timeoutMs, final int intervalMs, final Class<? extends Throwable>... additionalException) { final Class<? extends Throwable>[] leadToRetry = new Class[additionalException.length + 1]; System.arraycopy(additionalException, 0, leadToRetry, 1, additionalException.length); leadToRetry[0] = AssertionError.class; executeWithRetry( runnable, new RetryForSpecifiedTimeStrategy<Void>(timeoutMs) .withExceptionsThatForceRetry(leadToRetry) .withWaitBetweenEachTry(intervalMs)); }

Target:
public static void waitFor(final Runnable runnable, final long timeoutMs, final int intervalMs, final Class<? extends Throwable>... additionalException) { final List<Class<? extends Throwable>> leadToRetry = Stream.concat(Stream.of(additionalException), Stream.of(AssertionError.class)).collect(toList()); executeWithRetry( runnable, new RetryForSpecifiedTimeStrategy<Void>(timeoutMs) .withExceptionsThatForceRetry(leadToRetry) .withWaitBetweenEachTry(intervalMs)); }
Source:
public static List<String> validateClass(Class<? extends Messages> classUnderTest, File messagesDir) throws URISyntaxException, IOException { List<String> errors = new ArrayList<String>(); List<Method> messagesMethods = new ArrayList<Method>(); messagesMethods.addAll(Arrays.asList(classUnderTest.getDeclaredMethods())); classUnderTest = CommonApplicationMessages.class; for (File localeFile: getMessagesPropertiesFiles(messagesDir, classUnderTest)) { PropertiesFileInfo.properties = loadProperties(localeFile); PropertiesFileInfo.fileName = localeFile.getName(); compareMethodsToProperties(messagesMethods, errors, classUnderTest); } return errors; }

Target:
public static List<String> validateClass(Class<? extends Messages> classUnderTest, File messagesDir) throws URISyntaxException, IOException { List<String> errors = new ArrayList<String>(); if (classUnderTest.isInterface()) { List<Method> messagesMethods = new ArrayList<Method>(); messagesMethods.addAll(Arrays.asList(classUnderTest.getMethods())); for (File localeFile: getMessagesPropertiesFiles(messagesDir, classUnderTest)) { PropertiesFileInfo.properties = loadProperties(localeFile); PropertiesFileInfo.fileName = localeFile.getName(); compareMethodsToProperties(messagesMethods, errors, classUnderTest); } } else { errors.add("Class under test not interface: " + classUnderTest.getName()); } return errors; }
Source:
public void testConditionExistingAndMissingInActivation() throws Exception { Properties sysProperties = new Properties(); sysProperties.setProperty( "myproperty", "test" ); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); assertNotNull( builder ); DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setProcessPlugins( true ); request.setPomFile( getPom( "complexEmptyAndMissing" ) ); request.setSystemProperties( sysProperties ); try { builder.build( request ); } catch(Exception e) { assertTrue(e instanceof ModelBuildingException); } }

Target:
public void testConditionExistingAndMissingInActivation() throws Exception { Properties sysProperties = new Properties(); sysProperties.setProperty( "myproperty", "test" ); ModelBuilder builder = new DefaultModelBuilderFactory().newInstance(); assertNotNull( builder ); DefaultModelBuildingRequest request = new DefaultModelBuildingRequest(); request.setProcessPlugins( true ); request.setPomFile( getPom( "complexExistsAndMissing" ) ); request.setSystemProperties( sysProperties ); builder.build( request ); }
Source:
public static Collection<Persona> getPersonaByAccountIdentifierLike(String partialName) throws CentralRepoException { String queryClause = "SELECT DISTINCT accounts.id as a_id," + "p.id, p.uuid, p.name, p.comment, p.created_date, p.modified_date, p.status_id, p.examiner_id, e.login_name, e.display_name" + " FROM accounts" + " JOIN persona_accounts as pa ON pa.account_id = accounts.id" + " JOIN personas as p ON p.id = pa.persona_id" + " JOIN examiners as e ON e.id = p.examiner_id" + " WHERE LOWER(accounts.account_unique_identifier) LIKE LOWER('%" + partialName + "%')" + " AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId() + " GROUP BY p.id"; PersonaQueryCallback queryCallback = new PersonaQueryCallback(); CentralRepository.getInstance().executeSelectSQL(queryClause, queryCallback); return queryCallback.getPersonas(); }

Target:
public static Collection<Persona> getPersonaByAccountIdentifierLike(String partialName) throws CentralRepoException { String queryClause = "SELECT DISTINCT accounts.id as a_id," + "p.id, p.uuid, p.name, p.comment, p.created_date, p.modified_date, p.status_id, p.examiner_id, e.login_name, e.display_name" + " FROM accounts" + " JOIN persona_accounts as pa ON pa.account_id = accounts.id" + " JOIN personas as p ON p.id = pa.persona_id" + " JOIN examiners as e ON e.id = p.examiner_id" + " WHERE LOWER(accounts.account_unique_identifier) LIKE LOWER('%" + partialName + "%')" + " AND p.status_id != " + Persona.PersonaStatus.DELETED.getStatusId() + " GROUP BY p.id"; PersonaQueryCallback queryCallback = new PersonaQueryCallback(); CentralRepository cr = CentralRepository.getInstance(); if (cr != null) { cr.executeSelectSQL(queryClause, queryCallback); } return queryCallback.getPersonas(); }
Source:
protected Set<String> getApplicableColos(String type, Entity entity) { try { if (DeploymentUtil.isEmbeddedMode()) { return DeploymentUtil.getDefaultColos(); } if (EntityType.getEnum(type) == EntityType.CLUSTER) { return getAllColos(); } Set<String> clusters = EntityUtil.getClustersDefined(entity); Set<String> colos = new HashSet<String>(); for (String cluster : clusters) { try{ Cluster clusterEntity = EntityUtil.getEntity(EntityType.CLUSTER, cluster); if(type.equals(EntityType.PROCESS)){ EntityUtil.getEntity(EntityType.PROCESS,entity.getName()); } colos.add(clusterEntity.getColo()); } catch (EntityNotRegisteredException e){ LOG.warn(e.getMessage(), e); } } if (colos.isEmpty()) { throw new EntityNotRegisteredException(entity.getName() + " (" + type + ") not found"); } return colos; } catch (FalconException e) { throw FalconWebException.newAPIException(e); } }

Target:
protected Set<String> getApplicableColos(String type, Entity entity) { try { if (DeploymentUtil.isEmbeddedMode()) { return DeploymentUtil.getDefaultColos(); } if (EntityType.getEnum(type) == EntityType.CLUSTER) { return getAllColos(); } Set<String> clusters = EntityUtil.getClustersDefined(entity); Set<String> colos = new HashSet<String>(); try{ EntityType entitytype = EntityType.getEnum(type); if (entitytype == EntityType.PROCESS || entitytype == EntityType.FEED){ EntityUtil.getEntity(entitytype, entity.getName()); } for (String cluster : clusters) { Cluster clusterEntity = EntityUtil.getEntity(EntityType.CLUSTER, cluster); colos.add(clusterEntity.getColo()); } }catch (EntityNotRegisteredException e){ LOG.warn(e.getMessage(), e); } if (colos.isEmpty()) { throw new EntityNotRegisteredException(entity.getName() + " (" + type + ") not found"); } return colos; } catch (FalconException e) { throw FalconWebException.newAPIException(e); } }
Source:
public static int packIp4AddressBytes(short[] bytes) throws KuraException { if ((bytes == null) || (bytes.length != 4)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } int val = 0; for (int i = 0; i < 4; i++) { if ((bytes[i] < 0) || (bytes[i] > 255)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } val = val << 8; val |= bytes[i]; } return val; }

Target:
public static int packIp4AddressBytes(short[] bytes) { if ((bytes == null) || (bytes.length != 4)) { throw new IllegalArgumentException("bytes is null or invalid"); } int val = 0; for (int i = 0; i < 4; i++) { if ((bytes[i] < 0) || (bytes[i] > 255)) { throw new IllegalArgumentException( "bytes is invalid; value is out of range: " + Integer.toString(bytes[i])); } val = val << 8; val |= bytes[i]; } return val; }
Source:
CachedConnection reserveAny(final ThriftTransportKey key) { return executeWithinLock(key, () -> getOrCreateCachedConnections(key).reserveAny()); }

Target:
CachedConnection reserveAny(final ThriftTransportKey key) { var connections = getOrCreateCachedConnections(key); return executeWithinLock(key, connections::reserveAny); }
Source:
@Override public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); monthView.setDividerColor(dividerColor); monthView.setDayTextColor(dayTextColorResId); monthView.setTitleTextColor(titleTextColor); monthView.setHeaderTextColor(headerTextColor); if (dayBackgroundResId != 0) { monthView.setDayBackground(dayBackgroundResId); } } monthView.init(months.get(position), cells.get(position), displayOnly); return monthView; }

Target:
@Override public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today, dividerColor, dayBackgroundResId, dayTextColorResId, titleTextColor, headerTextColor); } monthView.init(months.get(position), cells.get(position), displayOnly); return monthView; }
Source:
private Object doMput(Message<?> requestMessage) { File file = null; Object payload = requestMessage.getPayload(); if (payload instanceof File) { file = (File) payload; } else if (payload instanceof String) { file = new File((String) payload); } else if (!(payload instanceof Collection)) { throw new IllegalArgumentException( "Only File or String payloads (or Collection of File/String) allowed for 'mput', received: " + payload.getClass()); } if ((payload instanceof Collection)) { return ((Collection<?>) payload).stream() .map(p -> doMput(getMessageBuilderFactory().withPayload(p) .copyHeaders(requestMessage.getHeaders()) .build())) .collect(Collectors.toList()); } else if (!file.isDirectory()) { return doPut(requestMessage); } else { File localDir = file; return this.remoteFileTemplate.invoke(t -> mPut(requestMessage, t.getSession(), localDir)); } }

Target:
private Object doMput(Message<?> requestMessage) { File file = null; Object payload = requestMessage.getPayload(); if (payload instanceof File) { file = (File) payload; } else if (payload instanceof String) { file = new File((String) payload); } else if (!(payload instanceof Collection)) { throw new IllegalArgumentException( "Only File or String payloads (or Collection of File/String) allowed for 'mput', received: " + payload.getClass()); } if ((payload instanceof Collection)) { return ((Collection<?>) payload).stream() .map(p -> doMput(new MutableMessage<>(p, requestMessage.getHeaders()))) .collect(Collectors.toList()); } else if (!file.isDirectory()) { return doPut(requestMessage); } else { File localDir = file; return this.remoteFileTemplate.invoke(t -> mPut(requestMessage, t.getSession(), localDir)); } }
Source:
private void apply(File file) throws Exception { String data; try (InputStream input = new FileInputStream(file)) { data = IOUtils.toString(input, StandardCharsets.UTF_8.name()); LOGGER.debug("Installing file [{}]. Contents:\n{}", file.getAbsolutePath(), data); } if (StringUtils.isEmpty(data)) { LOGGER.debug("File is empty [{}]. Nothing to install.", file.getAbsolutePath()); return; } Outer outer; try { outer = GSON.fromJson(data, Outer.class); } catch (ClassCastException e) { throw new IllegalArgumentException("Cannot parse json [" + file.getAbsolutePath() + "]", e); } final String filename = file.getName(); final Changeset changeset = new Changeset(); changesetsByFile.put(filename, changeset); handleSection(changeset, "Attribute Types", outer.attributeTypes, this::parseAttributeTypes); handleSection( changeset, METACARD_TYPES_PROPERTY, outer.metacardTypes, this::parseMetacardTypes); handleSection(changeset, VALIDATORS_PROPERTY, outer.validators, this::parseValidators); handleSection(changeset, DEFAULTS_PROPERTY, outer.defaults, this::parseDefaults); handleSection(changeset, INJECTIONS_PROPERTY, outer.inject, this::parseInjections); handleSection( changeset, METACARD_VALIDATORS_PROPERTY, outer.metacardvalidators, this::registerMetacardValidators); }

Target:
private void apply(File file) throws Exception { String data; try (InputStream input = new FileInputStream(file)) { data = IOUtils.toString(input, StandardCharsets.UTF_8.name()); LOGGER.debug("Installing file [{}]. Contents:\n{}", file.getAbsolutePath(), data); } if (StringUtils.isEmpty(data)) { LOGGER.debug("File is empty [{}]. Nothing to install.", file.getAbsolutePath()); return; } Outer outer = GSON.fromJson(data, Outer.class); final String filename = file.getName(); final Changeset changeset = new Changeset(); changesetsByFile.put(filename, changeset); handleSection(changeset, "Attribute Types", outer.attributeTypes, this::parseAttributeTypes); handleSection( changeset, METACARD_TYPES_PROPERTY, outer.metacardTypes, this::parseMetacardTypes); handleSection(changeset, VALIDATORS_PROPERTY, outer.validators, this::parseValidators); handleSection(changeset, DEFAULTS_PROPERTY, outer.defaults, this::parseDefaults); handleSection(changeset, INJECTIONS_PROPERTY, outer.inject, this::parseInjections); handleSection( changeset, METACARD_VALIDATORS_PROPERTY, outer.metacardvalidators, this::registerMetacardValidators); }
Source:
private boolean matchesParameterAndReturnTypes(Method method, List<Type> resolvedTypes, Type returnType) { checkState(method.getParameterCount() >= resolvedTypes.size(), "method %s has not enough arguments: %s (should have at least %s)", method.getName(), method.getParameterCount(), resolvedTypes.size()); Class<?>[] methodParameterJavaTypes = method.getParameterTypes(); for (int i = 0, methodParameterIndex = 0; i < resolvedTypes.size(); i++) { NullConvention nullConvention = argumentProperties.get(i).getNullConvention(); Class<?> type = getNullAwareContainerType(resolvedTypes.get(i).getJavaType(), nullConvention == USE_BOXED_TYPE); if (!methodParameterJavaTypes[methodParameterIndex].equals(type)) { return false; } methodParameterIndex += (nullConvention == USE_NULL_FLAG || nullConvention == BLOCK_POSITION) ? 2 : 1; } return method.getReturnType().equals(getNullAwareContainerType(returnType.getJavaType(), nullableResult)); }

Target:
private boolean matchesParameterAndReturnTypes(Method method, List<Type> resolvedTypes, Type returnType) { checkState(method.getParameterCount() >= resolvedTypes.size(), "method %s has not enough arguments: %s (should have at least %s)", method.getName(), method.getParameterCount(), resolvedTypes.size()); Class<?>[] methodParameterJavaTypes = method.getParameterTypes(); for (int i = 0, methodParameterIndex = 0; i < resolvedTypes.size(); i++) { NullConvention nullConvention = argumentProperties.get(i).getNullConvention(); Class<?> type = getNullAwareContainerType(resolvedTypes.get(i).getJavaType(), nullConvention == USE_BOXED_TYPE); if (!methodParameterJavaTypes[methodParameterIndex].equals(type)) { return false; } methodParameterIndex += nullConvention.getParameterCount(); } return method.getReturnType().equals(getNullAwareContainerType(returnType.getJavaType(), nullableResult)); }
Source:
UnnnecessaryLoadingTest.CountingStore getCacheStore(Cache cache) { return (UnnnecessaryLoadingTest.CountingStore) TestingUtil.getFirstLoader(cache); }

Target:
UnnecessaryLoadingTest.CountingStore getCacheStore(Cache cache) { return (UnnecessaryLoadingTest.CountingStore) TestingUtil.getFirstLoader(cache); }
Source:
public VaultRawSecret obtainSecret(String vaultSecretId) { Path secretPath = vaultPath.resolve(Paths.get(vaultSecretId)); if (!Files.exists(secretPath)) { return DefaultVaultRawSecret.empty(); } try(InputStream is = Files.newInputStream(secretPath)) { byte[] buf = new byte[is.available()]; is.read(buf); return DefaultVaultRawSecret.forByteArray(buf); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public VaultRawSecret obtainSecret(String vaultSecretId) { Path secretPath = resolveSecretPath(vaultSecretId); if (!Files.exists(secretPath)) { return DefaultVaultRawSecret.forBuffer(Optional.empty()); } try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(secretPath, EnumSet.of(StandardOpenOption.READ))) { MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); return DefaultVaultRawSecret.forBuffer(Optional.of(mappedByteBuffer)); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void saveLibraries(final Collection<Library> libraries) throws IOException { log.info("Migrating libraries..."); Date now = new Date(); User user = serviceManager.getAuthorizationManager().getCurrentUser(); for (Library library : libraries) { library.inheritPermissions(library.getSample()); valueTypeLookup.resolveAll(library); library.setLastModifier(user); library.setLastUpdated(now); library.getLibraryAdditionalInfo().setCreatedBy(user); library.getLibraryAdditionalInfo().setCreationDate(now); library.getLibraryAdditionalInfo().setUpdatedBy(user); library.getLibraryAdditionalInfo().setLastUpdated(now); if (replaceChangeLogs) { Collection<ChangeLog> changes = library.getChangeLog(); library.setId(serviceManager.getLibraryDao().save(library)); saveLibraryChangeLog(library, changes); } else { library.setId(serviceManager.getLibraryDao().save(library)); } log.debug("Saved library " + library.getAlias()); } log.info(libraries.size() + " libraries migrated."); }

Target:
public void saveLibraries(final Collection<Library> libraries) throws IOException { log.info("Migrating libraries..."); User user = serviceManager.getAuthorizationManager().getCurrentUser(); for (Library library : libraries) { library.inheritPermissions(library.getSample()); valueTypeLookup.resolveAll(library); library.setLastModifier(user); library.setLastUpdated(timeStamp); library.getLibraryAdditionalInfo().setCreatedBy(user); library.getLibraryAdditionalInfo().setCreationDate(timeStamp); library.getLibraryAdditionalInfo().setUpdatedBy(user); library.getLibraryAdditionalInfo().setLastUpdated(timeStamp); if (replaceChangeLogs) { Collection<ChangeLog> changes = library.getChangeLog(); library.setId(serviceManager.getLibraryDao().save(library)); saveLibraryChangeLog(library, changes); } else { library.setId(serviceManager.getLibraryDao().save(library)); } log.debug("Saved library " + library.getAlias()); } log.info(libraries.size() + " libraries migrated."); }
Source:
public Optional<Integer> getVal(ItemStack container) { return Optional.of(container.getMaxDamage() - container.getItemDamage()); }

Target:
public Optional<Integer> getVal(ItemStack container) { if(container.getItem().isDamageable()) { return Optional.of(container.getMaxDamage() - container.getItemDamage()); } return Optional.empty(); }
Source:
Aggregator[] getValueAggregators(TopNQuery query, BaseLongColumnValueSelector selector, Cursor cursor) { long key = selector.getLong(); Aggregator[] aggs = aggregatesStore.get(key); if (aggs == null) { aggs = BaseTopNAlgorithm.makeAggregators(cursor, query.getAggregatorSpecs()); aggregatesStore.put(key, aggs); } return aggs; }

Target:
Aggregator[] getValueAggregators(TopNQuery query, BaseLongColumnValueSelector selector, Cursor cursor) { long key = selector.getLong(); return aggregatesStore.computeIfAbsent( key, k -> BaseTopNAlgorithm.makeAggregators(cursor, query.getAggregatorSpecs()) ); }
Source:
protected String getText() { if (missingFile.length() > 0) { return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_0, missingFile); } else { if (context == null) return super.getText(); String contextDescription; ICSourceNotFoundDescription description = context.getAdapter(ICSourceNotFoundDescription.class); if (description != null) { contextDescription = description.getDescription(); } else contextDescription = context.toString(); if (description.isAdress()) return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_8, contextDescription); return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_3, contextDescription); } }

Target:
protected String getText() { if (missingFile.length() > 0) { return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_0, missingFile); } else { if (context == null) return super.getText(); String contextDescription; ICSourceNotFoundDescription description = context.getAdapter(ICSourceNotFoundDescription.class); if (description != null) contextDescription = description.getDescription(); else contextDescription = context.toString(); if (description.isAddress()) return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_8, contextDescription); return NLS.bind(SourceLookupUIMessages.CSourceNotFoundEditor_3, contextDescription); } }
Source:
public void testOpenWithDownBroker() throws Exception { String sinkstr = "{\n" + " \"type\": \"kafka\",\n" + " \"client.id\": \"kafkasink\",\n" + " \"bootstrap.servers\": \"localhost:7101\",\n" + " \"kafka.etc\": {\n" + " \"acks\": \"1\"\n" + " }\n" + "}"; KafkaSink sink = jsonMapper.readValue(sinkstr, new TypeReference<Sink>(){}); sink.open(); Assert.assertTrue(sink.isOpened()); sink.close(); }

Target:
public void testOpenWithDownBroker() throws Exception { String sinkstr = "{\n" + " \"type\": \"kafka\",\n" + " \"client.id\": \"kafkasink\",\n" + " \"bootstrap.servers\": \"localhost:1\",\n" + " \"kafka.etc\": {\n" + " \"acks\": \"1\"\n" + " }\n" + "}"; KafkaSink sink = jsonMapper.readValue(sinkstr, new TypeReference<Sink>(){}); sink.open(); Assert.assertTrue(sink.isOpened()); sink.close(); }
Source:
public void reschedule_commands_from_storage_in_parallel_on_build_if_thread_spawning_allowed() { final String mainThreadName = Thread.currentThread().getName(); final StringBuilder threadNameUponScheduling = new StringBuilder(0); final CommandScheduler scheduler = threadAwareScheduler(threadNameUponScheduling); storeSingleCommandForRescheduling(); final CommandBus commandBus = CommandBus.newBuilder() .setCommandStore(commandStore) .setCommandScheduler(scheduler) .setThreadSpawnAllowed(true) .setAutoReschedule(true) .build(); assertNotNull(commandBus); try { Thread.sleep(150); } catch (InterruptedException e) { throw new IllegalStateException(e); } final ArgumentCaptor<Command> commandCaptor = ArgumentCaptor.forClass(Command.class); verify(scheduler, times(1)).schedule(commandCaptor.capture()); final String actualThreadName = threadNameUponScheduling.toString(); assertNotNull(actualThreadName); assertNotEquals(mainThreadName, actualThreadName); }

Target:
public void reschedule_commands_from_storage_in_parallel_on_build_if_thread_spawning_allowed() { final String mainThreadName = Thread.currentThread().getName(); final StringBuilder threadNameUponScheduling = new StringBuilder(0); final CountDownLatch latch = new CountDownLatch(1); final CommandScheduler scheduler = threadAwareScheduler(threadNameUponScheduling, latch); storeSingleCommandForRescheduling(); final CommandBus commandBus = CommandBus.newBuilder() .setCommandStore(commandStore) .setCommandScheduler(scheduler) .setThreadSpawnAllowed(true) .setAutoReschedule(true) .build(); assertNotNull(commandBus); try { latch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } final ArgumentCaptor<Command> commandCaptor = ArgumentCaptor.forClass(Command.class); verify(scheduler, times(1)).schedule(commandCaptor.capture()); final String actualThreadName = threadNameUponScheduling.toString(); assertNotNull(actualThreadName); assertNotEquals(mainThreadName, actualThreadName); }
Source:
public String getMode() { if (!isEnabled()) { return DISABLED_MODE; } else if (opened) { return ACTIVE_MODE; } return DEFAULT_MODE; }

Target:
public String getMode() { if (!isEnabled()) { return DISABLED_MODE; } else if (opened || this.equals(TabbingManager.focusedWidget)) { return ACTIVE_MODE; } return DEFAULT_MODE; }
Source:
public static <T> T first(Class<T>type){ return findById(type, 1); }

Target:
public static <T> T first(Class<T>type){ List<T> list = findWithQuery(type, "SELECT * FROM " + NamingHelper.toSQLName(type) + " ORDER BY ROWID ASC LIMIT 1" ); if (list.isEmpty()) return null; return list.get(0); }
Source:
private boolean makeGitHubTeamVisible(Channel channel, User sender, String team) { boolean result = false; if (!isSenderAuthorized(channel, sender)) { insufficientPermissionError(channel); return false; } OutputChannel out = channel.send(); try { GitHub github = GitHub.connect(); GHOrganization o = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION); final GHTeam ghTeam = o.getTeamByName(team); if (ghTeam == null) { out.message("No team for " + team); return false; } ghTeam.setPrivacy(GHTeam.Privacy.CLOSED); String successMsg = "Made GitHub team " + team + " visible"; out.message(successMsg); result = true; } catch (IOException e) { out.message("Failed to make GitHub team " + team + " visible: " + e.getMessage()); e.printStackTrace(); } return result; }

Target:
private boolean makeGitHubTeamVisible(Channel channel, User sender, String team) { boolean result = false; if (!isSenderAuthorized(channel, sender)) { insufficientPermissionError(channel); return false; } OutputChannel out = channel.send(); try { GitHub github = GitHub.connect(); GHOrganization o = github.getOrganization(IrcBotConfig.GITHUB_ORGANIZATION); final GHTeam ghTeam = o.getTeamByName(team); if (ghTeam == null) { out.message("No team for " + team); return false; } ghTeam.setPrivacy(GHTeam.Privacy.CLOSED); out.message("Made GitHub team " + team + " visible"); result = true; } catch (IOException e) { out.message("Failed to make GitHub team " + team + " visible: " + e.getMessage()); e.printStackTrace(); } return result; }
Source:
private <E extends Enum<E>> Class<E> determineEnumClass(ExtensionContext context) { Class enumClass = enumSource.value(); if (enumClass.equals(NullEnum.class)) { Method method = context.getRequiredTestMethod(); Class<?>[] parameterTypes = method.getParameterTypes(); Preconditions.condition(parameterTypes.length > 0, () -> "At least one parameter is required on test method: " + method.toGenericString()); Preconditions.condition(Enum.class.isAssignableFrom(parameterTypes[0]), () -> "First parameter must reference an Enum type (alternatively, use the annotation's 'value' parameter to specify the type explicitly): " + method.toGenericString()); enumClass = parameterTypes[0]; } return enumClass; }

Target:
private <E extends Enum<E>> Class<E> determineEnumClass(ExtensionContext context) { Class enumClass = enumSource.value(); if (enumClass.equals(NullEnum.class)) { Method method = context.getRequiredTestMethod(); Class<?>[] parameterTypes = method.getParameterTypes(); Preconditions.condition(parameterTypes.length > 0, () -> "Test method must declare at least one parameter: " + method.toGenericString()); Preconditions.condition(Enum.class.isAssignableFrom(parameterTypes[0]), () -> "First parameter must reference an Enum type (alternatively, use the annotation's 'value' attribute to specify the type explicitly): " + method.toGenericString()); enumClass = parameterTypes[0]; } return enumClass; }
Source:
public void testDateFormat4ms() { testAssumeColumnDetails_Dates( Arrays.asList( "02/29/20 00:00:00" ), "MM/dd/yy HH:mm:ss" ); }

Target:
public void testDateFormat4ms() { testAssumeColumnDetails_Dates( asList( "11/10/15 11:57:33" ), "MM/dd/yy HH:mm:ss" ); }
Source:
public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } if (observers.contains(observer)) { return this; } observers.add(observer); return this; }

Target:
public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } if (!observers.contains(observer)) { observers.add(observer); } return this; }
Source:
public Navigation(ComponentContainer container) { super(container.$form()); activity = container.$context(); apiKey = ""; startLocation = new GeoPoint(0, 0); endLocation = new GeoPoint(0, 0); method = TransportMethod.DEFAULT; }

Target:
public Navigation(ComponentContainer container) { super(container.$form()); apiKey = ""; startLocation = new GeoPoint(0.0, 0.0); endLocation = new GeoPoint(0.0, 0.0); method = TransportMethod.DEFAULT; }
Source:
public PageBlobAsyncClient asPageBlobAsyncClient() { return new SpecializedBlobClientBuilder() .blobAsyncClient(this) .buildPageBlobAsyncClient(); }

Target:
public PageBlobAsyncClient asPageBlobAsyncClient() { return prepareBuilder().buildPageBlobAsyncClient(); }
Source:
public User setUserActivationKey(User user) { String token = RandomStringUtils.randomAlphanumeric(20); long time = System.currentTimeMillis() + getValidTime(); String hashedKey = Security.encodeString(token); String activationKey = hashedKey+":"+time; LoginCredential credentials = dao.getLoginCredential(user); credentials.setActivationKey(activationKey); dao.setUserActivationKey(credentials); String link = Context.getAdministrationService().getGlobalProperty(OpenmrsConstants.GP_HOST_URL) + token; String msg = "Hi " + user.getUsername() + ", \n It looks like you like to change your password, click on the following link to do so.\n" + link + " please disregard this email if you didn't innitiate the password reset process The openmrs Team"; Message mail = new Message(); mail.setId(20); mail.setRecipients(user.getEmail()); mail.setSender(Context.getAdministrationService().getGlobalProperty("mail.from")); mail.setContentType(Context.getAdministrationService().getGlobalProperty("mail.default_content_type")); mail.setSubject("Password Reset Request"); mail.setContent(msg); mail.setSentDate(new Date()); try { Context.getMessageService().sendMessage(mail); } catch (MessageException e) { } return user; }

Target:
public User setUserActivationKey(User user) throws MessageException { String token = RandomStringUtils.randomAlphanumeric(20); long time = System.currentTimeMillis() + getValidTime(); String hashedKey = Security.encodeString(token); String activationKey = hashedKey + ":" + time; LoginCredential credentials = dao.getLoginCredential(user); credentials.setActivationKey(activationKey); dao.setUserActivationKey(credentials); MessageSourceService messages = Context.getMessageSourceService(); AdministrationService adminService = Context.getAdministrationService(); String link = adminService.getGlobalProperty(OpenmrsConstants.GP_HOST_URL) .replace("{activationKey}", token); String msg = messages.getMessage("mail.passwordreset.content").replace("{name}", user.getUsername()) .replace("{link}", link) .replace("{time}", String.valueOf(getValidTime() / 60000)); Context.getMessageService().sendMessage(user.getEmail(), adminService.getGlobalProperty("mail.from"), messages.getMessage("mail.passwordreset.subject"), msg); return user; }
Source:
public void testNegativeBlockTime() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 20; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); ByteBuffer buffer = pool.allocate(size, 0); pool.deallocate(buffer); try { buffer = pool.allocate(size, -maxBlockTimeInMs); } catch (IllegalArgumentException e) { } pool.deallocate(buffer); assertEquals(size, pool.capacity()); }

Target:
public void testNegativeBlockTime() throws Exception { final int size = 1024; final long capacity = 1024; final long maxBlockTimeInMs = 20; SimpleByteBufferPool pool = new SimpleByteBufferPool(capacity); ByteBuffer buffer = pool.allocate(size, 0); pool.deallocate(buffer); try { pool.allocate(size, -maxBlockTimeInMs); fail("IllegalArgumentException should have been thrown when timeToBlockInMs is negative."); } catch (IllegalArgumentException e) { } try { pool.allocate((int) capacity + 1, maxBlockTimeInMs); fail( "IllegalArgumentException should have been thrown when requested buffer size is larger than the buffer pool's capacity."); } catch (IllegalArgumentException e) { } assertEquals(size, pool.capacity()); }
Source:
public TypedValue<?> apply(TypedValue<?> t) { if (runningExtremes == null) { this.runningExtremes = new RunningExtremes(this.options.getWindowSize()); } final double value = ((Number) t.getValue()).doubleValue(); return TypedValues.newDoubleValue(this.runningExtremes.updateAndGetMax(value)); }

Target:
public TypedValue<?> apply(TypedValue<?> t) { if (runningExtremum == null) { this.runningExtremum = new RunningExtremum<>(this.options.getWindowSize()); } final double value = ((Number) t.getValue()).doubleValue(); this.runningExtremum.add(value); return TypedValues.newDoubleValue(this.runningExtremum.max()); }
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); attr.setDisplayName("Accoun expiration."); attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; }

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_FACILITY_ATTR_DEF); attr.setFriendlyName("accountExpirationTime"); attr.setDisplayName("Account expiration."); attr.setType(Integer.class.getName()); attr.setDescription("Account expiration."); return attr; }
Source:
private Optional<LogFile> createLogFile(Path path) { Optional<LogFileName> logFileName = LogFileName.parseHistoryLogFileName(masterLogFile.getFileName().toString(), path.getFileName().toString()); if (!logFileName.isPresent()) { return Optional.empty(); } BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { return Optional.empty(); } return Optional.of(new LogFile(path, logFileName.get(), fileAttributes.size())); }

Target:
private Optional<LogFile> createLogFile(Path path) { Optional<LogFileName> logFileName = parseHistoryLogFileName(masterLogFile.getFileName().toString(), path.getFileName().toString()); if (!logFileName.isPresent()) { return Optional.empty(); } BasicFileAttributes fileAttributes; try { fileAttributes = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { return Optional.empty(); } return Optional.of(new LogFile(path, logFileName.get(), fileAttributes.size())); }