auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected SlaveObjectAxisProvider getSlaveObjectAxisProvider(final TableConfiguration configuration) { SlaveObjectAxisProvider slave = null; if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> columnAxisProvidersIterator = configuration.getColumnAxisProviders().iterator(); while (columnAxisProvidersIterator.hasNext() && null == slave) { AbstractAxisProvider axisProvider = columnAxisProvidersIterator.next(); if (axisProvider instanceof SlaveObjectAxisProvider) { slave = (SlaveObjectAxisProvider) axisProvider; } } } return slave; }

Target:
protected SlaveObjectAxisProvider getSlaveObjectAxisProvider(final TableConfiguration configuration) { SlaveObjectAxisProvider slave = null; if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> columnAxisProvidersIterator = configuration.getColumnAxisProviders().iterator(); while (columnAxisProvidersIterator.hasNext() && null == slave) { final AbstractAxisProvider axisProvider = columnAxisProvidersIterator.next(); if (axisProvider instanceof SlaveObjectAxisProvider) { slave = (SlaveObjectAxisProvider) axisProvider; } } } return slave; }
Source:
protected boolean acquireLock() { Guid objectLockingId = getObjectLockingId(); boolean returnValue = true; if (!Guid.Empty.equals(objectLockingId)) { EngineLock lock = new EngineLock(); String currType = getClass().getName(); Map<String, Guid> exclusiveLock = Collections.singletonMap(currType, objectLockingId); lock.setExclusiveLocks(exclusiveLock); if (LockManagerFactory.getLockManager().acquireLock(lock)) { log.infoFormat("Lock Aquired to object {0}", lock); commandLock = lock; } else { log.infoFormat("Failed to Aquire Lock to object {0}", lock); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED); returnValue = false; } } return returnValue; }

Target:
protected boolean acquireLock() { Guid objectLockingId = getObjectLockingId(); boolean returnValue = true; if (!Guid.Empty.equals(objectLockingId)) { EngineLock lock = new EngineLock(); String currType = getClass().getName(); Map<String, Guid> exclusiveLock = Collections.singletonMap(currType, objectLockingId); lock.setExclusiveLocks(exclusiveLock); if (LockManagerFactory.getLockManager().acquireLock(lock)) { log.infoFormat("Lock Acquired to object {0}", lock); commandLock = lock; } else { log.infoFormat("Failed to Acquire Lock to object {0}", lock); addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_OBJECT_LOCKED); returnValue = false; } } return returnValue; }
Source:
public void testJdbcBatchingOutputFormatCloseDuringRuntime() throws Exception{ JdbcOptions options = JdbcOptions.builder() .setDBUrl(getDbMetadata().getUrl()) .setTableName(OUTPUT_TABLE) .build(); RuntimeContext context = Mockito.mock(RuntimeContext.class); ExecutionConfig executionConfig = Mockito.mock(ExecutionConfig.class); JdbcExecutionOptions jdbcExecutionOptions = Mockito.mock(JdbcExecutionOptions.class); JdbcBatchStatementExecutor executor = Mockito.mock(JdbcBatchStatementExecutor.class); doReturn(executionConfig).when(context).getExecutionConfig(); doReturn(500L).when(jdbcExecutionOptions).getBatchIntervalMs(); doReturn(2).when(jdbcExecutionOptions).getBatchSize(); doReturn(3).when(jdbcExecutionOptions).getMaxRetries(); doThrow(SQLException.class).when(executor).executeBatch(); JdbcBatchingOutputFormat<Tuple2<Boolean, Row>, Row, JdbcBatchStatementExecutor<Row>> format = new JdbcBatchingOutputFormat<>( new SimpleJdbcConnectionProvider(options), jdbcExecutionOptions, (ctx) -> executor, (tuple2) -> tuple2.f1); format.setRuntimeContext(context); format.open(0, 1); try { for (JdbcTestFixture.TestEntry entry : TEST_DATA) { format.writeRecord(Tuple2.of(true, toRow(entry))); } } catch (Exception e) { try { format.close(); } catch (Exception realException){ Connection connection = format.getConnection(); if (connection != null && !connection.isClosed()){ throw new RuntimeException("Resource leak!"); } } } }

Target:
public void testJdbcBatchingOutputFormatCloseDuringRuntime() throws Exception{ JdbcOptions options = JdbcOptions.builder() .setDBUrl(getDbMetadata().getUrl()) .setTableName(OUTPUT_TABLE) .build(); JdbcExecutionOptions jdbcExecutionOptions = JdbcExecutionOptions.builder() .withBatchIntervalMs(1000_000L) .withBatchSize(2) .withMaxRetries(1) .build(); ExecutionConfig executionConfig = new ExecutionConfig(); RuntimeContext context = Mockito.mock(RuntimeContext.class); JdbcBatchStatementExecutor executor = Mockito.mock(JdbcBatchStatementExecutor.class); doReturn(executionConfig).when(context).getExecutionConfig(); doThrow(SQLException.class).when(executor).executeBatch(); JdbcBatchingOutputFormat<Tuple2<Boolean, Row>, Row, JdbcBatchStatementExecutor<Row>> format = new JdbcBatchingOutputFormat<>( new SimpleJdbcConnectionProvider(options), jdbcExecutionOptions, (ctx) -> executor, (tuple2) -> tuple2.f1); format.setRuntimeContext(context); format.open(0, 1); try { for (JdbcTestFixture.TestEntry entry : TEST_DATA) { format.writeRecord(Tuple2.of(true, toRow(entry))); } } catch (Exception e) { format.close(); } finally { assertNull(format.getConnection()); } }
Source:
private List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch, int msgLevel) throws Exception { if (fileToSearch == null) { log(messages.getString("info.file.validated")); return null; } if (!fileToSearch.exists()) { log(MessageFormat.format(messages.getString("info.file.validate.noexist"), fileToSearch.getCanonicalPath())); return null; } InputStream serverOutput = null; InputStreamReader in = null; Scanner s = null; List<String> matches = null; try { serverOutput = new FileInputStream(fileToSearch); in = new InputStreamReader(serverOutput); s = new Scanner(in); log(MessageFormat.format(messages.getString("info.look.string.infile"), regexp, fileToSearch.getName()), Project.MSG_VERBOSE); String foundString = null; Pattern pattern = Pattern.compile(regexp); matches = new ArrayList<String>(); while (s.hasNextLine()) { if (foundString != null && stopOnFirst) { break; } if (searchLimit <= 0 && searchLimit >= matches.size()) { break; } String line = s.nextLine(); if (pattern.matcher(line).find()) { foundString = line; matches.add(line); log(MessageFormat.format(messages.getString("info.match.string"), matches.size(), line), msgLevel); } } } catch (Exception e) { log(e.toString()); } finally { try { s.close(); } catch (Exception e) { } try { serverOutput.close(); } catch (Exception e) { } try { in.close(); } catch (Exception e) { } } return matches; }

