auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CollectionDetail get(HttpServletRequest request, HttpServletResponse response) throws IOException, ZebedeeException { com.github.onsdigital.zebedee.model.Collection collection = Collections .getCollection(request); if (collection == null) { response.setStatus(HttpStatus.NOT_FOUND_404); return null; } Session session = zebedeeCmsService.getSession(request); if (!zebedeeCmsService.getPermissions().canView(session.getEmail(), collection.getDescription())) { response.setStatus(HttpStatus.UNAUTHORIZED_401); return null; } CollectionDetail result = new CollectionDetail(); result.setId(collection.getDescription().getId()); result.setName(collection.getDescription().getName()); result.setType(collection.getDescription().getType()); result.setPublishDate(collection.getDescription().getPublishDate()); result.setReleaseUri(collection.getDescription().getReleaseUri()); result.approvalStatus = collection.getDescription().approvalStatus; return result; }

Target:
public CollectionDetail get(HttpServletRequest request, HttpServletResponse response) throws IOException, ZebedeeException { Collection collection = zebedeeCmsService.getCollection(request); if (collection == null) { throw new CollectionNotFoundException("collection not found"); } Session session = zebedeeCmsService.getSession(request); if (session == null || !zebedeeCmsService.getPermissions().canView(session.getEmail(), collection.getDescription())) { throw new UnauthorizedException("unauthorised call to get publishing queue collection details"); } CollectionDetail result = new CollectionDetail(); result.setId(collection.getDescription().getId()); result.setName(collection.getDescription().getName()); result.setType(collection.getDescription().getType()); result.setPublishDate(collection.getDescription().getPublishDate()); result.setReleaseUri(collection.getDescription().getReleaseUri()); result.approvalStatus = collection.getDescription().approvalStatus; return result; }
Source:
public void asNormal() { Flowable<Object> flow = normal.completable.as(new CompletableConverter<Flowable<Object>>() { @Override public Flowable<Object> apply(Completable c) { return c.toFlowable(); } }); flow.blockingForEach(new Consumer<Object>() { @Override public void accept(Object e) { } }); }

Target:
public void asNormal() { normal.completable .as(new CompletableConverter<Flowable<Object>>() { @Override public Flowable<Object> apply(Completable c) { return c.toFlowable(); } }) .test() .assertComplete() .assertNoValues(); }
Source:
public String getTimeZone() { String tz = timeZoneComboBox.getSelectedItem().toString(); return tz.substring(tz.indexOf(")") + 2).trim(); }

Target:
String getTimeZone() { String tz = timeZoneComboBox.getSelectedItem().toString(); return tz.substring(tz.indexOf(")") + 2).trim(); }
Source:
public CachingInputStream open(FileSystem fileSystem, Path path, Optional<byte[]> extraFileInfo) throws IOException { checkArgument(fileSystem instanceof CachingFileSystem, "fileSystem should be of CachingFileSystem type."); CachingFileSystem cachingFileSystem = (CachingFileSystem) fileSystem; FSDataInputStream fsDataInputStream = fileOpener.open(cachingFileSystem.getDataTier(), path, extraFileInfo); return new CachingInputStream(fsDataInputStream, cacheManager, path, cachingFileSystem.isCacheValidationEnabled()); }

Target:
public CachingInputStream open(FileSystem fileSystem, Path path, Optional<byte[]> extraFileInfo) throws IOException { checkArgument(fileSystem instanceof CachingFileSystem, "fileSystem should be of CachingFileSystem type"); CachingFileSystem cachingFileSystem = (CachingFileSystem) fileSystem; FSDataInputStream inputStream = fileOpener.open(cachingFileSystem.getDataTier(), path, extraFileInfo); return new CachingInputStream(inputStream, cacheManager, path, cachingFileSystem.isCacheValidationEnabled()); }
Source:
protected File getEmptyJarDestinationFolder() throws IOException { File destinationFolder = new File("/tmp/expandedJar"); if (destinationFolder.exists()) { FileUtils.cleanDirectory(destinationFolder); } else { destinationFolder.mkdirs(); } return destinationFolder; }

Target:
protected File getEmptyJarDestinationFolder() throws IOException { File destinationFolder = new File(System.getProperty("java.io.tmpdir"), "expandedJar"); if (destinationFolder.exists()) { FileUtils.cleanDirectory(destinationFolder); } else { destinationFolder.mkdirs(); } return destinationFolder; }
Source:
public boolean contains(String entityName, Object object) { checkTransactionSynchStatus(); if ( object == null ) { return false; } try { if ( !HibernateProxy.class.isInstance( object ) && persistenceContext.getEntry( object ) == null ) { try { getSessionFactory().getMetamodel().entityPersister( entityName ); } catch (HibernateException e) { throw new IllegalArgumentException( "Not an entity [" + entityName + "] : " + object ); } } if ( object instanceof HibernateProxy ) { checkOpen(); LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); if ( li.isUninitialized() ) { return li.getSession() == this; } else { object = li.getImplementation(); } } EntityEntry entry = persistenceContext.getEntry( object ); delayedAfterCompletion(); return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE; } catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } catch (RuntimeException e) { throw exceptionConverter.convert( e ); } }

Target:
public boolean contains(String entityName, Object object) { checkOpenOrWaitingForAutoClose(); checkTransactionSynchStatus(); if ( object == null ) { return false; } try { if ( !HibernateProxy.class.isInstance( object ) && persistenceContext.getEntry( object ) == null ) { try { getSessionFactory().getMetamodel().entityPersister( entityName ); } catch (HibernateException e) { throw new IllegalArgumentException( "Not an entity [" + entityName + "] : " + object ); } } if ( object instanceof HibernateProxy ) { LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); if ( li.isUninitialized() ) { return li.getSession() == this; } else { object = li.getImplementation(); } } EntityEntry entry = persistenceContext.getEntry( object ); delayedAfterCompletion(); return entry != null && entry.getStatus() != Status.DELETED && entry.getStatus() != Status.GONE; } catch (MappingException e) { throw new IllegalArgumentException( e.getMessage(), e ); } catch (RuntimeException e) { throw exceptionConverter.convert( e ); } }
Source:
public static CommandLineBuilder commandLineBuilder( PathFragment windowsSandboxPath, List<String> commandArguments) { return new CommandLineBuilder() .setWindowsSandboxPath(windowsSandboxPath) .setCommandArguments(commandArguments); }

