auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static InternalAggregationFunction generateAggregation(Type valueType, QuantileDigestType outputType, int arity) { DynamicClassLoader classLoader = new DynamicClassLoader(QuantileDigestAggregationFunction.class.getClassLoader()); List<Type> inputTypes = getInputTypes(valueType, arity); QuantileDigestStateSerializer stateSerializer = new QuantileDigestStateSerializer(valueType); Type intermediateType = stateSerializer.getSerializedType(); checkArgument(inputFunctions.containsKey(valueType.getDisplayName()), <START> "Unsupported type %s supplied, known types: %s", valueType.getDisplayName(), inputFunctions.keySet()); <END> AggregationMetadata metadata = new AggregationMetadata( generateAggregationName(NAME, outputType.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())), createInputParameterMetadata(inputTypes), getMethodHandle(valueType, arity), COMBINE_FUNCTION, OUTPUT_FUNCTION.bindTo(stateSerializer), ImmutableList.of(new AccumulatorStateDescriptor( QuantileDigestState.class, stateSerializer, new QuantileDigestStateFactory())), outputType); GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader); return new InternalAggregationFunction(NAME, inputTypes, ImmutableList.of(intermediateType), outputType, true, true, factory); }</code><technical_language>Declare 3 method handles static final fields of this class, switch ... case find here. Do a map. This is code this generally written. careful benchmarks. However, I remember this style is critical performance</technical_language>

Target:
private static InternalAggregationFunction generateAggregation(Type valueType, QuantileDigestType outputType, int arity) { DynamicClassLoader classLoader = new DynamicClassLoader(QuantileDigestAggregationFunction.class.getClassLoader()); List<Type> inputTypes = getInputTypes(valueType, arity); QuantileDigestStateSerializer stateSerializer = new QuantileDigestStateSerializer(valueType); Type intermediateType = stateSerializer.getSerializedType(); AggregationMetadata metadata = new AggregationMetadata( generateAggregationName(NAME, outputType.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())), createInputParameterMetadata(inputTypes), getMethodHandle(valueType, arity), COMBINE_FUNCTION, OUTPUT_FUNCTION.bindTo(stateSerializer), ImmutableList.of(new AccumulatorStateDescriptor( QuantileDigestState.class, stateSerializer, new QuantileDigestStateFactory())), outputType); GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader); return new InternalAggregationFunction(NAME, inputTypes, ImmutableList.of(intermediateType), outputType, true, true, factory); }
Source:
<code>public boolean onPrepareActionMode(ActionMode mode, Menu menu) { if (menu.findItem(16) == null) { <START> menu.add(Menu.NONE, 16, Menu.NONE, "Cloze deletion"); <END> return true; } else { return false; } }</code><technical_language>pre-existing localized string R.string.multimedia_editor_popup_cloze, follow "TODO" a static constant instead of a magic number</technical_language>

Target:
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { if (menu.findItem(mMenuId) == null) { menu.add(Menu.NONE, mMenuId, Menu.NONE, R.string.multimedia_editor_popup_cloze); return true; } else { return false; } }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { final ModelNode deployment = context.readResource(PathAddress.EMPTY_ADDRESS).getModel(); final boolean isEnabled = ENABLED.resolveModelAttribute(context, deployment).asBoolean(); final String runtimeName = RUNTIME_NAME.resolveModelAttribute(context, deployment).asString(); context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) { final ModelNode result = context.getResult(); if (!isEnabled) { result.set(AbstractDeploymentUnitService.DeploymentStatus.STOPPED.toString()); } else { final ServiceController<?> controller = context.getServiceRegistry(false).getService(Services.deploymentUnitName(runtimeName)); if (controller != null) { <START> if (controller.getState() == ServiceController.State.DOWN) { <END> result.set(AbstractDeploymentUnitService.DeploymentStatus.STOPPED.toString()); } else { result.set(((AbstractDeploymentUnitService) controller.getService()).getStatus().toString()); } } else { result.set(NO_METRICS); } } } }, OperationContext.Stage.RUNTIME); }</code><technical_language>I this is equivalent. other variants of WONT_START if true existing code drops a call AbstractDeploymentUnitService.getStatus. checks a StabilityMonitor for failed problems if result is DeploymentStatus.FAILED, DeploymentStatus.STOPPED. In other words, due missing dependencies -> DeploymentStatus.FAILED</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { final ModelNode deployment = context.readResource(PathAddress.EMPTY_ADDRESS).getModel(); final boolean isEnabled = ENABLED.resolveModelAttribute(context, deployment).asBoolean(); final String runtimeName = RUNTIME_NAME.resolveModelAttribute(context, deployment).asString(); context.addStep(new OperationStepHandler() { @Override public void execute(final OperationContext context, final ModelNode operation) { final ModelNode result = context.getResult(); if (!isEnabled) { result.set(AbstractDeploymentUnitService.DeploymentStatus.STOPPED.toString()); } else { final ServiceController<?> controller = context.getServiceRegistry(false).getService(Services.deploymentUnitName(runtimeName)); if (controller != null) { if (controller.getState() == ServiceController.State.DOWN && controller.getUnavailableDependencies().size() == 0) { result.set(AbstractDeploymentUnitService.DeploymentStatus.STOPPED.toString()); } else { result.set(((AbstractDeploymentUnitService) controller.getService()).getStatus().toString()); } } else { result.set(NO_METRICS); } } } }, OperationContext.Stage.RUNTIME); }
Source:
<code>public ValidationResult isAnyDomainInProcess() { List<StoragePoolIsoMap> poolIsoMaps = getStoragePoolIsoMapDao().getAllForStoragePool(storagePool.getId()); for (StoragePoolIsoMap domainIsoMap : poolIsoMaps) { if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, <START> String.format("$status %1$s", StorageDomainStatus.Locked)); <END> } } return ValidationResult.VALID; }</code><technical_language>please put correct status</technical_language>