Target:
private List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch, int msgLevel) { if (fileToSearch == null) { log(messages.getString("info.file.validated")); return null; } if (!fileToSearch.exists()) { try { log(MessageFormat.format(messages.getString("info.file.validate.noexist"), fileToSearch.getCanonicalPath())); } catch (IOException e) { log(MessageFormat.format(messages.getString("info.file.validate.noexist"), fileToSearch.getAbsolutePath())); } return null; } InputStream serverOutput = null; InputStreamReader in = null; Scanner s = null; List<String> matches = null; try { serverOutput = new FileInputStream(fileToSearch); in = new InputStreamReader(serverOutput); s = new Scanner(in); log(MessageFormat.format(messages.getString("info.look.string.infile"), regexp, fileToSearch.getName()), Project.MSG_VERBOSE); String foundString = null; Pattern pattern = Pattern.compile(regexp); matches = new ArrayList<String>(); while (s.hasNextLine()) { if (foundString != null && stopOnFirst) { break; } if (searchLimit <= 0 && searchLimit >= matches.size()) { break; } String line = s.nextLine(); if (pattern.matcher(line).find()) { foundString = line; matches.add(line); log(MessageFormat.format(messages.getString("info.match.string"), matches.size(), line), msgLevel); } } } catch (Exception e) { log(e.toString()); } finally { try { s.close(); } catch (Exception e) { } try { serverOutput.close(); } catch (Exception e) { } try { in.close(); } catch (Exception e) { } } return matches; }
Source:
public void setTags(final List<String> tags) { this.tags = tags != null ? SetUniqueList.decorate(tags) : null; }

Target:
public void setTags(final List<String> tags) { this.tags = tags != null ? SetUniqueList.decorate(new ArrayList(tags)) : null; }
Source:
public void testIpSubnetMin() { assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/24')", IPADDRESS, "1.2.3.0"); assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/32')", IPADDRESS, "1.2.3.4"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/127')", IPADDRESS, "64:ff9b::16"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/128')", IPADDRESS, "64:ff9b::17"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/0')", IPADDRESS, "::"); assertInvalidCast("IP_SUBNET_MIN(IPPREFIX '64::ff9b::10/48')", "Cannot cast value to IPPREFIX: 64::ff9b::10/48"); assertInvalidCast("IP_SUBNET_MIN(IPPREFIX '123.456.789.012/24')", "Cannot cast value to IPPREFIX: 123.456.789.012/24"); }

Target:
public void testIpSubnetMin() { assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/24')", IPADDRESS, "1.2.3.0"); assertFunction("IP_SUBNET_MIN(IPPREFIX '1.2.3.4/32')", IPADDRESS, "1.2.3.4"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/64')", IPADDRESS, "64:ff9b::"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/127')", IPADDRESS, "64:ff9b::16"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/128')", IPADDRESS, "64:ff9b::17"); assertFunction("IP_SUBNET_MIN(IPPREFIX '64:ff9b::17/0')", IPADDRESS, "::"); }
Source:
public Optional<PostEntity> getPostById(String postId) { return Optional.ofNullable( getPost() .getPosts() .stream() .peek(postEntity -> scrollTo(postEntity.getWebElement())) .filter(postEntity -> postEntity.findId().equals(postId)) .findFirst() .orElseThrow(() -> new RuntimeException(String.format("Post with id [%s] not found on page", postId)))); }

Target:
public PostEntity getPostById(String postId) { return getPost() .getPosts() .stream() .peek(postEntity -> scrollTo(postEntity.getWebElement())) .filter(postEntity -> postEntity.findId().equals(postId)) .findFirst() .orElseThrow( () -> new RuntimeException(String.format("Post with id [%s] not found on page", postId))); }
Source:
public Court GetCourtById(Long courtId) throws NotFoundException { return courtDAO.getByCourtId(courtId); }

Target:
public Court GetCourtById(Long courtId){ return courtDAO.getByCourtId(courtId); }
Source:
protected void terminate() throws ResourceManagerException { try { resourceManagerDriver.terminate().get(); } catch (Throwable t) { throw new ResourceManagerException("Cannot terminate resource provider.", t); } }