Target:
public static CommandLineBuilder commandLineBuilder( PathFragment windowsSandboxPath, List<String> commandArguments) { return new CommandLineBuilder(windowsSandboxPath, commandArguments); }
Source:
public void testNullBucket() { Session session = getSession(); QueryRunner queryRunner = getQueryRunner(); queryRunner.execute("CREATE TABLE table_with_null_buckets WITH (bucket_count=2, bucketed_by = ARRAY['key']) AS " + "SELECT 10 x, CAST(NULL AS INTEGER) AS key UNION ALL SELECT 20 x, 1 key"); try { assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL", "SELECT 1"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key IS NULL", "SELECT 10"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE x = 10", "SELECT NULL"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key = 1", "SELECT 20"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE key IS NULL AND x = 10", "SELECT NULL"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL AND x = 1", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key = 10", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IN (NULL,1)", "SELECT 1"); } finally { queryRunner.execute("DROP TABLE table_with_null_buckets"); } }

Target:
public void testNullBucket() { Session session = getSession(); QueryRunner queryRunner = getQueryRunner(); queryRunner.execute("CREATE TABLE table_with_null_buckets WITH (bucket_count=2, bucketed_by = ARRAY['key']) AS " + "SELECT 10 x, CAST(NULL AS INTEGER) AS key UNION ALL SELECT 20 x, 1 key"); try { assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL", "SELECT 1"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key IS NULL", "SELECT 10"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE x = 10", "SELECT NULL"); assertQuery(session, "SELECT x FROM table_with_null_buckets WHERE key = 1", "SELECT 20"); assertQuery(session, "SELECT key FROM table_with_null_buckets WHERE key IS NULL AND x = 10", "SELECT NULL"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL AND x = 1", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key = 10", "SELECT 0"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IN (NULL, 1)", "SELECT 1"); assertQuery(session, "SELECT COUNT() FROM table_with_null_buckets WHERE key IS NULL OR key = 1", "SELECT 2"); } finally { queryRunner.execute("DROP TABLE table_with_null_buckets"); } }
Source:
public BlockState getStateForPlacement(BlockItemUseContext context) { BlockState state = this.getDefaultState(); if(state.has(BlockStateProperties.WATERLOGGED) &&context.getWorld().getFluidState(context.getPos()).getFluid()==Fluids.WATER) { state = state.with(BlockStateProperties.WATERLOGGED, true); } return state; }

Target:
public BlockState getStateForPlacement(BlockItemUseContext context) { BlockState state = this.getDefaultState(); if(state.has(BlockStateProperties.WATERLOGGED) &&context.getWorld().getFluidState(context.getPos()).getFluid()==Fluids.WATER) state = state.with(BlockStateProperties.WATERLOGGED, true); return state; }
Source:
default void inputDetail() { or(mandatory(cluster().id()), mandatory(cluster().name())); optional(clone()); optional(exclusive()); optional(template().name()); optional(configuration()); }

Target:
default void inputDetail() { or(mandatory(cluster().id()), mandatory(cluster().name())); optional(clone()); optional(exclusive()); optional(template().name()); or(optional(storageDomain().id()), optional(storageDomain().name())); optional(vm().diskAttachments()[COLLECTION].id()); }
Source:
public synchronized void saveManagementLayout(Layout layout) { if (layout == null) { log.warn("saveManagementLayout: Attempted to update with null layout"); return; } Layout currentLayout = getManagementLayout(); if (currentLayout == null || layout.getEpoch() > currentLayout.getEpoch()) { dataStore.put(Layout.class, PREFIX_MANAGEMENT, MANAGEMENT_LAYOUT, layout); log.info("saveManagementLayout: Updated to new layout at epoch {}", getManagementLayout().getEpoch()); } else if (layout.getEpoch() < currentLayout.getEpoch()){ log.debug("saveManagementLayout: " + "Ignoring layout because new epoch < old epoch {}", layout.getEpoch(), currentLayout.getEpoch()); } else { log.trace("saveManagementLayout: " + "Ignoring layout because new epoch equal to old epoch {}", layout.getEpoch(), currentLayout.getEpoch()); } }

Target:
public synchronized void saveManagementLayout(Layout layout) { if (layout == null) { log.warn("saveManagementLayout: Attempted to update with null layout"); return; } Layout currentLayout = getManagementLayout(); if (currentLayout == null || layout.getEpoch() > currentLayout.getEpoch()) { dataStore.put(Layout.class, PREFIX_MANAGEMENT, MANAGEMENT_LAYOUT, layout); log.info("saveManagementLayout: Updated to new layout at epoch {}", getManagementLayout().getEpoch()); } else { log.trace("saveManagementLayout: " + "Ignoring layout because new epoch <= old epoch {}", layout.getEpoch(), currentLayout.getEpoch()); } }
Source:
private void handleOffsetOutOfRange(FetchPosition fetchPosition, TopicPartition topicPartition, String reason) { if (subscriptions.hasDefaultOffsetResetPolicy()) { log.info("Fetch offset epoch is out of range for partition {}, resetting offset", fetchPosition, topicPartition); subscriptions.requestOffsetReset(topicPartition); } else { Map<TopicPartition, Long> offsetOutOfRangePartitions = Collections.singletonMap(topicPartition, fetchPosition.offset); String errorMessage = String.format("Offsets out of range " + "with no configured reset policy for partitions: %s" + ", for fetch offset: %d, " + "root cause: %s", offsetOutOfRangePartitions, fetchPosition.offset, reason); log.error(errorMessage); throw new OffsetOutOfRangeException(errorMessage, offsetOutOfRangePartitions); } }