Target:
public ValidationResult isAnyDomainInProcess() { List<StoragePoolIsoMap> poolIsoMaps = getStoragePoolIsoMapDao().getAllForStoragePool(storagePool.getId()); for (StoragePoolIsoMap domainIsoMap : poolIsoMaps) { if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", domainIsoMap.getStatus())); } } return ValidationResult.VALID; }
Source:
<code>private void removeImage() { RemoveImageParameters removeImageParams = new RemoveImageParameters(getParameters().getImageId()); removeImageParams.setStorageDomainId(getParameters().getSourceDomainId().getValue()); removeImageParams.setEntityId(new ImageStorageDomainMapId(getParameters().getImageId(), getParameters().getSourceDomainId().getValue())); removeImageParams.setParentCommand(VdcActionType.RemoveImage); removeImageParams.setPerformDbOperationsStage(PerformOperationStage.NEVER); <START> VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction( <END> VdcActionType.RemoveImage, removeImageParams, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (returnValue.getSucceeded()) { startPollingAsyncTasks(returnValue.getInternalTaskIdList()); } else { addAuditLogOnRemoveFailue(); } }</code><technical_language>getBackend() instead</technical_language>

Target:
private void removeImage() { RemoveImageParameters removeImageParams = new RemoveImageParameters(getParameters().getImageId()); removeImageParams.setStorageDomainId(getParameters().getSourceDomainId().getValue()); removeImageParams.setEntityId(new ImageStorageDomainMapId(getParameters().getImageId(), getParameters().getSourceDomainId().getValue())); removeImageParams.setParentCommand(VdcActionType.RemoveImage); removeImageParams.setPerformDbOperationsStage(PerformOperationsStage.NEVER); VdcReturnValueBase returnValue = getBackend().runInternalAction( VdcActionType.RemoveImage, removeImageParams, ExecutionHandler.createDefaultContexForTasks(getExecutionContext())); if (returnValue.getSucceeded()) { startPollingAsyncTasks(returnValue.getInternalTaskIdList()); } else { addAuditLogOnRemoveFailue(); } }
Source:
<code>protected List<Class<?>> discoverServices(Class<?> klass) { final List<Class<?>> serviceClasses = new ArrayList<>(); try { final Enumeration<URL> resources = getClassLoader().getResources("META-INF/services/" + klass.getName()); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); try (InputStream input = url.openStream(); InputStreamReader streamReader = new InputStreamReader(input, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader)) { String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { final Class<?> loadedClass = loadClass(line); if (loadedClass != null) { serviceClasses.add(loadedClass); } } else { <START> LOGGER.debug("Line began with a comment. Ignoring"); <END> } } } } } catch (IOException e) { LOGGER.warn("Unable to load META-INF/services/{}", klass.getName(), e); } return serviceClasses; }</code><technical_language>remove debug log message</technical_language>

Target:
protected List<Class<?>> discoverServices(Class<?> klass) { final List<Class<?>> serviceClasses = new ArrayList<>(); try { final Enumeration<URL> resources = getClassLoader().getResources("META-INF/services/" + klass.getName()); while (resources.hasMoreElements()) { final URL url = resources.nextElement(); try (InputStream input = url.openStream(); InputStreamReader streamReader = new InputStreamReader(input, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(streamReader)) { String line; while ((line = reader.readLine()) != null) { if (!line.startsWith("#")) { final Class<?> loadedClass = loadClass(line); if (loadedClass != null) { serviceClasses.add(loadedClass); } } } } } } catch (IOException e) { LOGGER.warn("Unable to load META-INF/services/{}", klass.getName(), e); } return serviceClasses; }
Source:
<code>private Command selectCommand( Project project ) { return () -> { if ( hasAccessToPerspective( PerspectiveIds.AUTHORING ) ) { libraryBreadcrumbs.setupAuthoringBreadCrumbsForProject( project.getProjectName() ); placeManager.goTo( new DefaultPlaceRequest( PerspectiveIds.AUTHORING ) ); libraryContextSwitchEvent .fire( new LibraryContextSwitchEvent( LibraryContextSwitchEvent.EventType.PROJECT_SELECTED, project.getIdentifier() ) ); } else { <START> InfoPopup.generate( ts.getTranslation( LibraryConstants.Error_NoAccessRights ) ); <END> } }; }</code><technical_language>this more correctly handled View</technical_language>

Target:
private Command selectCommand( Project project ) { return () -> { if ( hasAccessToPerspective( PerspectiveIds.AUTHORING ) ) { libraryBreadcrumbs.setupAuthoringBreadCrumbsForProject( project.getProjectName() ); placeManager.goTo( new DefaultPlaceRequest( PerspectiveIds.AUTHORING ) ); libraryContextSwitchEvent .fire( new LibraryContextSwitchEvent( LibraryContextSwitchEvent.EventType.PROJECT_SELECTED, project.getIdentifier() ) ); } else { view.noRightsPopup(); } }; }
Source:
<code>protected void kill() { super.kill(); closeChannel(); IOUtils.closeQuietly(log); try { <START> Util.deleteRecursive(getLogFile().getParentFile()); <END> } catch (IOException ex) { logger.log(Level.WARNING, "Unable to delete slave logs", ex); } }</code><technical_language>defend catastrophes bad future refactorings, I recommend extracting a protected method for computer's log directory, clear deleting is specific this computer only</technical_language>

Target:
protected void kill() { super.kill(); closeChannel(); IOUtils.closeQuietly(log); try { Util.deleteRecursive(getLogDir()); } catch (IOException ex) { logger.log(Level.WARNING, "Unable to delete slave logs", ex); } }
Source:
<code>static <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> sequence3(Iterable<? extends Tuple3<? extends T1, ? extends T2, ? extends T3>> tuples) { Objects.requireNonNull(tuples, "tuples is null"); return new Tuple3<>(Stream.ofAll(tuples).map(Tuple3::_1), Stream.ofAll(tuples).map(Tuple3::_2), <START> Stream.ofAll(tuples).map(Tuple3::_3)); <END> }</code><technical_language>is more I code. Stream is persistent, tuples reused this: java final Stream<Tuple3<T1, T2, T3>> s = Stream.ofAll(tuples); return new Tuple3<>(s.map(Tuple3::_1), s.map(Tuple3::_2), s.map(Tuple3::_3)); please adjust generator accordingly</technical_language>

Target:
static <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> sequence3(Iterable<? extends Tuple3<? extends T1, ? extends T2, ? extends T3>> tuples) { Objects.requireNonNull(tuples, "tuples is null"); final Stream<Tuple3<? extends T1, ? extends T2, ? extends T3>> s = Stream.ofAll(tuples); return new Tuple3<>(s.map(Tuple3::_1), s.map(Tuple3::_2), s.map(Tuple3::_3)); }
Source:
<code>private ActionEventRequest buildCreateEncounterAction(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; String serviceMethod = "createEncounter"; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_DATE, DisplayNames.ENCOUNTER_DATE, DATE, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_TYPE, DisplayNames.ENCOUNTER_TYPE, true, order++)); actionParameters.add(prepareParameter(Keys.LOCATION_NAME, DisplayNames.LOCATION_NAME, false, order++)); actionParameters.add(prepareParameter(Keys.PATIENT_UUID, DisplayNames.PATIENT_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.PROVIDER_UUID, DisplayNames.PROVIDER_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION, DisplayNames.OBSERVATION, MAP, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_ENCOUNTER, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) <START> .setSubject(serviceMethod + "." + configName) <END> .setActionParameters(actionParameters) .createActionEventRequest(); }</code><technical_language>please add method for creating subject</technical_language>