Target:
protected void terminate() throws ResourceManagerException { try { resourceManagerDriver.terminate().get(); } catch (Exception e) { throw new ResourceManagerException("Cannot terminate resource provider.", e); } }
Source:
private void setupConfForPySpark(SparkConf conf) { String pysparkBasePath = new InterpreterProperty("SPARK_HOME", null, null, null).getValue(); File pysparkPath; if (null == pysparkBasePath) { pysparkBasePath = new InterpreterProperty("ZEPPELIN_HOME", "zeppelin.home", "../", null).getValue(); pysparkPath = new File(pysparkBasePath, "interpreter" + File.separator + "spark" + File.separator + "pyspark"); } else { pysparkPath = new File(pysparkBasePath, "python" + File.separator + "lib"); } String[] pythonLibs = new String[]{"pyspark.zip", "py4j-0.9-src.zip", "py4j-0.8.2.1-src.zip", "py4j-0.10.3-src.zip"}; ArrayList<String> pythonLibUris = new ArrayList<>(); for (String lib : pythonLibs) { File libFile = new File(pysparkPath, lib); if (libFile.exists()) { pythonLibUris.add(libFile.toURI().toString()); } } pythonLibUris.trimToSize(); if (pythonLibUris.size() == 2) { try { String confValue = conf.get("spark.yarn.dist.files"); conf.set("spark.yarn.dist.files", confValue + "," + Joiner.on(",").join(pythonLibUris)); } catch (NoSuchElementException e) { conf.set("spark.yarn.dist.files", Joiner.on(",").join(pythonLibUris)); } if (!useSparkSubmit()) { conf.set("spark.files", conf.get("spark.yarn.dist.files")); } conf.set("spark.submit.pyArchives", Joiner.on(":").join(pythonLibs)); } if (getProperty("master").equals("yarn-client")) { conf.set("spark.yarn.isPython", "true"); } }

Target:
private void setupConfForPySpark(SparkConf conf) { String pysparkBasePath = new InterpreterProperty("SPARK_HOME", null, null, null).getValue(); File pysparkPath; if (null == pysparkBasePath) { pysparkBasePath = new InterpreterProperty("ZEPPELIN_HOME", "zeppelin.home", "../", null).getValue(); pysparkPath = new File(pysparkBasePath, "interpreter" + File.separator + "spark" + File.separator + "pyspark"); } else { pysparkPath = new File(pysparkBasePath, "python" + File.separator + "lib"); } String[] pythonLibs = new String[]{"pyspark.zip", "py4j-0.9-src.zip", "py4j-0.8.2.1-src.zip", "py4j-0.10.1-src.zip", "py4j-0.10.3-src.zip"}; ArrayList<String> pythonLibUris = new ArrayList<>(); for (String lib : pythonLibs) { File libFile = new File(pysparkPath, lib); if (libFile.exists()) { pythonLibUris.add(libFile.toURI().toString()); } } pythonLibUris.trimToSize(); if (pythonLibUris.size() == 2) { try { String confValue = conf.get("spark.yarn.dist.files"); conf.set("spark.yarn.dist.files", confValue + "," + Joiner.on(",").join(pythonLibUris)); } catch (NoSuchElementException e) { conf.set("spark.yarn.dist.files", Joiner.on(",").join(pythonLibUris)); } if (!useSparkSubmit()) { conf.set("spark.files", conf.get("spark.yarn.dist.files")); } conf.set("spark.submit.pyArchives", Joiner.on(":").join(pythonLibs)); } if (getProperty("master").equals("yarn-client")) { conf.set("spark.yarn.isPython", "true"); } }
Source:
public void seek(long desired) throws IOException { inStream.skip(desired); }

Target:
public void seek(long desired) throws IOException { throw new UnsupportedOperationException("Compressed streams do not support the seek operation"); }
Source:
public void testCreateTableWithPrimaryKey() { final String sql = "CREATE TABLE tbl1 (\n" + " a bigint,\n" + " b varchar, \n" + " c int, \n" + " d varchar, \n" + " constraint ct1 primary key(a, b) not enforced\n" + ") with (\n" + " 'connector' = 'kafka', \n" + " 'kafka.topic' = 'log.test'\n" + ")\n"; FlinkPlannerImpl planner = getPlannerBySqlDialect(SqlDialect.DEFAULT); final CalciteParser parser = getParserBySqlDialect(SqlDialect.DEFAULT); Operation operation = parse(sql, planner, parser); assert operation instanceof CreateTableOperation; CreateTableOperation op = (CreateTableOperation) operation; CatalogTable catalogTable = op.getCatalogTable(); TableSchema tableSchema = catalogTable.getSchema(); assertThat( tableSchema .getPrimaryKey() .map(UniqueConstraint::asSummaryString) .orElse("fakeVal"), is("CONSTRAINT ct1 PRIMARY KEY (a, b)")); assertArrayEquals(tableSchema.getFieldNames(), new String[] {"a", "b", "c", "d"}); assertArrayEquals(tableSchema.getFieldDataTypes(), new DataType[]{ DataTypes.BIGINT().notNull(), DataTypes.STRING().notNull(), DataTypes.INT(), DataTypes.STRING()}); }

Target:
public void testCreateTableWithPrimaryKey() { final String sql = "CREATE TABLE tbl1 (\n" + " a bigint,\n" + " b varchar, \n" + " c int, \n" + " d varchar, \n" + " constraint ct1 primary key(a, b) not enforced\n" + ") with (\n" + " 'connector' = 'kafka', \n" + " 'kafka.topic' = 'log.test'\n" + ")\n"; FlinkPlannerImpl planner = getPlannerBySqlDialect(SqlDialect.DEFAULT); final CalciteParser parser = getParserBySqlDialect(SqlDialect.DEFAULT); Operation operation = parse(sql, planner, parser); assert operation instanceof CreateTableOperation; CreateTableOperation op = (CreateTableOperation) operation; CatalogTable catalogTable = op.getCatalogTable(); TableSchema tableSchema = catalogTable.getSchema(); assertThat( tableSchema .getPrimaryKey() .map(UniqueConstraint::asSummaryString) .orElse("fakeVal"), is("CONSTRAINT ct1 PRIMARY KEY (a, b)")); assertArrayEquals( new String[] {"a", "b", "c", "d"}, tableSchema.getFieldNames()); assertArrayEquals( new DataType[]{ DataTypes.BIGINT().notNull(), DataTypes.STRING().notNull(), DataTypes.INT(), DataTypes.STRING()}, tableSchema.getFieldDataTypes()); }
Source:
public SimpleFeature next() { SimpleFeature next = super.next(); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); for (Property property : next.getProperties()) { if (property instanceof GeometryAttribute) { builder.set(featureType.getGeometryDescriptor().getName(), property.getValue()); } else { builder.set(property.getName().getLocalPart(), property.getValue()); } } Map<Object, Object> userData = next.getUserData(); for (Entry<Object, Object> entry : userData.entrySet()) { builder.featureUserData(entry.getKey(), entry.getValue()); } String oldFeatureId = next.getIdentifier().getID(); String featureId; if (fidMappings.containsKey(oldFeatureId)) { featureId = fidMappings.get(oldFeatureId); } else { featureId = SimpleFeatureBuilder.createDefaultFeatureId(); } return builder.buildFeature(featureId); }