Target:
private void handleOffsetOutOfRange(FetchPosition fetchPosition, TopicPartition topicPartition, String reason) { if (subscriptions.hasDefaultOffsetResetPolicy()) { log.info("Fetch offset epoch is out of range for partition {}, resetting offset", fetchPosition, topicPartition); subscriptions.requestOffsetReset(topicPartition); } else { Map<TopicPartition, Long> offsetOutOfRangePartitions = Collections.singletonMap(topicPartition, fetchPosition.offset); String errorMessage = String.format("Offsets out of range " + "with no configured reset policy for partitions: %s" + ", for fetch offset: %d, " + "root cause: %s", offsetOutOfRangePartitions, fetchPosition.offset, reason); log.info(errorMessage); throw new OffsetOutOfRangeException(errorMessage, offsetOutOfRangePartitions); } }
Source:
protected synchronized long doPersist(final PreparedStatement ps, final MappedEntity me, final boolean useAutoInc, final int lastBindPosition) throws Exception { ps.execute(); if (useAutoInc) { for (final DbColumn column : me.getEntity().getColumns()) { if ((column.isAutoInc())) { try (final ResultSet generatedKeys = ps.getGeneratedKeys()) { if (generatedKeys.next()) { return generatedKeys.getLong(column.getName()); } } } } } return 0; }

Target:
protected synchronized long doPersist(final PreparedStatement ps, final MappedEntity me, final boolean useAutoInc, final int lastBindPosition) throws Exception { ps.execute(); final String autoIncColumnName = me.getAutoIncColumn(); if (useAutoInc && autoIncColumnName != null) { try (final ResultSet generatedKeys = ps.getGeneratedKeys()) { if (generatedKeys.next()) { return generatedKeys.getLong(autoIncColumnName); } } } return 0; }
Source:
public void testCounter() throws Exception { BoundedExecutor boundedExecutor = new BoundedExecutor(executorService, 1); int stageTasks = 100_000; int totalTasks = stageTasks * 2; AtomicInteger counter = new AtomicInteger(); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch completeLatch = new CountDownLatch(totalTasks); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { Uninterruptibles.awaitUninterruptibly(startLatch); int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } startLatch.countDown(); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } Uninterruptibles.awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES); Assert.assertEquals(counter.get(), totalTasks); }

Target:
public void testCounter() throws Exception { int maxThreads = 1; BoundedExecutor boundedExecutor = new BoundedExecutor(executorService, maxThreads); int stageTasks = 100_000; int totalTasks = stageTasks * 2; AtomicInteger counter = new AtomicInteger(); CountDownLatch initializeLatch = new CountDownLatch(maxThreads); CountDownLatch startLatch = new CountDownLatch(1); CountDownLatch completeLatch = new CountDownLatch(totalTasks); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { initializeLatch.countDown(); Uninterruptibles.awaitUninterruptibly(startLatch); int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } Uninterruptibles.awaitUninterruptibly(initializeLatch, 1, TimeUnit.MINUTES); startLatch.countDown(); for (int i = 0; i < stageTasks; i++) { boundedExecutor.execute(() -> { try { int initialCount = counter.get(); counter.set(initialCount + 1); } finally { completeLatch.countDown(); } }); } Uninterruptibles.awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES); Assert.assertEquals(counter.get(), totalTasks); }
Source:
public int updateOwnership(final String dataType, final int blockId, final int storeId) { try { routerLock.writeLock().lock(); final int oldOwnerId = router.updateOwnership(blockId, storeId); return oldOwnerId; } finally { routerLock.writeLock().unlock(); } }

Target:
public int updateOwnership(final String dataType, final int blockId, final int storeId) { routerLock.writeLock().lock(); try { final int oldOwnerId = router.updateOwnership(blockId, storeId); return oldOwnerId; } finally { routerLock.writeLock().unlock(); } }
Source:
public void process(CommandLine cl, @SuppressWarnings("rawtypes") Map stormConf) throws Exception { String appName = cl.getOptionValue("appname", "Storm-on-Yarn"); String queue = cl.getOptionValue("queue", "default"); String storm_zip_location = cl.getOptionValue("stormZip"); Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB); StormOnYarn storm = null; try { storm = StormOnYarn.launchApplication(appName, queue, amSize, stormConf, storm_zip_location); LOG.debug("Submitted application's ID:" + storm.getAppId()); String storm_yaml_output = cl.getOptionValue("stormConfOutput"); if (storm_yaml_output!=null && storm_yaml_output.length()>0) { StormMaster.Client client = storm.getClient(); if (client != null) StormMasterCommand.downloadStormYaml(client, storm_yaml_output); else LOG.warn("No storm.yaml is downaloaded"); } String output = cl.getOptionValue("output"); if (output == null) System.out.println(storm.getAppId()); else { PrintStream os = new PrintStream(output); os.println(storm.getAppId()); os.flush(); os.close(); } } finally { if (storm != null) { storm.stop(); } } }