Target:
private ActionEventRequest buildCreateEncounterAction(String configName) { SortedSet<ActionParameterRequest> actionParameters = new TreeSet<>(); int order = 0; String serviceMethod = "createEncounter"; actionParameters.add(prepareParameter(Keys.CONFIG_NAME, DisplayNames.CONFIG_NAME, configName, true, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_DATE, DisplayNames.ENCOUNTER_DATE, DATE, true, order++)); actionParameters.add(prepareParameter(Keys.ENCOUNTER_TYPE, DisplayNames.ENCOUNTER_TYPE, true, order++)); actionParameters.add(prepareParameter(Keys.LOCATION_NAME, DisplayNames.LOCATION_NAME, false, order++)); actionParameters.add(prepareParameter(Keys.PATIENT_UUID, DisplayNames.PATIENT_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.PROVIDER_UUID, DisplayNames.PROVIDER_UUID, true, order++)); actionParameters.add(prepareParameter(Keys.OBSERVATION, DisplayNames.OBSERVATION, MAP, false, order)); return new ActionEventRequestBuilder() .setDisplayName(getDisplayName(CREATE_ENCOUNTER, configName)) .setServiceInterface(OPENMRS_ACTION_PROXY_SERVICE) .setServiceMethod(serviceMethod) .setSubject(getSubject(serviceMethod, configName)) .setActionParameters(actionParameters) .createActionEventRequest(); }
Source:
<code>void logRenamedEntity() { if <START> (getCurrentUser() <END> != null && this instanceof RenamedEntityInfoProvider) { RenamedEntityInfoProvider renameable = (RenamedEntityInfoProvider) this; String oldEntityName = renameable.getEntityOldName(); String newEntityName = renameable.getEntityNewName(); if (!StringUtils.equals(oldEntityName, newEntityName)) { AuditLogable logable = new AuditLogableImpl(); String entityType = renameable.getEntityType(); logable.addCustomValue("EntityType", entityType); logable.addCustomValue("OldEntityName", oldEntityName); logable.addCustomValue("NewEntityName", newEntityName); logable.addCustomValue("UserName", getCurrentUser().getLoginName()); renameable.setEntityId(logable); auditLog(logable, AuditLogType.ENTITY_RENAMED); } } }</code><technical_language>is user ? in addition, if enter this block, miss event log previous entity name. I skip this condition</technical_language>

Target:
void logRenamedEntity() { if (this instanceof RenamedEntityInfoProvider) { RenamedEntityInfoProvider renameable = (RenamedEntityInfoProvider) this; String oldEntityName = renameable.getEntityOldName(); String newEntityName = renameable.getEntityNewName(); if (!StringUtils.equals(oldEntityName, newEntityName)) { AuditLogable logable = new AuditLogableImpl(); String entityType = renameable.getEntityType(); logable.addCustomValue("EntityType", entityType); logable.addCustomValue("OldEntityName", oldEntityName); logable.addCustomValue("NewEntityName", newEntityName); if (getCurrentUser() != null) { logable.addCustomValue("UserName", getCurrentUser().getLoginName()); } renameable.setEntityId(logable); auditLog(logable, getCurrentUser() != null ? AuditLogType.ENTITY_RENAMED : AuditLogType.ENTITY_RENAMED_INTERNALLY); } } }
Source:
<code>private void runStoragePoolUpEvent(final StoragePool storagePool) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { try { if (DbFacade.getInstance().getStorageDomainDao(). getStorageDomains(_storagePoolId, StorageDomainType.Master).stream() <START> .anyMatch(d -> d.getStatus() == StorageDomainStatus.Active || d.getStatus() == StorageDomainStatus.Unknown)) { <END> ResourceManager.getInstance() .getEventListener() .storagePoolUpEvent(storagePool); } } catch (RuntimeException exp) { log.error("Error in StoragePoolUpEvent: {}", exp.getMessage()); log.debug("Exception", exp); } } }); }</code><technical_language>in a method in if condition</technical_language>