Target:
public SimpleFeature next() { SimpleFeature next = super.next(); SimpleFeatureBuilder builder = new SimpleFeatureBuilder(featureType); builder.init(next); String oldFeatureId = next.getIdentifier().getID(); String featureId; if (fidMappings.containsKey(oldFeatureId)) { featureId = fidMappings.get(oldFeatureId); } else { featureId = SimpleFeatureBuilder.createDefaultFeatureId(); } return builder.buildFeature(featureId); }
Source:
public Paint getPaint() { return paint; }

Target:
public Color getPaint() { return paint; }
Source:
public static void main(String[] args) { System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "INFO"); System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, "System.err"); Logger LOG = LoggerFactory.getLogger(SystemInfoTest.class); LOG.info("Initializing System..."); SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); printSoundCards(hal.getSoundCards()); }

Target:
public static void main(String[] args) { System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "INFO"); System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, "System.err"); Logger LOG = LoggerFactory.getLogger(SystemInfoTest.class); LOG.info("Initializing System..."); SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); OperatingSystem os = si.getOperatingSystem(); System.out.println(os); LOG.info("Checking computer system..."); printComputerSystem(hal.getComputerSystem()); LOG.info("Checking Processor..."); printProcessor(hal.getProcessor()); LOG.info("Checking Memory..."); printMemory(hal.getMemory()); LOG.info("Checking CPU..."); printCpu(hal.getProcessor()); LOG.info("Checking Processes..."); printProcesses(os, hal.getMemory()); LOG.info("Checking Sensors..."); printSensors(hal.getSensors()); LOG.info("Checking Power sources..."); printPowerSources(hal.getPowerSources()); LOG.info("Checking Disks..."); printDisks(hal.getDiskStores()); LOG.info("Checking File System..."); printFileSystem(os.getFileSystem()); LOG.info("Checking Network interfaces..."); printNetworkInterfaces(hal.getNetworkIFs()); LOG.info("Checking Network parameterss..."); printNetworkParameters(os.getNetworkParams()); LOG.info("Checking Displays..."); printDisplays(hal.getDisplays()); LOG.info("Checking USB Devices..."); printUsbDevices(hal.getUsbDevices(true)); LOG.info("Checking Sound Cards..."); printSoundCards(hal.getSoundCards()); }
Source:
public void testPITRow() throws Exception { final int NROWS = 1; String schemaName = generateUniqueName(); String dataTableName = generateUniqueName(); String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName); String indexTableName = generateUniqueName(); String indexTableFullName = SchemaUtil.getTableName(schemaName, indexTableName); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { initTablesAndAddExtraRowsToIndex(conn, schemaName, dataTableName, indexTableName, NROWS); IndexToolIT.runIndexTool(false, false, schemaName, dataTableName, indexTableName, null, 0, IndexVerifyType.ONLY, "-fi"); Cell cell = IndexToolIT.getErrorMessageFromIndexToolOutputTable(conn, dataTableFullName, indexTableFullName); try { String expectedErrorMsg = IndexRepairRegionScanner.ERROR_MESSAGE_EXTRA_INDEX_ROW; String actualErrorMsg = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); assertTrue(expectedErrorMsg.equals(actualErrorMsg)); } catch(Exception ex) { Assert.fail("Fail to parsing the error message from IndexToolOutputTable"); } } }

Target:
public void testPITRow() throws Exception { final int NROWS = 1; String schemaName = generateUniqueName(); String dataTableName = generateUniqueName(); String dataTableFullName = SchemaUtil.getTableName(schemaName, dataTableName); String indexTableName = generateUniqueName(); String indexTableFullName = SchemaUtil.getTableName(schemaName, indexTableName); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { initTablesAndAddExtraRowsToIndex(conn, schemaName, dataTableName, indexTableName, NROWS); IndexToolIT.runIndexTool(false, false, schemaName, dataTableName, indexTableName, null, 0, IndexVerifyType.ONLY, "-fi"); Cell cell = IndexToolIT.getErrorMessageFromIndexToolOutputTable(conn, dataTableFullName, indexTableFullName); String expectedErrorMsg = IndexRepairRegionScanner.ERROR_MESSAGE_EXTRA_INDEX_ROW; String actualErrorMsg = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); assertTrue(actualErrorMsg.contains(expectedErrorMsg)); } }
Source:
public static Object convertField(String type, String fieldValue) { if (fieldValue == null) { return null; } try { if (type.equals(SupportedFieldType.BOOLEAN.toString())) { return Boolean.parseBoolean(fieldValue); } else if (type.equals(SupportedFieldType.DATE.toString())) { try { return FormatUtil.getTimeZoneFormat().parse(fieldValue); } catch (ParseException e) { return FormatUtil.getDateFormat().parse(fieldValue); } } else if (type.equals(SupportedFieldType.INTEGER.toString())) { return Integer.parseInt(fieldValue); } else if (type.equals(SupportedFieldType.MONEY.toString()) || type.equals(SupportedFieldType.DECIMAL.toString())) { return new BigDecimal(fieldValue); } } catch (ParseException e) { throw new RuntimeException(e); } throw new IllegalArgumentException("Unrecognized type(" + type + ") for map field conversion."); }