Target:
public void process(CommandLine cl, @SuppressWarnings("rawtypes") Map stormConf) throws Exception { String appName = cl.getOptionValue("appname", "Storm-on-Yarn"); String queue = cl.getOptionValue("queue", "default"); String storm_zip_location = cl.getOptionValue("stormZip"); Integer amSize = (Integer) stormConf.get(Config.MASTER_SIZE_MB); StormOnYarn storm = null; try { storm = StormOnYarn.launchApplication(appName, queue, amSize, stormConf, storm_zip_location); LOG.debug("Submitted application's ID:" + storm.getAppId()); String storm_yaml_output = cl.getOptionValue("stormConfOutput"); if (storm_yaml_output!=null && storm_yaml_output.length()>0) { StormMaster.Client client = storm.getClient(); if (client != null) StormMasterCommand.downloadStormYaml(client, storm_yaml_output); else LOG.warn("No storm.yaml is downloaded"); } String output = cl.getOptionValue("output"); if (output == null) System.out.println(storm.getAppId()); else { PrintStream os = new PrintStream(output); os.println(storm.getAppId()); os.flush(); os.close(); } } finally { if (storm != null) { storm.stop(); } } }
Source:
private <T extends WrappedModule<?, ?>> @Nullable String setModuleHandlers(String rUID, List<T> modules) { StringBuffer sb = null; for (T mm : modules) { final Module m = mm.unwrap(); try { ModuleHandler moduleHandler = getModuleHandler(m, rUID); if (moduleHandler != null) { if (mm instanceof WrappedAction) { ((WrappedAction) mm).setModuleHandler((ActionHandler) moduleHandler); } else if (mm instanceof WrappedCondition) { ((WrappedCondition) mm).setModuleHandler((ConditionHandler) moduleHandler); } else if (mm instanceof WrappedTrigger) { ((WrappedTrigger) mm).setModuleHandler((TriggerHandler) moduleHandler); } } else { if (sb == null) { sb = new StringBuffer(); } String message = "Missing handler '" + m.getTypeUID() + "' for module '" + m.getId() + "'"; sb.append(message).append("\n"); logger.trace(message); } } catch (Throwable t) { if (sb == null) { sb = new StringBuffer(); } String message = "Getting handler '" + m.getTypeUID() + "' for module '" + m.getId() + "' failed: " + t.getMessage(); sb.append(message).append("\n"); logger.trace(message); } } return sb != null ? sb.toString() : null; }

Target:
private <T extends WrappedModule<?, ?>> @Nullable String setModuleHandlers(String rUID, List<T> modules) { StringBuilder sb = null; for (T mm : modules) { final Module m = mm.unwrap(); try { ModuleHandler moduleHandler = getModuleHandler(m, rUID); if (moduleHandler != null) { if (mm instanceof WrappedAction) { ((WrappedAction) mm).setModuleHandler((ActionHandler) moduleHandler); } else if (mm instanceof WrappedCondition) { ((WrappedCondition) mm).setModuleHandler((ConditionHandler) moduleHandler); } else if (mm instanceof WrappedTrigger) { ((WrappedTrigger) mm).setModuleHandler((TriggerHandler) moduleHandler); } } else { if (sb == null) { sb = new StringBuilder(); } String message = "Missing handler '" + m.getTypeUID() + "' for module '" + m.getId() + "'"; sb.append(message).append("\n"); logger.trace(message); } } catch (Throwable t) { if (sb == null) { sb = new StringBuilder(); } String message = "Getting handler '" + m.getTypeUID() + "' for module '" + m.getId() + "' failed: " + t.getMessage(); sb.append(message).append("\n"); logger.trace(message); } } return sb != null ? sb.toString() : null; }
Source:
public void setSelected(final String modelName) { for (int i = 0; i < listBox.getItemCount(); i++) { if (listBox.getItemText(i).equals(modelName)) { listBox.setSelectedIndex(i); return; } } }

Target:
public void setSelected(final String modelName) { for (int i = 0; i < listBox.getItemCount(); i++) { if (Objects.equals(listBox.getItemText(i), modelName)) { listBox.setSelectedIndex(i); return; } } }
Source:
public void registerUserNotUsernamePasswordPolicy() { adminClient.realm("test").update(RealmBuilder.create() .passwordPolicy(NotUsernamePasswordPolicyProviderFactory.ID).build()); loginPage.open(); assertTrue(loginPage.isCurrent()); loginPage.clickRegister(); registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Invalid password: must not be equal to the username.", registerPage.getError()); adminClient.realm("test").users().create(UserBuilder.create().username("registerUserNotUsername").build()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Username already exists.", registerPage.getError()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", null, "password", "password"); assertTrue(registerPage.isCurrent()); assertEquals("Please specify username.", registerPage.getError()); }

Target:
public void registerUserNotUsernamePasswordPolicy() { adminClient.realm("test").update(RealmBuilder.create().passwordPolicy("notUsername").build()); loginPage.open(); assertTrue(loginPage.isCurrent()); loginPage.clickRegister(); registerPage.assertCurrent(); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Invalid password: must not be equal to the username.", registerPage.getError()); adminClient.realm("test").users().create(UserBuilder.create().username("registerUserNotUsername").build()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", "registerUserNotUsername", "registerUserNotUsername", "registerUserNotUsername"); assertTrue(registerPage.isCurrent()); assertEquals("Username already exists.", registerPage.getError()); registerPage.register("firstName", "lastName", "registerUserNotUsername@email", null, "password", "password"); assertTrue(registerPage.isCurrent()); assertEquals("Please specify username.", registerPage.getError()); }
Source:
public void run() { try { WatchService watchService = KeyStoreWatcher.this.watchService; while (watchService != null) { WatchKey key = watchService.take(); Path watchedPath = (Path) key.watchable(); Map<String, List<Store>> pathRegistration = watchedPaths.get(watchedPath); Set<Store> toNotify = new HashSet<Store>(); if (pathRegistration != null) { for (WatchEvent<?> event : key.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { Path context = (Path) event.context(); String name = context.getFileName().toString(); System.out.println("File Name " + name); List<Store> stores = pathRegistration.get(name); if (stores != null) { for (Store current : stores) { toNotify.add(current); } } } else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind())) { for (List<Store> stores : pathRegistration.values()) { for (Store current : stores) { toNotify.add(current); } } } } } key.reset(); for (Store current : toNotify) { current.modified(); } } } catch (ClosedWatchServiceException | InterruptedException e) { } }