Target:
private void runStoragePoolUpEvent(final StoragePool storagePool) { ThreadPoolUtil.execute(new Runnable() { @Override public void run() { try { if (isMasterDomainUp()) { ResourceManager.getInstance() .getEventListener() .storagePoolUpEvent(storagePool); } } catch (RuntimeException exp) { log.error("Error in StoragePoolUpEvent: {}", exp.getMessage()); log.debug("Exception", exp); } } private boolean isMasterDomainUp() { return DbFacade.getInstance().getStorageDomainDao(). getStorageDomains(_storagePoolId, StorageDomainType.Master).stream() .anyMatch(d -> d.getStatus() == StorageDomainStatus.Active || d.getStatus() == StorageDomainStatus.Unknown); } }); }
Source:
<code>public static DataStoreRole getDataStoreRole(Snapshot snapshot, SnapshotDataStoreDao snapshotStoreDao, DataStoreManager dataStoreMgr) { SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Primary); if (snapshotStore == null) { return DataStoreRole.Image; } long storagePoolId = snapshotStore.getDataStoreId(); <START> if (! snapshotStore.getState().equals(ObjectInDataStoreStateMachine.State.Destroyed)){ <END> DataStore dataStore = dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); Map<String, String> mapCapabilities = dataStore.getDriver().getCapabilities(); if (mapCapabilities != null) { String value = mapCapabilities.get(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString()); Boolean supportsStorageSystemSnapshots = new Boolean(value); if (supportsStorageSystemSnapshots) { return DataStoreRole.Primary; } } } return DataStoreRole.Image; }</code><technical_language>@nvazquez this NPE, instead ObjectInDataStoreStateMachine.State.Destroyed.equals(...) explicit != null</technical_language>

Target:
public static DataStoreRole getDataStoreRole(Snapshot snapshot, SnapshotDataStoreDao snapshotStoreDao, DataStoreManager dataStoreMgr) { SnapshotDataStoreVO snapshotStore = snapshotStoreDao.findBySnapshot(snapshot.getId(), DataStoreRole.Primary); if (snapshotStore == null) { return DataStoreRole.Image; } long storagePoolId = snapshotStore.getDataStoreId(); if (snapshotStore.getState() != null && ! snapshotStore.getState().equals(ObjectInDataStoreStateMachine.State.Destroyed)) { DataStore dataStore = dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); Map<String, String> mapCapabilities = dataStore.getDriver().getCapabilities(); if (mapCapabilities != null) { String value = mapCapabilities.get(DataStoreCapabilities.STORAGE_SYSTEM_SNAPSHOT.toString()); Boolean supportsStorageSystemSnapshots = Boolean.valueOf(value); if (supportsStorageSystemSnapshots) { return DataStoreRole.Primary; } } } return DataStoreRole.Image; }
Source:
<code>public void afterCompletion(final MessageContext messageContext, final Exception ex) { LOGGER.debug("In after completion."); <START> if (ex != null && ex instanceof IOException) { <END> LOGGER.warn("An IOException occurred, indicate failure to the circuit breaker."); this.circuitBreaker.markFailure(); } }</code><technical_language>not-null check is redundant, this case is covered instanceof check already</technical_language>

Target:
public void afterCompletion(final MessageContext messageContext, final Exception ex) { LOGGER.debug("In after completion."); if (ex instanceof IOException) { LOGGER.warn("An IOException occurred, indicate failure to the circuit breaker."); this.circuitBreaker.markFailure(); } }
Source:
<code>public static void shutdownModules(ServletContext servletContext) { String realPath = getRealPath(servletContext); String messagesPath = Paths.get(realPath,"WEB-INF").toString(); <START> File folder = new File(messagesPath); <END> File[] files = folder.listFiles(); if (folder.exists() && files != null) { Properties emptyProperties = new Properties(); for (File f : files) { if (f.getName().startsWith("module_messages")) { OpenmrsUtil.storeProperties(emptyProperties, f, ""); } } } for (Module mod : ModuleFactory.getLoadedModules()) { stopModule(mod, servletContext, true); } }</code><technical_language>remove temp variable messagesPath calling toFile() Paths.get()</technical_language>

Target:
public static void shutdownModules(ServletContext servletContext) { String realPath = getRealPath(servletContext); File folder = Paths.get(realPath,"WEB-INF").toFile(); File[] files = folder.listFiles(); if (folder.exists() && files != null) { Properties emptyProperties = new Properties(); for (File f : files) { if (f.getName().startsWith("module_messages")) { OpenmrsUtil.storeProperties(emptyProperties, f, ""); } } } for (Module mod : ModuleFactory.getLoadedModules()) { stopModule(mod, servletContext, true); } }
Source:
<code>public List<Task> findActiveTasksForTriggerSubject(final String subject) { List<Task> list = null; if (isNotBlank(subject)) { List enabledTasks = tasksDataService.executeQuery(new QueryExecution<List<Task>>() { @Override public List<Task> execute(Query query, InstanceSecurityRestriction restriction) { String byTriggerSubject = "trigger.subject == param"; String isTaskActive = "enabled == true"; String isNotUsingTimeWindow = "useTimeWindow != true"; String now = (new Time(LocalTime.now(DateTimeZone.UTC))).toString(); String isAfterStartTime = String.format("startTime < \"%s\"", now); String isBeforeEndTime = String.format("endTime > \"%s\"", now); String isEndTimeNextDay = "endTime < startTime"; String isBetweenStartTimeAndMidnight = String.format("(%s) && (\"24:00\" > \"%s\")", isAfterStartTime, now); String isBetweenMidnightAndEndTime = String.format("(%s) && (\"00:00\" < \"%s\")", isBeforeEndTime, now); String isInTimeWindow = String.format("(%s) || ((%s) && (%s)) || ((%s) && ((%s) || (%s)))", isNotUsingTimeWindow, isAfterStartTime, isBeforeEndTime, isEndTimeNextDay, isBetweenStartTimeAndMidnight, isBetweenMidnightAndEndTime); String filter = String.format("(%s) && (%s) && (%s)", isTaskActive, byTriggerSubject, isInTimeWindow); <START> <END> query.setFilter(filter); query.declareParameters("java.lang.String param"); query.setOrdering("id asc"); return (List) QueryExecutor.execute(query, subject, restriction); } }); if (enabledTasks != null) { checkChannelAvailableInTasks(enabledTasks); list = new ArrayList<>(enabledTasks); CollectionUtils.filter(list, tasksWithRegisteredChannel()); } } return list == null ? new ArrayList<>() : list; }</code><technical_language>get list of task sql parse this list, simplier this raw sql</technical_language>