Target:
public static Object convertField(String type, String fieldValue) { if (fieldValue == null) { return null; } try { if (type.equals(SupportedFieldType.BOOLEAN.toString())) { return Boolean.parseBoolean(fieldValue); } else if (type.equals(SupportedFieldType.DATE.toString())) { if (fieldValue.length() == 19) { return FormatUtil.getDateFormat().parse(fieldValue); } else { return FormatUtil.getTimeZoneFormat().parse(fieldValue); } } else if (type.equals(SupportedFieldType.INTEGER.toString())) { return Integer.parseInt(fieldValue); } else if (type.equals(SupportedFieldType.MONEY.toString()) || type.equals(SupportedFieldType.DECIMAL.toString())) { return new BigDecimal(fieldValue); } } catch (ParseException e) { throw new RuntimeException(e); } throw new IllegalArgumentException("Unrecognized type(" + type + ") for map field conversion."); }
Source:
public boolean addNewUser(AccountRequest request) throws QuadrigaStorageException, UsernameExistsException { QuadrigaUserDTO userDTO = usermanagerDAO.getUserDTO(request.getUsername()); if (userDTO != null) throw new UsernameExistsException("Username already in use."); QuadrigaUserRequestsDTO userRequest = usermanagerDAO.getUserRequestDTO(request.getUsername()); if (userRequest != null) throw new UsernameExistsException("Username already in use."); String plainPassword = request.getPassword(); boolean success = false; if(request.isSocialSignIn()){ success = usermanagerDAO.addNewUserAccountRequest(request.getUsername(), null, request.getName(), request.getEmail(), request.getProvider(), request.getUserIdOfProvider()); } else{ success = usermanagerDAO.addNewUserAccountRequest(request.getUsername(), encryptPassword(plainPassword), request.getName(), request.getEmail(), null, null); } if (success) { IQuadrigaRole role = rolemanager.getQuadrigaRoleById(IQuadrigaRoleManager.MAIN_ROLES, RoleNames.ROLE_QUADRIGA_ADMIN); List<QuadrigaUserDTO> admins = usermanagerDAO.getUserDTOList(role.getDBid()); for (QuadrigaUserDTO admin : admins) { try { emailManager.sendAccountCreatedEmail(request.getName(), request.getUsername(), admin.getFullname(), admin.getEmail()); } catch (QuadrigaNotificationException e) { logger.error("Email to " + admin.getUsername() + " could not be sent.", e); } } } return success; }

Target:
public void addNewUser(AccountRequest request) throws QuadrigaStorageException, UsernameExistsException, UserRequestExistsException{ if (usermanagerDAO.getUserDTO(request.getUsername()) != null){ throw new UsernameExistsException("Username already in use."); } QuadrigaUserRequestsDTO userRequest = usermanagerDAO.getUserRequestDTO(request.getUsername()); if (userRequest != null){ throw new UserRequestExistsException("User request already exists."); } String password = (request.getPassword() != null) ? encryptPassword(request.getPassword()) : null ; boolean success = usermanagerDAO.addNewUserAccountRequest(request.getUsername(), password, request.getName(), request.getEmail(), request.getProvider() , request.getUserIdOfProvider()); if (success) { IQuadrigaRole role = rolemanager.getQuadrigaRoleById(IQuadrigaRoleManager.MAIN_ROLES, RoleNames.ROLE_QUADRIGA_ADMIN); List<QuadrigaUserDTO> admins = usermanagerDAO.getUserDTOList(role.getDBid()); for (QuadrigaUserDTO admin : admins) { try { emailManager.sendAccountCreatedEmail(request.getName(), request.getUsername(), admin.getFullname(), admin.getEmail()); } catch (QuadrigaNotificationException e) { logger.error("Email to " + admin.getUsername() + " could not be sent.", e); } } } }
Source:
private void sendQualityImpl(XMLStreamWriter serializer) throws XMLStreamException { if ( qualityModified == false ) return; serializer.writeStartElement("rapi", "quality", REST_API_NS); if(String.valueOf(getQuality()) != null) serializer.writeCharacters(String.valueOf(getQuality())); serializer.writeEndElement(); }

Target:
private void sendQualityImpl(XMLStreamWriter serializer) throws XMLStreamException { if ( qualityModified == false ) return; serializer.writeStartElement("rapi", "quality", REST_API_NS); serializer.writeCharacters(String.valueOf(getQuality())); serializer.writeEndElement(); }
Source:
private void doSetChannelMappings(Map<String, String> newChannelMappings) { Map<String, String> oldChannelMappings = new HashMap<String, String>(this.channelMappings); synchronized (this.channelMappings) { this.channelMappings.clear(); this.channelMappings.putAll(newChannelMappings); } if (logger.isDebugEnabled()) { logger.debug("Channel mappings: " + oldChannelMappings + " replaced with: " + newChannelMappings); } }

Target:
private void doSetChannelMappings(Map<String, String> newChannelMappings) { Map<String, String> oldChannelMappings = this.channelMappings; this.channelMappings = newChannelMappings; if (logger.isDebugEnabled()) { logger.debug("Channel mappings: " + oldChannelMappings + " replaced with: " + newChannelMappings); } }
Source:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); String entity = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); List<StudentAttributes> students; if (userInfo.isInstructor && entity.equals(Const.EntityType.INSTRUCTOR)) { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } else if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { throw new InvalidHttpParameterException("Invalid entity type for search"); } List<StudentData> studentDataList = new ArrayList<>(); for (StudentAttributes s : students) { StudentData studentData = new StudentData(s); if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { studentData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(s.getKey()), getInstituteFromCourseId(s.getCourse()), s.getGoogleId()); } else { studentData.hideInformationForSearch(); } studentData.hideLastName(); studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); return new JsonResult(studentsData); }