Target:
public void run() { try { WatchService watchService = null; while ((watchService = KeyStoreWatcher.this.watchService) != null) { WatchKey key = watchService.take(); Path watchedPath = (Path) key.watchable(); Set<Store> toNotify = new HashSet<Store>(); synchronized (watchedPaths) { Map<String, List<Store>> pathRegistration = watchedPaths.get(watchedPath); if (pathRegistration != null) { for (WatchEvent<?> event : key.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) { Path context = (Path) event.context(); String name = context.getFileName().toString(); List<Store> stores = pathRegistration.get(name); if (stores != null) { for (Store current : stores) { toNotify.add(current); } } } else if (StandardWatchEventKinds.OVERFLOW.equals(event.kind())) { for (List<Store> stores : pathRegistration.values()) { for (Store current : stores) { toNotify.add(current); } } } } } key.reset(); } for (Store current : toNotify) { current.modified(); } } } catch (ClosedWatchServiceException | InterruptedException e) { } }
Source:
public static ByteBuffer[] encodeValues( Object[] values, List<DataType> fieldTypes, CodecRegistry codecRegistry, ProtocolVersion protocolVersion) { Preconditions.checkArgument( values.length <= fieldTypes.size(), "Too many values (expected %s, got %s)", fieldTypes.size(), values.length); ByteBuffer[] encodedValues = new ByteBuffer[fieldTypes.size()]; for (int i = 0; i < values.length; i++) { Object value = values[i]; ByteBuffer encodedValue; if (value == null) { encodedValue = null; } else if (value instanceof Token) { if (value instanceof Murmur3Token) { encodedValue = TypeCodecs.BIGINT.encode(((Murmur3Token) value).getValue(), protocolVersion); } else if (value instanceof ByteOrderedToken) { encodedValue = TypeCodecs.BLOB.encode(((ByteOrderedToken) value).getValue(), protocolVersion); } else if (value instanceof RandomToken) { encodedValue = TypeCodecs.VARINT.encode(((RandomToken) value).getValue(), protocolVersion); } else { throw new IllegalArgumentException("Unsupported token type " + value.getClass()); } } else { TypeCodec<Object> codec = codecRegistry.codecFor(fieldTypes.get(i), value); encodedValue = codec.encode(value, protocolVersion); } encodedValues[i] = encodedValue; } return encodedValues; }

Target:
public static ByteBuffer[] encodeValues( Object[] values, List<DataType> fieldTypes, CodecRegistry codecRegistry, ProtocolVersion protocolVersion) { Preconditions.checkArgument( values.length <= fieldTypes.size(), "Too many values (expected %s, got %s)", fieldTypes.size(), values.length); ByteBuffer[] encodedValues = new ByteBuffer[fieldTypes.size()]; for (int i = 0; i < values.length; i++) { Object value = values[i]; ByteBuffer encodedValue; if (value instanceof Token) { if (value instanceof Murmur3Token) { encodedValue = TypeCodecs.BIGINT.encode(((Murmur3Token) value).getValue(), protocolVersion); } else if (value instanceof ByteOrderedToken) { encodedValue = TypeCodecs.BLOB.encode(((ByteOrderedToken) value).getValue(), protocolVersion); } else if (value instanceof RandomToken) { encodedValue = TypeCodecs.VARINT.encode(((RandomToken) value).getValue(), protocolVersion); } else { throw new IllegalArgumentException("Unsupported token type " + value.getClass()); } } else { TypeCodec<Object> codec = (value == null) ? codecRegistry.codecFor(fieldTypes.get(i)) : codecRegistry.codecFor(fieldTypes.get(i), value); encodedValue = codec.encode(value, protocolVersion); } encodedValues[i] = encodedValue; } return encodedValues; }
Source:
public void resetCommitMessageComponent() { overwrittenCommitMessage = commitMessageComponent.getCommitMessage(); loadInitialState(new CommitHelper(currentRepository)); }

Target:
public void resetCommitMessageComponent() { if (currentRepository != null) { String commitMessage = commitMessageComponent.getCommitMessage(); if (commitMessage.trim().length() > 0) { CommitMessageHistory.saveCommitHistory(commitMessage); } loadInitialState(new CommitHelper(currentRepository)); } }
Source:
public static List<ColumnMapping> buildColumnMappings( List<HivePartitionKey> partitionKeys, List<HiveColumnHandle> columns, List<HiveColumnHandle> requiredInterimColumns, Map<Integer, Column> partitionSchemaDifference, Path path, OptionalInt bucketNumber) { Map<String, HivePartitionKey> partitionKeysByName = uniqueIndex(partitionKeys, HivePartitionKey::getName); int regularIndex = 0; Set<Integer> regularColumnIndices = new HashSet<>(); ImmutableList.Builder<ColumnMapping> columnMappings = ImmutableList.builder(); for (HiveColumnHandle column : columns) { Optional<Column> partitionColumn = Optional.ofNullable(partitionSchemaDifference.get(column.getHiveColumnIndex())); Optional<HiveType> coerceFrom = Optional.empty(); if (partitionColumn.isPresent() && !partitionColumn.get().getType().equals(column.getHiveType())) { coerceFrom = Optional.of(partitionColumn.get().getType()); } if (column.getColumnType() == REGULAR) { checkArgument(regularColumnIndices.add(column.getHiveColumnIndex()), "duplicate hiveColumnIndex in columns list"); columnMappings.add(regular(column, regularIndex, coerceFrom)); regularIndex++; } else { columnMappings.add(prefilled( column, getPrefilledColumnValue(column, partitionKeysByName.get(column.getName()), path, bucketNumber), coerceFrom)); } } for (HiveColumnHandle column : requiredInterimColumns) { checkArgument(column.getColumnType() == REGULAR); if (regularColumnIndices.contains(column.getHiveColumnIndex())) { continue; } columnMappings.add(interim(column, regularIndex)); regularIndex++; } return columnMappings.build(); }