Target:
public List<Task> findActiveTasksForTriggerSubject(final String subject) { List<Task> list = null; if (isNotBlank(subject)) { List enabledTasks = tasksDataService.executeQuery(new QueryExecution<List<Task>>() { @Override public List<Task> execute(Query query, InstanceSecurityRestriction restriction) { String byTriggerSubject = "trigger.subject == param"; String isTaskActive = "enabled == true"; String filter = String.format("(%s) && (%s)", isTaskActive, byTriggerSubject); query.setFilter(filter); query.declareParameters("java.lang.String param"); query.setOrdering("id asc"); return (List) QueryExecutor.execute(query, subject, restriction); } }); if (enabledTasks != null) { checkChannelAvailableInTasks(enabledTasks); list = checkTimeWindowInTasks(enabledTasks); CollectionUtils.filter(list, tasksWithRegisteredChannel()); } } return list == null ? new ArrayList<>() : list; }
Source:
<code>public void testAllModulesAreReferencedInConfigFile() throws Exception { final Set<String> modulesReferencedInConfig = CheckUtil.getConfigCheckStyleModules(); final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules()); moduleNames.remove("JavadocMetadataScraper"); moduleNames.stream().filter(check -> !modulesReferencedInConfig.contains(check)) <START> .forEach(check -> { <END> final String errorMessage = String.format(Locale.ROOT, "%s is not referenced in checkstyle_checks.xml", check); fail(errorMessage); }); }</code><technical_language>please list of strings internal modules, please place this module in new list</technical_language>

Target:
public void testAllModulesAreReferencedInConfigFile() throws Exception { final Set<String> modulesReferencedInConfig = CheckUtil.getConfigCheckStyleModules(); final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules()); moduleNames.removeAll(INTERNAL_MODULES); moduleNames.stream().filter(check -> !modulesReferencedInConfig.contains(check)) .forEach(check -> { final String errorMessage = String.format(Locale.ROOT, "%s is not referenced in checkstyle_checks.xml", check); fail(errorMessage); }); }
Source:
<code>public PersistentBinaryDeque(final String nonce, final File path, VoltLogger logger, final boolean deleteEmpty) throws IOException { EELibraryLoader.loadExecutionEngineLibrary(true); m_path = path; m_nonce = nonce; m_usageSpecificLog = logger; if (!path.exists() || !path.canRead() || !path.canWrite() || !path.canExecute() || !path.isDirectory()) { throw new IOException(path + " is not usable ( !exists || !readable " + "|| !writable || !executable || !directory)"); } parseFiles(deleteEmpty); Instant now = Instant.now(); Map.Entry<Long, PBDSegment> lastEntry = m_segments.lastEntry(); Instant tsLast = lastEntry == null ? now.minusMillis(1) : lastEntry.getValue().created(); Long writeSegmentIndex = lastEntry == null ? 0L : lastEntry.getKey(); String fname = getSegmentFileName(now, tsLast); PBDSegment writeSegment = newSegment( writeSegmentIndex, now, new VoltFile(m_path, fname)); m_segments.put(writeSegmentIndex, writeSegment); writeSegment.openForWrite(true); writeSegment.setFinal(false); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + writeSegment.file() + " (final: " + writeSegment.isFinal() + "), has been opened for writing"); } <START> <END> m_numObjects = countNumObjects(); assertions(); }</code><technical_language>This code is duplicated in getPreviousTimestamp good a single place file name structure</technical_language>

Target:
public PersistentBinaryDeque(final String nonce, final File path, VoltLogger logger, final boolean deleteEmpty) throws IOException { EELibraryLoader.loadExecutionEngineLibrary(true); m_path = path; m_nonce = nonce; m_usageSpecificLog = logger; if (!path.exists() || !path.canRead() || !path.canWrite() || !path.canExecute() || !path.isDirectory()) { throw new IOException(path + " is not usable ( !exists || !readable " + "|| !writable || !executable || !directory)"); } parseFiles(deleteEmpty); long curId = getNextSegmentId(); Map.Entry<Long, PBDSegment> lastEntry = m_segments.lastEntry(); long prevId = lastEntry == null ? getNextSegmentId() : lastEntry.getValue().segmentId(); Long writeSegmentIndex = lastEntry == null ? 0L : lastEntry.getKey() + 1; String fname = getSegmentFileName(curId, prevId); PBDSegment writeSegment = newSegment( writeSegmentIndex, curId, new VoltFile(m_path, fname)); PBDSegment check = m_segments.put(writeSegmentIndex, writeSegment); if (check != null) { throw new IllegalStateException("Overwriting segment " + writeSegmentIndex); } writeSegment.openForWrite(true); writeSegment.setFinal(false); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + writeSegment.file() + " (final: " + writeSegment.isFinal() + "), has been opened for writing"); } m_numObjects = countNumObjects(); assertions(); }
Source:
<code>public void goto_successors() throws Exception { Label label0 = new Label(); Label label1 = new Label(); BytecodeCFGBuilder.BytecodeCFG cfg = new Instructions() .visitVarInsn(Opcodes.ALOAD, 0) .visitJumpInsn(Opcodes.IFNULL, label0) .visitVarInsn(Opcodes.ALOAD, 0) .visitJumpInsn(Opcodes.IFNULL, label1) .visitVarInsn(Opcodes.ALOAD, 0) .visitVarInsn(Opcodes.ALOAD, 0) .visitJumpInsn(Opcodes.IFEQ, label0) .visitInsn(Opcodes.ICONST_0) .visitJumpInsn(Opcodes.GOTO, label1) .visitLabel(label0) .visitInsn(Opcodes.ICONST_1) .visitLabel(label1) .visitInsn(Opcodes.IRETURN) .cfg(); <START> cfg.blocks.forEach(b -> System.out.println(b.printBlock())); <END> assertThat(cfg.blocks.get(6).successors).containsExactly(cfg.blocks.get(4)); }</code><technical_language>forgetten this System.out do need a print in this test</technical_language>