Target:
public ActionResult execute() { String searchKey = getNonNullRequestParamValue(Const.ParamsNames.SEARCH_KEY); String entity = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); List<StudentAttributes> students; if (userInfo.isInstructor && entity.equals(Const.EntityType.INSTRUCTOR)) { List<InstructorAttributes> instructors = logic.getInstructorsForGoogleId(userInfo.id); students = logic.searchStudents(searchKey, instructors).studentList; } else if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { students = logic.searchStudentsInWholeSystem(searchKey).studentList; } else { throw new InvalidHttpParameterException("Invalid entity type for search"); } List<StudentData> studentDataList = new ArrayList<>(); for (StudentAttributes s : students) { StudentData studentData = new StudentData(s); if (userInfo.isAdmin && entity.equals(Const.EntityType.ADMIN)) { studentData.addAdditionalInformationForAdminSearch( StringHelper.encrypt(s.getKey()), getInstituteFromCourseId(s.getCourse()), s.getGoogleId() ); } studentData.hideLastName(); studentDataList.add(studentData); } StudentsData studentsData = new StudentsData(); studentsData.setStudents(studentDataList); return new JsonResult(studentsData); }
Source:
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.get().getKeyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed " + "for key with id %s", this.key.get().getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key.get()); }); }

Target:
Mono<UnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); return ensureValidKeyAvailable().flatMap(available -> { if (!available) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.getKeyOps(), KeyOperation.UNWRAP_KEY)) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed " + "for key with id %s", this.key.getId())))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); }); }
Source:
private ArgumentParseException createValueError() { return createError(t("Short setFlags that are not at the end of a group cannot have a value.")); }

Target:
private ArgumentParseException createValueError() { return createError(t("Short flags that are not at the end of a group cannot have a value.")); }
Source:
public void deleteSelectedApi(String[] apiNames) throws APIException{ final Lock lock = getLock(); try { lock.lock(); CAppArtifactDataService cAppArtifactDataService = ConfigHolder.getInstance(). getcAppArtifactDataService(); for (String apiName :apiNames ) { assertNameNotEmpty(apiName); apiName = apiName.trim(); if (!cAppArtifactDataService.isArtifactDeployedFromCApp(getTenantId(), ServiceBusConstants.API_TYPE + File.separator + apiName)) { if (log.isDebugEnabled()) { log.debug("Deleting API : " + apiName + " from the configuration"); } SynapseConfiguration synapseConfiguration = getSynapseConfiguration(); API api = synapseConfiguration.getAPI(apiName); api.destroy(); synapseConfiguration.removeAPI(apiName); MediationPersistenceManager pm = getMediationPersistenceManager(); String fileName = api.getFileName(); pm.deleteItem(apiName, fileName, ServiceBusConstants.ITEM_TYPE_REST_API); if (log.isDebugEnabled()) { log.debug("Api : " + apiName + " removed from the configuration"); } } } } finally { lock.unlock(); } }

Target:
public void deleteSelectedApi(String[] apiNames) throws APIException { final Lock lock = getLock(); try { lock.lock(); CAppArtifactDataService cAppArtifactDataService = ConfigHolder.getInstance().getcAppArtifactDataService(); for (String apiName : apiNames) { assertNameNotEmpty(apiName); apiName = apiName.trim(); if (!cAppArtifactDataService.isArtifactDeployedFromCApp(getTenantId(), getArtifactName(artifactType, apiName))) { if (log.isDebugEnabled()) { log.debug("Deleting API : " + apiName + " from the configuration"); } SynapseConfiguration synapseConfiguration = getSynapseConfiguration(); API api = synapseConfiguration.getAPI(apiName); api.destroy(); synapseConfiguration.removeAPI(apiName); MediationPersistenceManager pm = getMediationPersistenceManager(); String fileName = api.getFileName(); pm.deleteItem(apiName, fileName, ServiceBusConstants.ITEM_TYPE_REST_API); if (log.isDebugEnabled()) { log.debug("Api : " + apiName + " removed from the configuration"); } } } } finally { lock.unlock(); } }
Source:
private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; try { Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); return EnvInjectPlugin.canViewInjectedVars(run); } finally { if (initialContext != null) { SecurityContextHolder.setContext(initialContext); } } }

Target:
private boolean canViewInjectedVars(@Nonnull User user, @Nonnull Run<?,?> run) throws UsernameNotFoundException { SecurityContext initialContext = null; Authentication auth = user.impersonate(); initialContext = hudson.security.ACL.impersonate(auth); try { return EnvInjectPlugin.canViewInjectedVars(run); } finally { SecurityContextHolder.setContext(initialContext); } }
Source:
protected int run() throws Exception { if (doImport) { store.checkPermission(CredentialsProvider.UPDATE); List<DomainCredentials> replacement = (List<DomainCredentials>) Items.XSTREAM.unmarshal(safeXmlStreamReader(stdin)); for (DomainCredentials domain : replacement) { for (Credentials credentials : domain.getCredentials()) { store.addDomain(domain.getDomain(), credentials); } } return 0; } else { store.checkPermission(CredentialsProvider.VIEW); List<DomainCredentials> existing = new ArrayList<>(); List<Domain> domains = store.getDomains(); for (Domain domain : domains) { existing.add(new DomainCredentials(domain, store.getCredentials(domain))); } CredentialsStoreAction.SECRETS_REDACTED.toXML(existing, new OutputStreamWriter(stdout, "UTF-8")); return 0; } }