Target:
public static List<ColumnMapping> buildColumnMappings( List<HivePartitionKey> partitionKeys, List<HiveColumnHandle> columns, List<HiveColumnHandle> requiredInterimColumns, Map<Integer, Column> partitionSchemaDifference, Path path, OptionalInt bucketNumber) { Map<String, HivePartitionKey> partitionKeysByName = uniqueIndex(partitionKeys, HivePartitionKey::getName); int regularIndex = 0; Set<Integer> regularColumnIndices = new HashSet<>(); ImmutableList.Builder<ColumnMapping> columnMappings = ImmutableList.builder(); for (HiveColumnHandle column : columns) { Optional<Column> partitionColumn = Optional.ofNullable(partitionSchemaDifference.get(column.getHiveColumnIndex())); Optional<HiveType> coercionFrom = Optional.empty(); if (partitionColumn.isPresent() && !partitionColumn.get().getType().equals(column.getHiveType())) { coercionFrom = Optional.of(partitionColumn.get().getType()); } if (column.getColumnType() == REGULAR) { checkArgument(regularColumnIndices.add(column.getHiveColumnIndex()), "duplicate hiveColumnIndex in columns list"); columnMappings.add(regular(column, regularIndex, coercionFrom)); regularIndex++; } else { columnMappings.add(prefilled( column, getPrefilledColumnValue(column, partitionKeysByName.get(column.getName()), path, bucketNumber), coercionFrom)); } } for (HiveColumnHandle column : requiredInterimColumns) { checkArgument(column.getColumnType() == REGULAR); if (regularColumnIndices.contains(column.getHiveColumnIndex())) { continue; } columnMappings.add(interim(column, regularIndex)); regularIndex++; } return columnMappings.build(); }
Source:
protected void processChecks(final UserSelection userSelection, final ImportGermplasmListForm form) { final String[] selectedCheck = form.getSelectedCheck(); if (selectedCheck != null && selectedCheck.length != 0) { ImportedGermplasmMainInfo importedGermplasmMainInfoToUse = userSelection.getImportedCheckGermplasmMainInfo(); if (importedGermplasmMainInfoToUse == null) { importedGermplasmMainInfoToUse = userSelection.getImportedGermplasmMainInfo(); } if (importedGermplasmMainInfoToUse != null) { for (int i = 0; i < selectedCheck.length; i++) { if (NumberUtils.isNumber(selectedCheck[i])) { importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i).setEntryTypeValue(selectedCheck[i]); importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i) .setEntryTypeCategoricalID(Integer.parseInt(selectedCheck[i])); } } } } }

Target:
protected void processChecks(final UserSelection userSelection, final ImportGermplasmListForm form) { final String[] selectedCheck = form.getSelectedCheck(); if (selectedCheck != null && selectedCheck.length != 0) { ImportedGermplasmMainInfo importedGermplasmMainInfoToUse = userSelection.getImportedCheckGermplasmMainInfo(); if (importedGermplasmMainInfoToUse == null) { importedGermplasmMainInfoToUse = userSelection.getImportedGermplasmMainInfo(); } if (importedGermplasmMainInfoToUse != null) { for (int i = 0; i < selectedCheck.length; i++) { if (NumberUtils.isNumber(selectedCheck[i])) { importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i) .setEntryTypeValue(selectedCheck[i]); importedGermplasmMainInfoToUse.getImportedGermplasmList().getImportedGermplasms().get(i) .setEntryTypeCategoricalID(Integer.parseInt(selectedCheck[i])); } } } } else { if (userSelection.getImportedGermplasmMainInfo() != null && userSelection.getImportedGermplasmMainInfo().getImportedGermplasmList() != null && userSelection.getImportedGermplasmMainInfo().getImportedGermplasmList().getImportedGermplasms() != null) { for (final ImportedGermplasm germplasm : userSelection.getImportedGermplasmMainInfo().getImportedGermplasmList() .getImportedGermplasms()) { germplasm.setEntryTypeCategoricalID(null); germplasm.setEntryTypeValue(""); } } } }
Source:
public void start() throws Exception { if (started.compareAndSet(false, true)) { node.start(); started.set(true); } }

Target:
public void start() throws Exception { if (running.compareAndSet(false, true)) { node.start(); } }
Source:
public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); UriComponents uriComponents = uriBuilder.path("/{id}").buildAndExpand(id); response.setHeader("Location", uriComponents.toUri().toString()); return getPoolById(id); }

Target:
public PoolDto createPool(@RequestBody PoolDto pool, UriComponentsBuilder uriBuilder, HttpServletResponse response) throws IOException { Long id = poolService.savePool(Dtos.to(pool)); return getPoolById(id); }
Source:
public User getUser(Integer userId) throws APIException { User user = dao.getUser(userId); if (isDaemon(user)) { log.warn("requested User of Id '" + userId + "' is Daemon"); return null; } return user; }

Target:
public User getUser(Integer userId) throws APIException { return dao.getUser(userId); }
Source:
private Object parseId(Map message) throws JsonRpcException { if (!message.containsKey("id")) { throw new JsonRpcException(null, invalid("required key `id` missing")); } Object id = message.get("id"); if (!(id instanceof String || id instanceof Number || id == null)) { throw new JsonRpcException(null, invalid("key `id` not string or number or null", id)); } else { return id; } }

Target:
private Object parseId(Map message) throws JsonRpcException { if (!message.containsKey(ID)) { throw new JsonRpcException(null, invalid(String.format("required key `%s` missing", ID))); } Object id = message.get(ID); if (!(id instanceof String || id instanceof Number || id == null)) { throw new JsonRpcException( null, invalid(String.format("key `%s` not string or number or null", ID), id)); } else { return id; } }
Source:
public boolean onHttpResponseReceive(HttpMessage msg) { String site = msg.getRequestHeader().getHostName() + ":" + msg.getRequestHeader().getHostPort(); if (getView() != null) { this.getParamsPanel().addSite(site); } SiteParameters sps = this.getSiteParameters(site); TreeSet<HtmlParameter> params = msg.getCookieParams(); Iterator<HtmlParameter> iter = params.iterator(); while (iter.hasNext()) { persist(sps.addParam(site, iter.next(), msg)); } List<HttpHeaderField> headersList = msg.getResponseHeader().getHeaders(); Iterator<HttpHeaderField> hdrIter = headersList.iterator(); while (hdrIter.hasNext()) { HttpHeaderField hdrField = hdrIter.next(); HtmlParameter headerParam = new HtmlParameter(HtmlParameter.Type.header, hdrField.getName(), hdrField.getValue()); sps.addParam(site, headerParam, msg); } return true; }