Target:
public void goto_successors() throws Exception { Label label0 = new Label(); Label label1 = new Label(); BytecodeCFGBuilder.BytecodeCFG cfg = new Instructions() .visitVarInsn(Opcodes.ALOAD, 0) .visitJumpInsn(Opcodes.IFNULL, label0) .visitVarInsn(Opcodes.ALOAD, 0) .visitJumpInsn(Opcodes.IFNULL, label1) .visitVarInsn(Opcodes.ALOAD, 0) .visitVarInsn(Opcodes.ALOAD, 0) .visitJumpInsn(Opcodes.IFEQ, label0) .visitInsn(Opcodes.ICONST_0) .visitJumpInsn(Opcodes.GOTO, label1) .visitLabel(label0) .visitInsn(Opcodes.ICONST_1) .visitLabel(label1) .visitInsn(Opcodes.IRETURN) .cfg(); assertThat(cfg.blocks.get(6).successors).containsExactly(cfg.blocks.get(4)); }
Source:
<code>protected void configure(HttpSecurity http) throws Exception { http .apply(stormpath()).and() <START> .authorizeRequests(); <END> }</code><technical_language>original code demonstrate syntax, paths locked default. I need permit /restricted for this example work properly. I double check a UAT step</technical_language>

Target:
protected void configure(HttpSecurity http) throws Exception { http .apply(stormpath()).and() .authorizeRequests() .antMatchers("/restricted").fullyAuthenticated() .antMatchers("/**").permitAll(); }
Source:
<code>private KafkaAdminClient(AdminClientConfig config, String clientId, Time time, AdminMetadataManager metadataManager, Metrics metrics, KafkaClient client, TimeoutProcessorFactory timeoutProcessorFactory, LogContext logContext) { this.clientId = clientId; this.log = logContext.logger(KafkaAdminClient.class); <START> configureDefaultApiTimeoutMsAndRequestTimeoutMs(config); <END> this.time = time; this.metadataManager = metadataManager; this.metrics = metrics; this.client = client; this.runnable = new AdminClientRunnable(); String threadName = NETWORK_THREAD_PREFIX + " | " + clientId; this.thread = new KafkaThread(threadName, runnable, true); this.timeoutProcessorFactory = (timeoutProcessorFactory == null) ? new TimeoutProcessorFactory() : timeoutProcessorFactory; this.maxRetries = config.getInt(AdminClientConfig.RETRIES_CONFIG); this.retryBackoffMs = config.getLong(AdminClientConfig.RETRY_BACKOFF_MS_CONFIG); config.logUnused(); AppInfoParser.registerAppInfo(JMX_PREFIX, clientId, metrics, time.milliseconds()); log.debug("Kafka admin client initialized"); thread.start(); }</code><technical_language>move this extra initialization logic factories constructor accept new values? allow final</technical_language>

Target:
private KafkaAdminClient(AdminClientConfig config, String clientId, Time time, AdminMetadataManager metadataManager, Metrics metrics, KafkaClient client, TimeoutProcessorFactory timeoutProcessorFactory, LogContext logContext) { this.clientId = clientId; this.log = logContext.logger(KafkaAdminClient.class); this.requestTimeoutMs = config.getInt(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG); this.defaultApiTimeoutMs = configureDefaultApiTimeoutMs(config); this.time = time; this.metadataManager = metadataManager; this.metrics = metrics; this.client = client; this.runnable = new AdminClientRunnable(); String threadName = NETWORK_THREAD_PREFIX + " | " + clientId; this.thread = new KafkaThread(threadName, runnable, true); this.timeoutProcessorFactory = (timeoutProcessorFactory == null) ? new TimeoutProcessorFactory() : timeoutProcessorFactory; this.maxRetries = config.getInt(AdminClientConfig.RETRIES_CONFIG); this.retryBackoffMs = config.getLong(AdminClientConfig.RETRY_BACKOFF_MS_CONFIG); config.logUnused(); AppInfoParser.registerAppInfo(JMX_PREFIX, clientId, metrics, time.milliseconds()); log.debug("Kafka admin client initialized"); thread.start(); }
Source:
<code><START> public void terminate() throws IllegalStateException{ <END> terminate(Integer.MAX_VALUE); }</code><technical_language>need declare unchecked exception</technical_language>

Target:
public void terminate() { terminate(Integer.MAX_VALUE); }
Source:
<code>private Handler<NetSocket> getEchoHandler() { return new Handler<NetSocket>() { public void handle(NetSocket socket) { <START> System.out.println("YAY"); <END> tu.checkThread(); final int numChunks = 100; final int chunkSize = 100; final Buffer received = new Buffer(); final Buffer sent = new Buffer(); socket.dataHandler(new Handler<Buffer>() { public void handle(Buffer buffer) { tu.checkThread(); received.appendBuffer(buffer); if (received.length() == sent.length()) { tu.azzert(TestUtils.buffersEqual(sent, received)); tu.testComplete(); } } }); for (int i = 0; i < numChunks; i++) { Buffer buff = TestUtils.generateRandomBuffer(chunkSize); sent.appendBuffer(buff); socket.write(buff); } } }; }</code><technical_language>Litter! ;)</technical_language>