Target:
protected int run() throws Exception { store.checkPermission(CredentialsProvider.UPDATE); List<DomainCredentials> existing = new ArrayList<>(); List<Domain> domains = store.getDomains(); for (Domain domain : domains) { existing.add(new DomainCredentials(domain, store.getCredentials(domain))); } CredentialsStoreAction.SECRETS_REDACTED.toXML(existing, new OutputStreamWriter(stdout, "UTF-8")); return 0; }
Source:
public void stop(String handle, String reason) { Map<String, String> params = new HashMap<String, String>(); addParam(params, "reason", reason); this.transport.stop(handle, params); }

Target:
public void stop(String handle, String reason) { Map<String, String> params = buildParams("reason", reason); this.transport.stop(handle, params); }
Source:
private List<String> resultToList(TupleQueryResult result, String valueBinding, Function<String, String> transform) { ImmutableList.Builder<String> values = ImmutableList.builder(); try { while (result.hasNext()) { BindingSet bindings = result.next(); Binding value = bindings.getBinding(valueBinding); if (value == null) { continue; } String strValue = value.getValue().stringValue(); if (transform != null) { strValue = transform.apply(strValue); } values.add(strValue); } } catch (QueryEvaluationException e) { throw new FatalException("Can't load results: " + e, e); } return values.build(); }

Target:
private List<String> resultToList(TupleQueryResult result, String valueBinding, Function<String, String> transform) { ImmutableList.Builder<String> values = ImmutableList.builder(); try { while (result.hasNext()) { BindingSet bindings = result.next(); Binding value = bindings.getBinding(valueBinding); if (value == null) { continue; } values.add(transform.apply(value.getValue().stringValue())); } } catch (QueryEvaluationException e) { throw new FatalException("Can't load results: " + e, e); } return values.build(); }
Source:
private List<VM> checkVmsStatusChanged() { List<VM> running = new ArrayList<VM>(); if (!_vdsManager.getRefreshStatistics()) { List<VmDynamic> tempRunningList = new ArrayList<VmDynamic>(); for (Entry<VmDynamic, VmStatistics> runningVm : _runningVms.values()) { tempRunningList.add(runningVm.getKey()); } for (VmDynamic runningVm : tempRunningList) { VM vmToUpdate = null; vmToUpdate = _vmDict.get(runningVm.getId()); if (vmToUpdate == null || (vmToUpdate.getstatus() != runningVm.getstatus() && !(vmToUpdate.getstatus() == VMStatus.SavingState && runningVm .getstatus() == VMStatus.Up))) { GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters> command = new GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters>(new GetVmStatsVDSCommandParameters( _vds, runningVm.getId())); command.Execute(); if (command.getVDSReturnValue().getSucceeded()) { _runningVms.put(runningVm.getId(), (Entry<VmDynamic, VmStatistics>) command.getReturnValue()); } else { _runningVms.remove(runningVm.getId()); } } else { running.add(vmToUpdate); _runningVms.remove(vmToUpdate.getId()); } } } for (VM vm : running) { ResourceManager.getInstance().updateQuota(vm); } return running; }

Target:
private List<VM> checkVmsStatusChanged() { List<VM> running = new ArrayList<VM>(); if (!_vdsManager.getRefreshStatistics()) { List<VmDynamic> tempRunningList = new ArrayList<VmDynamic>(); for (Entry<VmDynamic, VmStatistics> runningVm : _runningVms.values()) { tempRunningList.add(runningVm.getKey()); } for (VmDynamic runningVm : tempRunningList) { VM vmToUpdate = null; vmToUpdate = _vmDict.get(runningVm.getId()); if (vmToUpdate == null || (vmToUpdate.getstatus() != runningVm.getstatus() && !(vmToUpdate.getstatus() == VMStatus.SavingState && runningVm .getstatus() == VMStatus.Up))) { GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters> command = new GetVmStatsVDSCommand<GetVmStatsVDSCommandParameters>(new GetVmStatsVDSCommandParameters( _vds, runningVm.getId())); command.Execute(); if (command.getVDSReturnValue().getSucceeded()) { _runningVms.put(runningVm.getId(), (Entry<VmDynamic, VmStatistics>) command.getReturnValue()); } else { _runningVms.remove(runningVm.getId()); } } else { running.add(vmToUpdate); _runningVms.remove(vmToUpdate.getId()); } } } return running; }
Source:
public BulkImportOptions setTempDir(Path tempDir) { this.tempDir = tempDir; return this; }