Target:
public boolean onHttpResponseReceive(HttpMessage msg) { String site = msg.getRequestHeader().getHostName() + ":" + msg.getRequestHeader().getHostPort(); if (getView() != null) { this.getParamsPanel().addSite(site); } SiteParameters sps = this.getSiteParameters(site); TreeSet<HtmlParameter> params = msg.getCookieParams(); Iterator<HtmlParameter> iter = params.iterator(); while (iter.hasNext()) { persist(sps.addParam(site, iter.next(), msg)); } List<HttpHeaderField> headersList = msg.getResponseHeader().getHeaders(); List<String> setCookieHeaders = Arrays.asList(HttpHeader.SET_COOKIE.toLowerCase(), HttpHeader.SET_COOKIE2.toLowerCase()); for (HttpHeaderField hdrField:headersList) { if (setCookieHeaders.contains(hdrField.getName().toLowerCase())) { continue; } HtmlParameter headerParam = new HtmlParameter(HtmlParameter.Type.header, hdrField.getName(), hdrField.getValue()); persist(sps.addParam(site, headerParam, msg)); } return true; }
Source:
public void setup() throws IOException { InputStreamFactory in = new ResourceAsStreamFactory(ADSentenceSampleStreamTest.class, "/opennlp/tools/formats/ad.sample"); try (ADSentenceSampleStream stream = new ADSentenceSampleStream( new PlainTextByLineStream(in, "UTF-8"), true)) { SentenceSample sample = stream.read(); while (sample != null) { System.out.println(sample.getDocument()); System.out.println("<fim>"); samples.add(sample); sample = stream.read(); } } }

Target:
public void setup() throws IOException { InputStreamFactory in = new ResourceAsStreamFactory(ADSentenceSampleStreamTest.class, "/opennlp/tools/formats/ad.sample"); try (ADSentenceSampleStream stream = new ADSentenceSampleStream( new PlainTextByLineStream(in, StandardCharsets.UTF_8), true)) { SentenceSample sample; while ((sample = stream.read()) != null) { System.out.println(sample.getDocument()); System.out.println("<fim>"); samples.add(sample); } } }
Source:
public String toString() { return new StringBuilder("Amount{") .append("total=").append(total) .append('}').toString(); }

Target:
public String toString() { return new StringBuilder("Amount{") .append("total=").append(total) .append(", fees=").append(fees) .append(", refunds=").append(refunds) .append(", liquid=").append(liquid) .append(", currency='").append(currency) .append('\'') .append('}').toString(); }
Source:
private static ArmorStand getArmorStand(Block projector, boolean createIfNoneExists) { String nametag = BlockStorage.getLocationInfo(projector.getLocation(), "text"); double xOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), X_OFFSET_PARAMETER)); double yOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Y_OFFSET_PARAMETER)); double zOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Z_OFFSET_PARAMETER)); Location l = new Location(projector.getWorld(), projector.getX() + xOffset, projector.getY() + yOffset, projector.getZ() + zOffset); for (Entity n : l.getChunk().getEntities()) { if (n instanceof ArmorStand && l.distanceSquared(n.getLocation()) < 0.4) { String customName = n.getCustomName(); if (customName != null && customName.equals(nametag)) { return (ArmorStand) n; } } } if (!createIfNoneExists) { return null; } ArmorStand hologram = SimpleHologram.create(l); hologram.setCustomName(nametag); return hologram; }

Target:
private static ArmorStand getArmorStand(Block projector, boolean createIfNoneExists) { String nametag = BlockStorage.getLocationInfo(projector.getLocation(), "text"); double xOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), X_OFFSET_PARAMETER)); double yOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Y_OFFSET_PARAMETER)); double zOffset = Double.parseDouble(BlockStorage.getLocationInfo(projector.getLocation(), Z_OFFSET_PARAMETER)); Location l = projector.getLocation().add(xOffset, yOffset, zOffset); for (Entity n : l.getChunk().getEntities()) { if (n instanceof ArmorStand && l.distanceSquared(n.getLocation()) < 0.4) { String customName = n.getCustomName(); if (customName != null && customName.equals(nametag)) { return (ArmorStand) n; } } } if (!createIfNoneExists) { return null; } ArmorStand hologram = SimpleHologram.create(l); hologram.setCustomName(nametag); return hologram; }
Source:
default Iterator<T> takeRight(int n) { if (n <= 0) { return empty(); } else { final Iterator<T> that = this; return new Iterator<T>() { private Queue<T> queue = Queue.empty(); @Override public boolean hasNext() { while (that.hasNext()) { queue = queue.append(that.next()); if(queue.length() > n) { queue = queue.dequeue()._2; } } return queue.length() > 0; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final Tuple2<T, Queue<T>> t = queue.dequeue(); queue = t._2; return t._1; } }; } }