Target:
private Handler<NetSocket> getEchoHandler() { return new Handler<NetSocket>() { public void handle(NetSocket socket) { tu.checkThread(); final int numChunks = 100; final int chunkSize = 100; final Buffer received = new Buffer(); final Buffer sent = new Buffer(); socket.dataHandler(new Handler<Buffer>() { public void handle(Buffer buffer) { tu.checkThread(); received.appendBuffer(buffer); if (received.length() == sent.length()) { tu.azzert(TestUtils.buffersEqual(sent, received)); tu.testComplete(); } } }); for (int i = 0; i < numChunks; i++) { Buffer buff = TestUtils.generateRandomBuffer(chunkSize); sent.appendBuffer(buff); socket.write(buff); } } }; }
Source:
<code>public PatchSetInfo get(PatchSet.Id patchSetId) throws PatchSetInfoNotAvailableException { ReviewDb db = null; try { db = schemaFactory.open(); final PatchSet patchSet = db.patchSets().get(patchSetId); final Change change = db.changes().get(patchSet.getId().getParentKey()); final Project.NameKey projectKey = change.getDest().getParentKey(); final String projectName = projectKey.get(); <START> final Repository repo = gs.openRepository(projectName); <END> final RevWalk rw = new RevWalk(repo); final RevCommit src = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); return get(src, patchSetId); } catch (OrmException e) { throw new PatchSetInfoNotAvailableException(e); } catch (IOException e) { throw new PatchSetInfoNotAvailableException(e); } finally { if (db != null) db.close(); } }</code><technical_language>repo closed done it</technical_language>

Target:
public PatchSetInfo get(PatchSet.Id patchSetId) throws PatchSetInfoNotAvailableException { ReviewDb db = null; Repository repo = null; try { db = schemaFactory.open(); final PatchSet patchSet = db.patchSets().get(patchSetId); final Change change = db.changes().get(patchSet.getId().getParentKey()); final Project.NameKey projectKey = change.getDest().getParentKey(); final String projectName = projectKey.get(); repo = gs.openRepository(projectName); final RevWalk rw = new RevWalk(repo); final RevCommit src = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); return get(src, patchSetId); } catch (OrmException e) { throw new PatchSetInfoNotAvailableException(e); } catch (IOException e) { throw new PatchSetInfoNotAvailableException(e); } finally { if (db != null) db.close(); if (repo != null) repo.close(); } }
Source:
<code>public void updateColHeaderFilter(Database db, MolgenisRequest t) throws Exception { if (matrix instanceof SliceablePhenoMatrixMV) { List<Integer> measurementIds = new ArrayList<Integer>(); List<String> list = (List<String>) t.getList(MEASUREMENTCHOOSER); for (String s : list) { measurementIds.add(Integer.parseInt(s)); } resetColumns(measurementIds); } else { List<?> chosenMeasurementIds; if (t.getList(MEASUREMENTCHOOSER) != null) { chosenMeasurementIds = t.getList(MEASUREMENTCHOOSER); } else { chosenMeasurementIds = new ArrayList<Object>(); } List<String> chosenMeasurementNames = new ArrayList<String>(); for (Object measurementId : chosenMeasurementIds) { <START> System.out.println("__objmeasid: " + measurementId + "\n"); <END> int measId = Integer.parseInt((String) measurementId); chosenMeasurementNames.add(db.findById(Measurement.class, measId).getName()); } setColHeaderFilter(chosenMeasurementNames); } }</code><technical_language>Please remove print statement replace logger.debug</technical_language>

Target:
public void updateColHeaderFilter(Database db, MolgenisRequest t) throws Exception { if (matrix instanceof SliceablePhenoMatrixMV) { List<Integer> measurementIds = new ArrayList<Integer>(); List<String> list = (List<String>) t.getList(MEASUREMENTCHOOSER); for (String s : list) { measurementIds.add(Integer.parseInt(s)); } resetColumns(measurementIds); } else { List<?> chosenMeasurementIds; if (t.getList(MEASUREMENTCHOOSER) != null) { chosenMeasurementIds = t.getList(MEASUREMENTCHOOSER); } else { chosenMeasurementIds = new ArrayList<Object>(); } List<String> chosenMeasurementNames = new ArrayList<String>(); for (Object measurementId : chosenMeasurementIds) { int measId = Integer.parseInt((String) measurementId); chosenMeasurementNames.add(db.findById(Measurement.class, measId).getName()); } setColHeaderFilter(chosenMeasurementNames); } }
Source:
<code>private II providedPatientId(PRPAIN201305UV02 request) { II patId = null; String aaId; if (request != null && request.getControlActProcess() != null) { aaId = extractAAOID(request); <START> if (NullChecker.isNotNullish(aaId) && request.getControlActProcess().getQueryByParameter() != null <END> && request.getControlActProcess().getQueryByParameter().getValue() != null && request.getControlActProcess().getQueryByParameter().getValue().getParameterList() != null && NullChecker.isNotNullish(request.getControlActProcess().getQueryByParameter().getValue() .getParameterList().getLivingSubjectId())) { for (PRPAMT201306UV02LivingSubjectId livingSubId : request.getControlActProcess() .getQueryByParameter().getValue().getParameterList().getLivingSubjectId()) { for (II id : livingSubId.getValue()) { if (id != null && NullChecker.isNotNullish(id.getRoot()) && NullChecker.isNotNullish(id.getExtension()) && aaId.contentEquals(id.getRoot())) { patId = new II(); patId.setRoot(id.getRoot()); patId.setExtension(id.getExtension()); break; } } if (patId != null) { break; } } } } return patId; }</code><technical_language>introduce long null check instead of calling requestHasLivingId(request)? reasons</technical_language>