Target:
public BulkImportOptions setTempDir(Path tempDir) { Objects.requireNonNull(tempDir); this.tempDir = tempDir; return this; }
Source:
protected void delete(Context context, UUID id) throws AuthorizeException { Collection collection = null; try { collection = cs.find(context, id); if (collection == null) { throw new ResourceNotFoundException( CollectionRest.CATEGORY + "." + CollectionRest.NAME + " with id: " + id + " not found"); } } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } try { cs.delete(context, collection); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
protected void delete(Context context, UUID id) throws AuthorizeException { Collection collection = null; try { collection = cs.find(context, id); if (collection == null) { throw new ResourceNotFoundException( CollectionRest.CATEGORY + "." + CollectionRest.NAME + " with id: " + id + " not found"); } } catch (SQLException e) { throw new RuntimeException("Unable to find Collection with id = " + id, e); } try { cs.delete(context, collection); } catch (SQLException e) { throw new RuntimeException("Unable to delete Collection with id = " + id, e); } catch (IOException e) { throw new RuntimeException("Unable to delete collection because the logo couldn't be deleted", e); } }
Source:
public void recreate() throws BuildException { try { if (fileSets.isEmpty()) { handleError( "File set identifying link file(s) required for action recreate"); return; } final Properties links = loadLinks(fileSets); for (final String lnk : links.stringPropertyNames()) { final String res = links.getProperty(lnk); try { if (Files.isSymbolicLink(Paths.get(lnk)) && Paths.get(lnk).toFile().getCanonicalPath().equals(Paths.get(res).toFile().getCanonicalPath())) { continue; } } catch (IOException e) { if (failonerror) { throw new BuildException("Failed to recreate symlink " + lnk + " to target " + res, e); } log("Failed to recreate symlink " + lnk + " to target " + res, Project.MSG_INFO); continue; } this.doLink(res, lnk); } } finally { setDefaults(); } }

Target:
public void recreate() throws BuildException { try { if (fileSets.isEmpty()) { handleError( "File set identifying link file(s) required for action recreate"); return; } final Properties links = loadLinks(fileSets); for (final String lnk : links.stringPropertyNames()) { final String res = links.getProperty(lnk); try { if (Files.isSymbolicLink(Paths.get(lnk)) && new File(lnk).getCanonicalPath().equals(new File(res).getCanonicalPath())) { continue; } } catch (IOException e) { final String errMessage = "Failed to check if path " + lnk + " is a symbolic link, linking to " + res; if (failonerror) { throw new BuildException(errMessage, e); } log(errMessage, Project.MSG_INFO); continue; } this.doLink(res, lnk); } } finally { setDefaults(); } }
Source:
public String getSuggestedSchema(String separator) { String s = ExternalTableUtils.getSuggestedSchema(schema, partition_schema, separator); if(foundFiles != null && foundFiles.length > 0) s = s + separator + " STORED AS " + ExternalTableUtils.getExternalTableTypeFromPath(foundFiles[0]); if( rootPath != null ) s = s + " LOCATION '" + rootPath + "';"; return s; }

Target:
public String getSuggestedSchema(String separator) { StringBuilder sb = new StringBuilder(); ExternalTableUtils.getSuggestedSchema(sb, schema, partition_schema, separator); if(foundFiles != null && foundFiles.length > 0) { sb.append(separator); sb.append(" STORED AS "); sb.append(ExternalTableUtils.getExternalTableTypeFromPath(foundFiles[0])); } if( rootPath != null ) { sb.append(" LOCATION '"); sb.append(rootPath); sb.append("';"); } return sb.toString(); }
Source:
public void removeAllApps() throws Exception { ApplicationListDTO getAllAppResponse = restAPIStore.getAllApps(); List<ApplicationInfoDTO> array = getAllAppResponse.getList(); for (int app = 0; array.size() > app; app++) { restAPIStore.deleteApplication(array.get(app).getApplicationId()); } }

Target:
public void removeAllApps() throws Exception { ApplicationListDTO getAllAppResponse = restAPIStore.getAllApps(); List<ApplicationInfoDTO> applicationInfoDTOs = getAllAppResponse.getList(); for (ApplicationInfoDTO applicationInfoDTO : applicationInfoDTOs) { restAPIStore.deleteApplication(applicationInfoDTO.getApplicationId()); } }
Source:
protected Events executeStateAction(final ExecutionContext executionContext) { log.info("Cleaning up job..."); final String claimedJobId = executionContext.getClaimedJobId(); final JobStatus finalJobStatus = executionContext.getFinalJobStatus(); final ExecutionContext.KillProvenance killProvenance = executionContext.getJobKillProvenance(); final JobStatus lastJobStatus = executionContext.getCurrentJobStatus(); if (lastJobStatus != null && claimedJobId != null) { if (finalJobStatus == null) { if (killProvenance != null) { try { agentJobService.changeJobStatus( claimedJobId, lastJobStatus, JobStatus.KILLED, "Terminated by user via " + killProvenance.name() ); } catch (final ChangeJobStatusException e) { throw new RuntimeException("Failed to update server status", e); } executionContext.setFinalJobStatus(JobStatus.KILLED); } else { throw new IllegalStateException( "Reached cleanup state and finalJobState is null. Last job state: " + lastJobStatus ); } } else { log.debug("Job final status already updated server-side: {}", finalJobStatus); } } else { log.debug("Job never claimed an ID, skipping server-side status update"); } final List<StateAction> cleanupActions = executionContext.getCleanupActions(); for (final StateAction cleanupAction : cleanupActions) { if (cleanupAction == this) { continue; } try { cleanupAction.cleanup(); } catch (final Exception e) { log.warn( "Exception during action cleanup", cleanupAction.getClass().getSimpleName(), e ); } } return Events.CLEANUP_JOB_COMPLETE; }

Target:
protected Events executeStateAction(final ExecutionContext executionContext) { log.info("Cleaning up job..."); final String claimedJobId = executionContext.getClaimedJobId(); final JobStatus finalJobStatus = executionContext.getFinalJobStatus(); final ExecutionContext.KillSource killSource = executionContext.getJobKillSource(); final JobStatus lastJobStatus = executionContext.getCurrentJobStatus(); if (lastJobStatus != null && claimedJobId != null) { if (finalJobStatus == null) { if (killSource != null) { try { agentJobService.changeJobStatus( claimedJobId, lastJobStatus, JobStatus.KILLED, "Terminated by user via " + killSource.name() ); } catch (final ChangeJobStatusException e) { throw new RuntimeException("Failed to update server status", e); } executionContext.setFinalJobStatus(JobStatus.KILLED); } else { throw new IllegalStateException( "Reached cleanup state and finalJobState is null. Last job state: " + lastJobStatus ); } } else { log.debug("Job final status already updated server-side: {}", finalJobStatus); } } else { log.debug("Job never claimed an ID, skipping server-side status update"); } final List<StateAction> cleanupActions = executionContext.getCleanupActions(); for (final StateAction cleanupAction : cleanupActions) { if (cleanupAction == this) { continue; } try { cleanupAction.cleanup(); } catch (final Exception e) { log.warn( "Exception during action cleanup", cleanupAction.getClass().getSimpleName(), e ); } } return Events.CLEANUP_JOB_COMPLETE; }