Target:
default Iterator<T> takeRight(int n) { if (n <= 0) { return empty(); } else { final Iterator<T> that = this; return new Iterator<T>() { private Queue<T> queue = Queue.empty(); @Override public boolean hasNext() { while (that.hasNext()) { queue = queue.enqueue(that.next()); if(queue.length() > n) { queue = queue.dequeue()._2; } } return queue.length() > 0; } @Override public T next() { if (!hasNext()) { EMPTY.next(); } final Tuple2<T, Queue<T>> t = queue.dequeue(); queue = t._2; return t._1; } }; } }
Source:
public Set<HivePrivilegeInfo> listTablePrivileges(String databaseName, String tableName, PrestoPrincipal principal) { try { return retry() .stopOnIllegalExceptions() .run("getListPrivileges", stats.getListPrivileges().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { Table table = client.getTable(databaseName, tableName); ImmutableSet.Builder<HivePrivilegeInfo> privileges = ImmutableSet.builder(); if (principal.getType() == USER && table.getOwner().equals(principal.getName())) { privileges.add(new HivePrivilegeInfo(OWNERSHIP, true, principal)); } List<HiveObjectPrivilege> hiveObjectPrivilegeList = client.listPrivileges( principal.getName(), fromPrestoPrincipalType(principal.getType()), new HiveObjectRef(TABLE, databaseName, tableName, null, null)); for (HiveObjectPrivilege hiveObjectPrivilege : hiveObjectPrivilegeList) { privileges.addAll(parsePrivilege(hiveObjectPrivilege.getGrantInfo())); } return privileges.build(); } })); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }

Target:
public Set<HivePrivilegeInfo> listTablePrivileges(String databaseName, String tableName, PrestoPrincipal principal) { try { return retry() .stopOnIllegalExceptions() .run("getListPrivileges", stats.getListPrivileges().wrap(() -> { try (HiveMetastoreClient client = clientProvider.createMetastoreClient()) { Table table = client.getTable(databaseName, tableName); ImmutableSet.Builder<HivePrivilegeInfo> privileges = ImmutableSet.builder(); List<HiveObjectPrivilege> hiveObjectPrivilegeList; if (principal == null) { hiveObjectPrivilegeList = client.listPrivileges( null, null, new HiveObjectRef(TABLE, databaseName, tableName, null, null)); } else { if (principal.getType() == USER && table.getOwner().equals(principal.getName())) { privileges.add(new HivePrivilegeInfo(OWNERSHIP, true, principal, principal)); } hiveObjectPrivilegeList = client.listPrivileges( principal.getName(), fromPrestoPrincipalType(principal.getType()), new HiveObjectRef(TABLE, databaseName, tableName, null, null)); } for (HiveObjectPrivilege hiveObjectPrivilege : hiveObjectPrivilegeList) { PrestoPrincipal grantee = new PrestoPrincipal(fromMetastoreApiPrincipalType(hiveObjectPrivilege.getPrincipalType()), hiveObjectPrivilege.getPrincipalName()); privileges.addAll(parsePrivilege(hiveObjectPrivilege.getGrantInfo(), Optional.of(grantee))); } return privileges.build(); } })); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }
Source:
public void concurrentUsageTest() throws Exception { final int firstNumber = 1; final int lastNumber = 50; final BigIntegerNumberGenerator generator = createGenerator(); final List<CompletionStage<BigInteger>> completionStageNumbers = IntStream.range(firstNumber, lastNumber) .mapToObj(i -> generator.getNextNumber()) .collect(Collectors.toList()); final List<BigInteger> numbersGenerated = CompletableFutureUtils.listOfFuturesToFutureOfList(completionStageNumbers).toCompletableFuture().join(); final List<BigInteger> expectedNumbers = IntStream.range(firstNumber, lastNumber).mapToObj(i -> BigInteger.valueOf(i)).collect(Collectors.toList()); assertThat(numbersGenerated.containsAll(expectedNumbers)).isTrue(); }

Target:
public void concurrentUsageTest() throws Exception { final int firstNumber = 1; final int lastNumber = 20; final BigIntegerNumberGenerator generator = createGenerator(); final List<CompletionStage<BigInteger>> completionStageNumbers = IntStream.range(firstNumber, lastNumber) .mapToObj(i -> generator.getNextNumber()) .collect(Collectors.toList()); final List<BigInteger> numbersGenerated = CompletableFutureUtils.listOfFuturesToFutureOfList(completionStageNumbers).toCompletableFuture().join(); final List<BigInteger> expectedNumbers = IntStream.range(firstNumber, lastNumber).mapToObj(i -> BigInteger.valueOf(i)).collect(Collectors.toList()); assertThat(numbersGenerated.containsAll(expectedNumbers)).isTrue(); }
Source:
public void processTaskState(Task task) { long workItemId = task.getTaskData().getWorkItemId(); long processInstanceId = task.getTaskData().getProcessInstanceId(); RuntimeManager manager = getManager(task); RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); KieSession session = runtime.getKieSession(); if (task.getTaskData().getStatus() == Status.Completed) { String userId = task.getTaskData().getActualOwner().getId(); Map<String, Object> results = new HashMap<String, Object>(); Map<String, Object> taskOutcome = task.getTaskData().getTaskOutputVariables(); if (taskOutcome != null) { results.putAll(taskOutcome); } predictionService.train(task, task.getTaskData().getTaskInputVariables(), results); session.getWorkItemManager().completeWorkItem(workItemId, results); } else { session.getWorkItemManager().abortWorkItem(workItemId); } }

Target:
public void processTaskState(Task task) { long workItemId = task.getTaskData().getWorkItemId(); long processInstanceId = task.getTaskData().getProcessInstanceId(); RuntimeManager manager = getManager(task); RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get(processInstanceId)); KieSession session = runtime.getKieSession(); if (task.getTaskData().getStatus() == Status.Completed) { String userId = task.getTaskData().getActualOwner().getId(); Map<String, Object> results = new HashMap<String, Object>(); Map<String, Object> taskOutcome = task.getTaskData().getTaskOutputVariables(); if (taskOutcome != null) { results.putAll(taskOutcome); } results.put("ActorId", userId); predictionService.train(task, task.getTaskData().getTaskInputVariables(), results); session.getWorkItemManager().completeWorkItem(workItemId, results); } else { session.getWorkItemManager().abortWorkItem(workItemId); } }