Target:
private II providedPatientId(PRPAIN201305UV02 request) { II patId = null; String aaId; if (request != null && request.getControlActProcess() != null) { aaId = extractAAOID(request); if (NullChecker.isNotNullish(aaId) && requestHasLivingId(request)) { for (PRPAMT201306UV02LivingSubjectId livingSubId : request.getControlActProcess() .getQueryByParameter().getValue().getParameterList().getLivingSubjectId()) { for (II id : livingSubId.getValue()) { if (id != null && NullChecker.isNotNullish(id.getRoot()) && NullChecker.isNotNullish(id.getExtension()) && aaId.contentEquals(id.getRoot())) { patId = new II(); patId.setRoot(id.getRoot()); patId.setExtension(id.getExtension()); break; } } if (patId != null) { break; } } } } return patId; }
Source:
<code>@Test public void defaultEntrypoint() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { DockerTestUtil.assumeDocker(); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " withDockerContainer('ubuntu') {\n" + " sh 'cat /proc/1/cmdline'\n" + " }\n" + "}", true)); WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0)); <START> story.j.assertLogContains("cat", b); <END> } }); }</code><technical_language>is this proving? If groovy sh 'cat /any/file/at/all' log + cat /any/file/at/all</technical_language>

Target:
@Test public void defaultEntrypoint() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { DockerTestUtil.assumeDocker(); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " withDockerContainer('ubuntu') {\n" + " sh 'grep cat /proc/1/cmdline'\n" + " }\n" + "}", true)); WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0)); } }); }
Source:
<code>public void explain(OperationContext ctx, CRUDFindRequest req) { initialize(ctx,req); ExecutionContext executionContext = new ExecutionContext(ctx,null); JsonDoc doc=new JsonDoc(executionPlan.explain(executionContext)); ArrayList<DocCtx> l=new ArrayList<>(1); l.add(new DocCtx(doc)); <START> ctx.setDocumentStream(new ListDocumentStream<DocCtx>(l)); <END> }</code><technical_language>Arrays.asList(doc)</technical_language>

Target:
public void explain(OperationContext ctx, CRUDFindRequest req) { initialize(ctx,req); ExecutionContext executionContext = new ExecutionContext(ctx,null); JsonDoc doc=new JsonDoc(executionPlan.explain(executionContext)); ctx.setDocumentStream(new ListDocumentStream<DocCtx>(Arrays.asList(new DocCtx(doc)))); }
Source:
<code>@Override public boolean isApplicableToSCM(@Nonnull Class<? extends SCM> scmClass) { return super.isApplicableToSCM(scmClass) && MercurialSCM.class.isAssignableFrom(scmClass); <START> } <END></code><technical_language>if installations set useCaches MercurialSCMSource all. this method is called, returning true</technical_language>

Target:
@Override public boolean isApplicableToSCM(@Nonnull Class<? extends SCM> scmClass) { if (super.isApplicableToSCM(scmClass)) { for (MercurialInstallation i : MercurialInstallation.allInstallations()) { if (i.isUseCaches()) { return true; } } } return false; }
Source:
<code>public void aggregate(Object item) { if (item instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) item; <START> if (objectNode.hasNonNull("count")) { <END> long count = objectNode.get("count").asLong(); if (count == 0) { return; } if (objectNode.has("min")) { item = MaxAggregator.getValue(objectNode.get("min")); } else { item = Undefined.value(); } } } if (item == Undefined.value()) { return; } if (Undefined.value().equals(this.value)) { this.value = item; } else if (ItemComparator.getInstance().compare(item, this.value) < 0) { this.value = item; } }</code><technical_language>constants</technical_language>

Target:
public void aggregate(Object item) { if (item instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) item; if (objectNode.hasNonNull(COUNT_PROPERTY_NAME)) { long count = objectNode.get(COUNT_PROPERTY_NAME).asLong(); if (count == 0) { return; } if (objectNode.has(MIN_PROPERTY_NAME)) { item = MaxAggregator.getValue(objectNode.get(MIN_PROPERTY_NAME)); } else { item = Undefined.value(); } } } if (item == Undefined.value()) { return; } if (Undefined.value().equals(this.value)) { this.value = item; } else if (ItemComparator.getInstance().compare(item, this.value) < 0) { this.value = item; } }
Source:
<code>public Job getJobContent(JobId jobId) throws NotConnectedException, PermissionException, UnknownJobException, JobCreationException, SubmissionClosedException { File tempFile = null; try { final InputStream jobContent = restApi().getJobContent(sid, jobId.value()); tempFile = File.createTempFile("jobContent", jobId.value()); <START> FileUtils.copyInputStreamToFile(jobContent, tempFile); <END> final Job job = JobFactory.getFactory().createJob(tempFile.getPath()); return job; } catch (NotConnectedRestException e) { throw new NotConnectedException(e); } catch (UnknownJobRestException e) { throw new UnknownJobException(e); } catch (PermissionRestException e) { throw new PermissionException(e); } catch (SubmissionClosedRestException e) { throw new SubmissionClosedException(e); } catch (JobCreationRestException e) { throw new JobCreationException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if (tempFile != null) { tempFile.delete(); } } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Define throw a dedicated exception instead of a generic one. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Job getJobContent(JobId jobId) throws NotConnectedException, PermissionException, UnknownJobException, JobCreationException, SubmissionClosedException { File tempFile = null; try { final InputStream jobContent = restApi().getJobContent(sid, jobId.value()); tempFile = File.createTempFile("jobContent", jobId.value()); FileUtils.copyInputStreamToFile(jobContent, tempFile); return JobFactory.getFactory().createJob(tempFile.getPath()); } catch (NotConnectedRestException e) { throw new NotConnectedException(e); } catch (UnknownJobRestException e) { throw new UnknownJobException(e); } catch (PermissionRestException e) { throw new PermissionException(e); } catch (SubmissionClosedRestException e) { throw new SubmissionClosedException(e); } catch (JobCreationRestException e) { throw new JobCreationException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if (tempFile != null) { try { Files.delete(tempFile.toPath()); } catch (IOException e) { logger.error("Cannot delete file: " + e); } } } }
Source:
<code>public void setDurability(int durability) { <START> if (durability >= 0) { <END> this.durability = durability; } else { throw new IllegalArgumentException("Invalid value for durability"); } }</code><technical_language>replace checkArgument(durability >= 0, "Durability zero!");</technical_language>

Target:
public void setDurability(int durability) { checkArgument(durability >= 0, "Durability cannot be less than zero!"); this.durability = durability; }