auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testLifeCycleReverse() throws Exception { deployContrib(CoreUTConstants.CORE_TESTS_BUNDLE, "LifeCycleManagerReverseTestExtensions.xml"); applyInlineDeployments(); postSetUp(); LifeCycle lifeCycle = lifeCycleService.getLifeCycleByName("defaultReverse"); LifeCycleState workState = lifeCycle.getStateByName("work"); assertEquals("work", workState.getName()); Collection<String> transitions = workState.getAllowedStateTransitions(); assertEquals(3, transitions.size()); assertTrue(transitions.contains("approve")); assertTrue(transitions.contains("cancel")); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("approved"); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("cancelled"); assertEquals("cancelled", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("backToWork")); workState = lifeCycle.getStateByName("obsolete"); assertEquals("obsolete", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(0, transitions.size()); LifeCycleTransition transition = lifeCycle.getTransitionByName("approve"); assertNotNull(transition); String destinationName = transition.getDestinationStateName(); assertEquals("approved", destinationName); }

Target:
public void testLifeCycleReverse() throws Exception { pushInlineDeployments(CoreUTConstants.CORE_TESTS_BUNDLE + ":LifeCycleManagerReverseTestExtensions.xml"); LifeCycle lifeCycle = lifeCycleService.getLifeCycleByName("defaultReverse"); LifeCycleState workState = lifeCycle.getStateByName("work"); assertEquals("work", workState.getName()); Collection<String> transitions = workState.getAllowedStateTransitions(); assertEquals(3, transitions.size()); assertTrue(transitions.contains("approve")); assertTrue(transitions.contains("cancel")); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("approved"); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("obsolete")); workState = lifeCycle.getStateByName("cancelled"); assertEquals("cancelled", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(1, transitions.size()); assertTrue(transitions.contains("backToWork")); workState = lifeCycle.getStateByName("obsolete"); assertEquals("obsolete", workState.getName()); transitions = workState.getAllowedStateTransitions(); assertEquals(0, transitions.size()); LifeCycleTransition transition = lifeCycle.getTransitionByName("approve"); assertNotNull(transition); String destinationName = transition.getDestinationStateName(); assertEquals("approved", destinationName); }
Source:
private void loadLocale() throws IOException, NoticeException { for (DataRow row : queryResults("SELECT name, setting FROM pg_settings WHERE name IN ('lc_numeric', 'lc_time')")) { String localeSpec = row.getColumn(1).toString(); switch (localeSpec.toUpperCase(Locale.US)) { case "C": case "POSIX": localeSpec = "en_US"; break; } if (Locales.getJavaCompatibleLocale(localeSpec.split("\\.")[0]) != null) { localeSpec = Locales.getJavaCompatibleLocale(localeSpec.split("\\.")[0]); } String[] localeIds = localeSpec.split("_|\\."); switch (row.getColumn(0).toString()) { case "lc_numeric": Locale numLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); decimalFormatter = (DecimalFormat) DecimalFormat.getNumberInstance(numLocale); decimalFormatter.setParseBigDecimal(true); currencyFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance(numLocale); currencyFormatter.setParseBigDecimal(true); break; case "lc_time": Locale timeLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); } row.release(); } }

Target:
private void loadLocale() throws IOException, NoticeException { for (DataRow row : queryResults("SELECT name, setting FROM pg_settings WHERE name IN ('lc_numeric', 'lc_time')")) { String localeSpec = row.getColumn(1).toString(); switch (localeSpec.toUpperCase(Locale.US)) { case "C": case "POSIX": localeSpec = "en_US"; break; } String windowsLocale = localeSpec.split("\\.")[0]; if (Locales.getJavaCompatibleLocale(windowsLocale) != null) { localeSpec = Locales.getJavaCompatibleLocale(windowsLocale); } String[] localeIds = localeSpec.split("_|\\."); switch (row.getColumn(0).toString()) { case "lc_numeric": Locale numLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); decimalFormatter = (DecimalFormat) DecimalFormat.getNumberInstance(numLocale); decimalFormatter.setParseBigDecimal(true); currencyFormatter = (DecimalFormat) NumberFormat.getCurrencyInstance(numLocale); currencyFormatter.setParseBigDecimal(true); break; case "lc_time": Locale timeLocale = new Locale.Builder().setLanguageTag(localeIds[0]).setRegion(localeIds[1]).build(); } row.release(); } }
Source:
public JDynamicCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert !this.castTypes.isEmpty(); }

Target:
public JDynamicCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert !this.castTypes.isEmpty(); assert this.castTypes.size() == 1 || !hasJPrimitiveType(); }
Source:
public void removeAllOwnerContacts(PerunSession sess, Owner owner) throws InternalErrorException { try { List<ContactGroup> contactGroups = getFacilityContactGroups(sess, owner); for (ContactGroup contactGroup : contactGroups) { sess.getPerun().getAuditer().log(sess, "User/owner (" + owner.getId() + ") removed from facility contacts " + contactGroup.toString() + "."); } jdbc.update("delete from facility_contacts where owner_id=?", owner.getId()); log.info("All owner's facilities contacts deleted.", owner); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }

Target:
public void removeAllOwnerContacts(PerunSession sess, Owner owner) throws InternalErrorException { try { jdbc.update("delete from facility_contacts where owner_id=?", owner.getId()); log.info("All owner's facilities contacts deleted.", owner); } catch (RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
public CellBaseIterator<Gene> iterator(GeneQuery query) { Bson bson = parseQuery(query); QueryOptions queryOptions = query.toQueryOptions(); Bson projection = getProjection(query); GenericDocumentComplexConverter<Gene> converter = new GenericDocumentComplexConverter<>(Gene.class); MongoDBIterator<Gene> iterator = null; if (query.getSource() != null && !query.getSource().isEmpty() && "refseq".equalsIgnoreCase(query.getSource().get(0))) { iterator = refseqCollection.iterator(null, bson, projection, converter, queryOptions); } else { iterator = mongoDBCollection.iterator(null, bson, projection, converter, queryOptions); } return new CellBaseIterator<>(iterator); }

Target:
public CellBaseIterator<Gene> iterator(GeneQuery query) { Bson bson = parseQuery(query); QueryOptions queryOptions = query.toQueryOptions(); Bson projection = getProjection(query); GenericDocumentComplexConverter<Gene> converter = new GenericDocumentComplexConverter<>(Gene.class); MongoDBIterator<Gene> iterator = null; if (query.getSource() != null && !query.getSource().isEmpty() && VariantDBAdaptor.QueryParams.REFSEQ.key() .equalsIgnoreCase(query.getSource().get(0))) { iterator = refseqCollection.iterator(null, bson, projection, converter, queryOptions); } else { iterator = ensemblCollection.iterator(null, bson, projection, converter, queryOptions); } return new CellBaseIterator<>(iterator); }
Source:
protected void addVmPermission() { if ((getParameters()).isMakeCreatorExplicitOwner()) { permissions perms = new permissions(getCurrentUser().getUserId(), PredefinedRoles.VM_OPERATOR.getId(), getVmId(), VdcObjectType.VM); MultiLevelAdministrationHandler.addPermission(perms); getCompensationContext().snapshotNewEntity(perms); } if (getParameters().isCopyTemplatePermissions() && getVmTemplateId() != null && !getVmTemplateId().equals(Guid.Empty)) { copyTemplatePermissions(); } }

Target:
protected void addVmPermission() { if ((getParameters()).isMakeCreatorExplicitOwner()) { permissions perms = new permissions(getCurrentUser().getUserId(), PredefinedRoles.VM_OPERATOR.getId(), getVmId(), VdcObjectType.VM); MultiLevelAdministrationHandler.addPermission(perms); getCompensationContext().snapshotNewEntity(perms); } if (getParameters().isCopyTemplatePermissions() && !getVmTemplateId().equals(VmTemplateHandler.BlankVmTemplateId)) { copyTemplatePermissions(); } }
Source:
protected Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); }

Target:
private Mono<Authentication> attemptSwitchUser(Authentication currentAuthentication, String userName) { Assert.notNull(userName, "The userName can not be null."); if (this.logger.isDebugEnabled()) { this.logger.debug("Attempt to switch to user [" + userName + "]"); } return userDetailsService.findByUsername(userName) .switchIfEmpty(Mono.error(this::noTargetAuthenticationException)) .doOnNext(userDetailsChecker::check) .map(userDetails -> createSwitchUserToken(userDetails, currentAuthentication)); }
Source:
private void deleteMail(Account.Id id, final String mailAddress) throws UnloggedFailure { if (mailAddress.equals("ALL")) { ResultSet<AccountExternalId> ids; try { ids = db.accountExternalIds().byAccount(id); } catch (OrmException e) { throw die("Could not query database: " + e.getMessage()); } for (AccountExternalId extId : ids) { unlink(id, extId.getEmailAddress()); } } else { unlink(id, mailAddress); } }

Target:
private void deleteMail(Account.Id id, final String mailAddress) throws UnloggedFailure { if (mailAddress.equals("ALL")) { ResultSet<AccountExternalId> ids; try { ids = db.accountExternalIds().byAccount(id); } catch (OrmException e) { throw die("Could not query database: " + e.getMessage()); } for (AccountExternalId extId : ids) { if (extId.getEmailAddress() != null) { unlink(id, extId.getEmailAddress()); } } } else { unlink(id, mailAddress); } }
Source:
public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); if (getWindowStartTime() != startTime || getWindowEndTime() != endTime) { return true; } return false; }

Target:
public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); return (getWindowStartTime() != startTime || getWindowEndTime() != endTime); }
Source:
private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = oldChildValue == null ? false : oldChildValue .booleanValue(); return oldChildStale; }

Target:
private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = oldChildValue != null && oldChildValue; return oldChildStale; }
Source:
public Result<TopNResultValue> build() { final DimValHolder[] holderValueArray = pQueue.toArray(new DimValHolder[0]); Arrays.sort( holderValueArray, new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = -metricComparator.compare(d1.getTopNMetricVal(), d2.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } } ); List<DimValHolder> holderValues = Arrays.asList(holderValueArray); final List<Map<String, Object>> values = Lists.transform( holderValues, new Function<DimValHolder, Map<String, Object>>() { @Override public Map<String, Object> apply(DimValHolder valHolder) { return valHolder.getMetricValues(); } } ); return new Result<TopNResultValue>( timestamp, new TopNResultValue(values) ); }

Target:
public Result<TopNResultValue> build() { final DimValHolder[] holderValueArray = pQueue.toArray(new DimValHolder[0]); Arrays.sort( holderValueArray, new Comparator<DimValHolder>() { @Override public int compare(DimValHolder d1, DimValHolder d2) { int retVal = metricComparator.compare(d2.getTopNMetricVal(), d1.getTopNMetricVal()); if (retVal == 0) { retVal = dimNameComparator.compare(d1.getDimName(), d2.getDimName()); } return retVal; } } ); List<DimValHolder> holderValues = Arrays.asList(holderValueArray); final List<Map<String, Object>> values = Lists.transform( holderValues, new Function<DimValHolder, Map<String, Object>>() { @Override public Map<String, Object> apply(DimValHolder valHolder) { return valHolder.getMetricValues(); } } ); return new Result<TopNResultValue>( timestamp, new TopNResultValue(values) ); }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { btStatusTextView.setText(getString(R.string.status_bluetooth_connected)); } else { Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show(); } } super.onActivityResult(requestCode, resultCode, data); }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { btStatusTextView.setText(getString(R.string.status_bluetooth_connected)); } else { Toast.makeText(this, R.string.text_bluetooth_disabled, Toast.LENGTH_LONG).show(); } } super.onActivityResult(requestCode, resultCode, data); }
Source:
public void visitAnonymousClass(AnonymousClassTree tree) { enterScope(tree); classScope = currentScope; tree.arguments().stream() .filter(arg -> arg.is(Kind.VARIABLE_IDENTIFIER)) .map(VariableIdentifierTree.class::cast) .forEach(arg -> createSymbol(currentScope.outer(), arg, Symbol.Kind.VARIABLE)); createMemberSymbols(tree); super.visitAnonymousClass(tree); classScope = null; leaveScope(); }

Target:
public void visitAnonymousClass(AnonymousClassTree tree) { scan(tree.arguments()); enterScope(tree); classScope = currentScope; createMemberSymbols(tree); NamespaceNameTree superClass = tree.superClass(); if (superClass != null) { scan(superClass); } scan(tree.superInterfaces()); scan(tree.members()); classScope = null; leaveScope(); }
Source:
public static void SYSCS_GET_GLOBAL_DATABASE_PROPERTY(final String key,final ResultSet[] resultSet) throws SQLException{ List<HostAndPort> servers; try { servers = EngineDriver.driver().getServiceDiscovery().listServers(); } catch (IOException e) { throw PublicAPI.wrapStandardException(Exceptions.parseException(e)); } List<ExecRow> rows = new ArrayList<>(); for (HostAndPort server : servers) { try (Connection connection = RemoteUser.getConnection(server.toString())) { try (PreparedStatement ps = connection.prepareStatement("values SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(?)")) { ps.setString(1, key); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { ExecRow row = new ValueRow(1); row.setColumn(1, new SQLVarchar(server.toString())); row.setColumn(2, new SQLVarchar(rs.getString(1))); rows.add(row); } } }; } } GenericColumnDescriptor[] descriptors = { new GenericColumnDescriptor("HOST_NAME", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.VARCHAR, 120)), new GenericColumnDescriptor("PROPERTY_VALUE", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.VARCHAR, 120)), }; EmbedConnection conn = (EmbedConnection)getDefaultConn(); LanguageConnectionContext lcc = conn.getLanguageConnection(); Activation lastActivation = conn.getLanguageConnection().getLastActivation(); IteratorNoPutResultSet resultsToWrap = new IteratorNoPutResultSet(rows, descriptors, lastActivation); try { resultsToWrap.openCore(); } catch (StandardException se) { throw PublicAPI.wrapStandardException(se); } resultSet[0] = new EmbedResultSet40(conn, resultsToWrap, false, null, true); }

Target:
public static void SYSCS_GET_GLOBAL_DATABASE_PROPERTY(final String key,final ResultSet[] resultSet) throws SQLException{ List<HostAndPort> servers; try { servers = EngineDriver.driver().getServiceDiscovery().listServers(); } catch (IOException e) { throw PublicAPI.wrapStandardException(Exceptions.parseException(e)); } List<ExecRow> rows = new ArrayList<>(); for (HostAndPort server : servers) { try (Connection connection = RemoteUser.getConnection(server.toString())) { try (PreparedStatement ps = connection.prepareStatement("values SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(?)")) { ps.setString(1, key); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { ExecRow row = new ValueRow(2); row.setColumn(1, new SQLVarchar(server.toString())); row.setColumn(2, new SQLVarchar(rs.getString(1))); rows.add(row); } } }; } } GenericColumnDescriptor[] descriptors = { new GenericColumnDescriptor("HOST_NAME", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.VARCHAR, 120)), new GenericColumnDescriptor("PROPERTY_VALUE", DataTypeDescriptor.getBuiltInDataTypeDescriptor(Types.VARCHAR, 120)), }; EmbedConnection conn = (EmbedConnection)getDefaultConn(); LanguageConnectionContext lcc = conn.getLanguageConnection(); Activation lastActivation = conn.getLanguageConnection().getLastActivation(); IteratorNoPutResultSet resultsToWrap = new IteratorNoPutResultSet(rows, descriptors, lastActivation); try { resultsToWrap.openCore(); } catch (StandardException se) { throw PublicAPI.wrapStandardException(se); } resultSet[0] = new EmbedResultSet40(conn, resultsToWrap, false, null, true); }
Source:
public static String macToString(byte[] mac) throws KuraException { if ((mac == null) || (mac.length != 6)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } String[] items = new String[6]; for (int i = 0; i < 6; i++) { String octet = Integer.toHexString(mac[i] & 0xFF).toUpperCase(); if (octet.length() == 1) { octet = "0" + octet; } items[i] = octet; } String macString = String.join(":", items); return macString; }

Target:
public static String macToString(byte[] mac) { if ((mac == null) || (mac.length != 6)) { throw new IllegalArgumentException("mac is null or invalid"); } String[] items = new String[6]; for (int i = 0; i < 6; i++) { String octet = Integer.toHexString(mac[i] & 0xFF).toUpperCase(); if (octet.length() == 1) { octet = "0" + octet; } items[i] = octet; } return String.join(":", items); }
Source:
public void setup() throws CommandLineException { cliOut = new ByteArrayOutputStream(); System.setProperty("aesh.ansi","false"); System.setProperty("aesh.terminal","org.jboss.aesh.terminal.TestTerminal"); CLITestUtil.setJBossCliConfig(); config = new CommandContextConfiguration.Builder() .setController(CLITestUtil.constructUri(null, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort())) .setUsername(null) .setPassword(null) .setConsoleInput(null) .setConsoleOutput(cliOut) .setDisableLocalAuth(false) .setInitConsole(true) .build(); ctx = CommandContextFactory.getInstance().newCommandContext(config); ctx.handle("set " + FOO_NAME + "=" + FOO_VALUE); ctx.handle("set " + FOOBAR_NAME + "=" + FOOBAR_VALUE); cliOut.reset(); ctx.handle("echo $" + FOO_NAME); assertTrue(cliOut.toString().contains(FOO_VALUE)); ctx.handle("echo $" + FOOBAR_NAME); assertTrue(cliOut.toString().contains(FOOBAR_VALUE)); ctx.handle("connect"); }

Target:
public void setup() throws Exception { cli = new CLIWrapper(true, null, System.in); assertTrue(cli.isConnected()); cli.sendLine("set " + FOO_NAME + "=" + FOO_VALUE); cli.sendLine("set " + FOOBAR_NAME + "=" + FOOBAR_VALUE); cli.sendLine("echo $" + FOO_NAME); assertTrue(cli.readOutput().contains(FOO_VALUE)); cli.sendLine("echo $" + FOOBAR_NAME); assertTrue(cli.readOutput().contains(FOOBAR_VALUE)); }
Source:
public void testExecuteBatchPreparedStatementFailOne() throws Exception { try (Connection conn = DriverManager.getConnection(connectionStr)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id, string_field) values (?, ?)"); stmt.setInt(1, 2); stmt.setString(2, "foo"); stmt.addBatch(); stmt.setInt(1, 3); stmt.setString(2, "bar"); stmt.addBatch(); stmt.setInt(1, 1); stmt.setObject(2, "baz"); stmt.addBatch(); int[] results = stmt.executeBatch(); assertArrayEquals(new int[]{1, 1, Statement.EXECUTE_FAILED}, results); conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(3L)); } }

Target:
public void testExecuteBatchPreparedStatementFailOne() throws Exception { try (Connection conn = DriverManager.getConnection(connectionString)) { PreparedStatement stmt = conn.prepareStatement("insert into test (id, string_field) values (?, ?)"); stmt.setInt(1, 2); stmt.setString(2, "foo"); stmt.addBatch(); stmt.setInt(1, 1); stmt.setObject(2, "baz"); stmt.addBatch(); int[] results = stmt.executeBatch(); assertArrayEquals(new int[]{1, Statement.EXECUTE_FAILED}, results); conn.createStatement().execute("refresh table test"); ResultSet resultSet = conn.createStatement().executeQuery("select count(*) from test"); assertThat(resultSet.next(), is(true)); assertThat(resultSet.getLong(1), is(2L)); } }
Source:
public KafkaOffsetProvider(KafkaConfigProvider configProvider) { this.configProvider = configProvider; }

Target:
public KafkaOffsetProvider(KafkaConfigProvider configProvider) { this.configProvider = Objects.requireNonNull(configProvider); }
Source:
public void testNoMessageBody() throws Exception { when(msg.getBody()).thenReturn(null); processor.process(exchange); verify(messageSender, never()).sendIndexingOperation(anyString(), any(Collection.class), any(IndexingActionType.class)); }

Target:
public void testNoMessageBody() throws Exception { when(msg.getBody()).thenReturn(null); processor.process(exchange); verify(messageSender, never()).sendIndexingOperation(anyString(), any(PID.class), any(IndexingActionType.class)); }
Source:
PinotExpression(String definition, Origin origin) { this.definition = requireNonNull(definition, "definition"); this.origin = requireNonNull(origin, "origin"); }

Target:
PinotExpression(String definition, Origin origin) { this.definition = requireNonNull(definition, "definition is null"); this.origin = requireNonNull(origin, "origin is null"); }
Source:
public void reTakeLabelLockForQueryWithIndexUsagesWhenSchemaStateWasUpdatedDuringLockOperations() throws Exception { String labelName = "Robot"; Label human = Label.label( labelName ); String propertyKey = "name"; createIndex( human, propertyKey ); try ( Transaction transaction = databaseRule.beginTx() ) { Node node = databaseRule.createNode( human ); node.setProperty( propertyKey, RandomStringUtils.randomAscii( 10 ) ); transaction.success(); } String query = "MATCH (n:" + labelName + ") where n." + propertyKey + " = \"Bender\" RETURN n "; LockOperationListener lockOperationListener = new OnceSchemaFlushListener(); List<LockOperationRecord> lockOperationRecords = traceQueryLocks( query, lockOperationListener ); assertThat( "Observed list of lock operations is: " + lockOperationRecords, lockOperationRecords, hasSize( 3 ) ); LockOperationRecord operationRecord = lockOperationRecords.get( 0 ); assertTrue( operationRecord.acquisition ); assertFalse( operationRecord.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord.resourceType ); LockOperationRecord operationRecord1 = lockOperationRecords.get( 1 ); assertFalse( operationRecord1.acquisition ); assertFalse( operationRecord1.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord1.resourceType ); LockOperationRecord operationRecord2 = lockOperationRecords.get( 2 ); assertTrue( operationRecord2.acquisition ); assertFalse( operationRecord2.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord2.resourceType ); }

Target:
public void reTakeLabelLockForQueryWithIndexUsagesWhenSchemaStateWasUpdatedDuringLockOperations() throws Exception { String labelName = "Robot"; Label robot = Label.label( labelName ); String propertyKey = "name"; createIndex( robot, propertyKey ); try ( Transaction transaction = databaseRule.beginTx() ) { Node node = databaseRule.createNode( robot ); node.setProperty( propertyKey, RandomStringUtils.randomAscii( 10 ) ); transaction.success(); } String query = "MATCH (n:" + labelName + ") where n." + propertyKey + " = \"Bender\" RETURN n "; LockOperationListener lockOperationListener = new OnceSchemaFlushListener(); List<LockOperationRecord> lockOperationRecords = traceQueryLocks( query, lockOperationListener ); assertThat( "Observed list of lock operations is: " + lockOperationRecords, lockOperationRecords, hasSize( 3 ) ); LockOperationRecord operationRecord = lockOperationRecords.get( 0 ); assertTrue( operationRecord.acquisition ); assertFalse( operationRecord.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord.resourceType ); LockOperationRecord operationRecord1 = lockOperationRecords.get( 1 ); assertFalse( operationRecord1.acquisition ); assertFalse( operationRecord1.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord1.resourceType ); LockOperationRecord operationRecord2 = lockOperationRecords.get( 2 ); assertTrue( operationRecord2.acquisition ); assertFalse( operationRecord2.exclusive ); assertEquals( ResourceTypes.LABEL, operationRecord2.resourceType ); }
Source:
Container(JSONObject metadata) throws JSONException { if (metadata == null) { throw new IllegalArgumentException("metadata cannot be null."); } short metadataVersion = (short) metadata.getInt(CONTAINER_METADATA_VERSION_KEY); switch (metadataVersion) { case CONTAINER_METADATA_VERSION_1: this.id = (short) metadata.getInt(CONTAINER_ID_KEY); this.name = metadata.getString(CONTAINER_NAME_KEY); this.status = ContainerStatus.valueOf(metadata.getString(CONTAINER_STATUS_KEY)); this.description = metadata.optString(CONTAINER_DESCRIPTION_KEY); this.isPrivate = metadata.getBoolean(CONTAINER_IS_PRIVATE_KEY); this.parentAccountId = (short) metadata.getInt(CONTAINER_PARENT_ACCOUNT_ID_KEY); checkRequiredFields(); break; default: throw new IllegalStateException("Unsupported container metadata version=" + metadataVersion); } }

Target:
private Container(JSONObject metadata) throws JSONException { if (metadata == null) { throw new IllegalArgumentException("metadata cannot be null."); } short metadataVersion = (short) metadata.getInt(JSON_VERSION_KEY); switch (metadataVersion) { case JSON_VERSION_1: this.id = (short) metadata.getInt(CONTAINER_ID_KEY); this.name = metadata.getString(CONTAINER_NAME_KEY); this.status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY)); this.description = metadata.optString(DESCRIPTION_KEY); this.isPrivate = metadata.getBoolean(IS_PRIVATE_KEY); this.parentAccountId = (short) metadata.getInt(PARENT_ACCOUNT_ID_KEY); checkRequiredFields(); break; default: throw new IllegalStateException("Unsupported container json version=" + metadataVersion); } }
Source:
public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, Vo vo, User authorizedUser) throws InternalErrorException, PrivilegeException, UserNotExistsException, VoNotExistsException { Utils.checkPerunSession(sess); getPerunBl().getVosManagerBl().checkVoExists(sess, vo); getPerunBl().getUsersManagerBl().checkUserExists(sess, authorizedUser); List<Resource> resources = getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, vo, authorizedUser); if(AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) || AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)){ return resources; } if(AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN)) { return filterNotAuthorizedResource(sess, resources); } else { throw new PrivilegeException(sess, "getResourcesByResourceManager"); } }

Target:
public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, Vo vo, User authorizedUser) throws InternalErrorException, PrivilegeException, UserNotExistsException, VoNotExistsException { Utils.checkPerunSession(sess); getPerunBl().getVosManagerBl().checkVoExists(sess, vo); getPerunBl().getUsersManagerBl().checkUserExists(sess, authorizedUser); List<Resource> resources = getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, vo, authorizedUser); if(AuthzResolver.isAuthorized(sess, Role.VOADMIN, vo) || AuthzResolver.isAuthorized(sess, Role.VOOBSERVER, vo) || AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)){ return resources; } if(AuthzResolver.isAuthorized(sess, Role.RESOURCEADMIN)) { return filterNotAuthorizedResource(sess, resources); } else { throw new PrivilegeException(sess, "getResourcesWhereUserIsAdmin"); } }
Source:
@Test void testRowCountRightJoinEmptyFinite() { final String sql = "select * from (select * from emp limit 4) as emp\n" + "right join (select * from dept limit 0) as dept\n" + "on emp.deptno = dept.deptno"; checkRowCount(sql, 1D, 0D, 0D); }

Target:
@Test void testRowCountRightJoinEmptyFinite() { final String sql = "select * from (select * from emp limit 0) as emp\n" + "right join (select * from dept limit 4) as dept\n" + "on emp.deptno = dept.deptno"; checkRowCount(sql, 4D, 0D, 4D); }
Source:
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ProcessorData other = (ProcessorData) obj; return processorId.equals(other.processorId) && host.equals(other.host); }

Target:
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ProcessorData other = (ProcessorData) obj; return Objects.equals(processorId, other.processorId) && Objects.equals(host, other.host); }
Source:
public String getServerVersion() throws SecurityException, TransactionException, TException { return Version.getVersion(ConcourseServer.class).toString(); }

Target:
public String getServerVersion() { return Version.getVersion(ConcourseServer.class).toString(); }
Source:
private Guid getVdsToRunOn(Iterable<VDS> vdss) { final List<VDS> readyToRun = new ArrayList<VDS>(); final List<VmNetworkInterface> vmNetworks = getVmNetworkInterfaceDAO().getAllForVm(getVm().getId()); for (VDS curVds : vdss) { if (!curVds.getvds_group_id().equals(getVm().getvds_group_id())) continue; if (curVds.getstatus() != VDSStatus.Up) continue; if (!RunVmCommandBase.hasMemoryToRunVM(curVds, getVm())) continue; if ((getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) || isVdsFailedToRunVm(curVds.getId()) || !RunVmCommandBase.hasCapacityToRunVM(curVds)) continue; if (curVds.getcpu_cores() != null && getVm().getnum_of_cpus() > curVds.getcpu_cores()) { continue; } if (!IsVMSwapValueLegal(curVds)) continue; if(!areRequiredNetworksAvailable(vmNetworks, getInterfaceDAO().getAllInterfacesForVds(curVds.getId()))) continue; readyToRun.add(curVds); } return readyToRun.isEmpty() ? Guid.Empty : getBestVdsToRun(readyToRun); }

Target:
private Guid getVdsToRunOn(Iterable<VDS> vdss) { final List<VDS> readyToRun = new ArrayList<VDS>(); final List<VmNetworkInterface> vmNICs = getVmNetworkInterfaceDAO().getAllForVm(getVm().getId()); for (VDS curVds : vdss) { if (!curVds.getvds_group_id().equals(getVm().getvds_group_id())) continue; if (curVds.getstatus() != VDSStatus.Up) continue; if (!RunVmCommandBase.hasMemoryToRunVM(curVds, getVm())) continue; if ((getVm().getrun_on_vds() != null && getVm().getrun_on_vds().equals(curVds.getId())) || isVdsFailedToRunVm(curVds.getId()) || !RunVmCommandBase.hasCapacityToRunVM(curVds)) continue; if (curVds.getcpu_cores() != null && getVm().getnum_of_cpus() > curVds.getcpu_cores()) { continue; } if (!IsVMSwapValueLegal(curVds)) continue; if(!areRequiredNetworksAvailable(vmNICs, getInterfaceDAO().getAllInterfacesForVds(curVds.getId()))) continue; readyToRun.add(curVds); } return readyToRun.isEmpty() ? Guid.Empty : getBestVdsToRun(readyToRun); }
Source:
public void storeSettings() { if (preferences.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE) != fontOverrideProperty.getValue()) { restartWarnings.add(Localization.lang("Override font settings")); preferences.putBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE, fontOverrideProperty.getValue()); } int newFontSize = Integer.parseInt(fontSizeProperty.getValue()); if (preferences.getInt(JabRefPreferences.MAIN_FONT_SIZE) != newFontSize) { restartWarnings.add(Localization.lang("Override font size")); preferences.putInt(JabRefPreferences.MAIN_FONT_SIZE, newFontSize); } if (themeLightProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.MAIN_CSS)) { restartWarnings.add(Localization.lang("Theme changed:") + " " + ThemeLoader.MAIN_DESCRIPTION); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.MAIN_CSS); } else if (themeDarkProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.DARK_CSS)) { restartWarnings.add(Localization.lang("Theme changed:") + " " + ThemeLoader.DARK_DESCRIPTION); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.DARK_CSS); } }

Target:
public void storeSettings() { if (preferences.getBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE) != fontOverrideProperty.getValue()) { restartWarnings.add(Localization.lang("Override font settings")); preferences.putBoolean(JabRefPreferences.OVERRIDE_DEFAULT_FONT_SIZE, fontOverrideProperty.getValue()); } int newFontSize = Integer.parseInt(fontSizeProperty.getValue()); if (preferences.getInt(JabRefPreferences.MAIN_FONT_SIZE) != newFontSize) { restartWarnings.add(Localization.lang("Override font size")); preferences.putInt(JabRefPreferences.MAIN_FONT_SIZE, newFontSize); } if (themeLightProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.MAIN_CSS)) { restartWarnings.add(Localization.lang("Theme changed to light theme.")); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.MAIN_CSS); } else if (themeDarkProperty.getValue() && !preferences.get(JabRefPreferences.FX_THEME).equals(ThemeLoader.DARK_CSS)) { restartWarnings.add(Localization.lang("Theme changed to dark theme.")); preferences.put(JabRefPreferences.FX_THEME, ThemeLoader.DARK_CSS); } }
Source:
public TestingLabDTO create(final TestingLabDTO atl) throws UserRetrievalException, EntityCreationException, EntityRetrievalException, JsonProcessingException { String maxCode = testingLabDAO.getMaxCode(); int maxCodeValue = Integer.parseInt(maxCode); int nextCodeValue = maxCodeValue + 1; String nextAtlCode = ""; if (nextCodeValue < 10) { nextAtlCode = "0" + nextCodeValue; } else if (nextCodeValue > 99) { throw new EntityCreationException( "Cannot create a 2-digit ATL code since there are more than 99 ATLs in the system."); } else { nextAtlCode = nextCodeValue + ""; } atl.setTestingLabCode(nextAtlCode); atl.setRetired(false); TestingLabDTO result = testingLabDAO.create(atl); userPermissionsManager.addAtlPermission(result, Util.getCurrentUser().getId()); LOGGER.debug("Created testing lab " + result + " and granted admin permission to recipient " + gov.healthit.chpl.auth.Util.getUsername()); String activityMsg = "Created Testing Lab " + result.getName(); activityManager.addActivity(ActivityConcept.ACTIVITY_CONCEPT_ATL, result.getId(), activityMsg, null, result); return result; }

Target:
public TestingLabDTO create(final TestingLabDTO atl) throws UserRetrievalException, EntityCreationException, EntityRetrievalException, JsonProcessingException { String maxCode = testingLabDAO.getMaxCode(); int maxCodeValue = Integer.parseInt(maxCode); int nextCodeValue = maxCodeValue + 1; String nextAtlCode = ""; if (nextCodeValue < 10) { nextAtlCode = "0" + nextCodeValue; } else if (nextCodeValue > 99) { throw new EntityCreationException( "Cannot create a 2-digit ATL code since there are more than 99 ATLs in the system."); } else { nextAtlCode = nextCodeValue + ""; } atl.setTestingLabCode(nextAtlCode); atl.setRetired(false); TestingLabDTO result = testingLabDAO.create(atl); userPermissionsManager.addAtlPermission(result, Util.getAuditId()); LOGGER.debug("Created testing lab " + result + " and granted admin permission to recipient " + gov.healthit.chpl.auth.Util.getUsername()); String activityMsg = "Created Testing Lab " + result.getName(); activityManager.addActivity(ActivityConcept.ACTIVITY_CONCEPT_ATL, result.getId(), activityMsg, null, result); return result; }
Source:
public void endActivity(){ this.getActivity().finish(); }

Target:
public void endActivity(){ getActivity().finish(); }
Source:
private BlobId createBlobId(String hexBlobId) throws IOException { return new BlobId(hexBlobId, clusterMap); }

Target:
private BlobId createBlobId(String hexBlobId) throws IOException { if (hexBlobId == null) { return null; } return new BlobId(hexBlobId, clusterMap); }
Source:
public void testEdgeLabelMoveFromBorder() { String diagramName = "EdgeWith3SegmentsHVH"; diagramEditor = setUpEditorAccordingToDimensions(diagramName, ZoomLevel.ZOOM_100); SWTBotGefEditPart editPart = diagramEditor.getEditPart("refToBCenter"); editPart.select(); GraphicalEditPart part = (GraphicalEditPart) editPart.part(); IFigure figure = part.getFigure(); figure.translateToAbsolute(figure.getBounds()); int originalX = part.getFigure().getBounds().x; int originalY = part.getFigure().getBounds().y; CheckEditPartMoved checkEditPartMoved = new CheckEditPartMoved(editPart); diagramEditor.dragWithKey(part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y, part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y - 10, SWT.None); bot.waitUntil(checkEditPartMoved); assertEquals("The x corrdinate should be the same as the move is only on y axis.", originalX, part.getFigure().getBounds().x); assertEquals("The y coordinate should be different as the label has been moved by moving its border.", originalY - 10, part.getFigure().getBounds().y); }

Target:
public void testEdgeLabelMoveFromBorder() { String diagramName = "EdgeWith3SegmentsHVH"; diagramEditor = setUpEditorAccordingToDimensions(diagramName, ZoomLevel.ZOOM_100); SWTBotGefEditPart editPart = diagramEditor.getEditPart("refToBCenter"); editPart.select(); GraphicalEditPart part = (GraphicalEditPart) editPart.part(); IFigure figure = part.getFigure(); figure.translateToAbsolute(figure.getBounds()); int originalX = part.getFigure().getBounds().x; int originalY = part.getFigure().getBounds().y; CheckEditPartMoved checkEditPartMoved = new CheckEditPartMoved(editPart); diagramEditor.dragWithKey(part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y, part.getFigure().getBounds().x + 10, part.getFigure().getBounds().y - 10, SWT.None); bot.waitUntil(checkEditPartMoved); assertEquals("The x coordinate should be the same as the move is only on y axis.", originalX, part.getFigure().getBounds().x); assertEquals("The y coordinate should be different as the label has been moved by moving its border.", originalY - 10, part.getFigure().getBounds().y); }
Source:
private String parseFan(String value) { if (value.equals("FA")) return "FAuto"; if (value.equals("F1")) return "Fun1"; if (value.equals("F2")) return "Fun2"; if (value.equals("F3")) return "Fun3"; if (value.equals("F4")) return "Fun4"; if (value.equals("F5")) return "Fun5"; return "None"; }

Target:
private DaikinFan parseFan(String value) { if (value.equals("FA")) return DaikinFan.Auto; if (value.equals("F1")) return DaikinFan.F1; if (value.equals("F2")) return DaikinFan.F2; if (value.equals("F3")) return DaikinFan.F3; if (value.equals("F4")) return DaikinFan.F4; if (value.equals("F5")) return DaikinFan.F5; return DaikinFan.None; }
Source:
public char peekPrevious() { if (index > 0) { int prev = index - 1; return line.charAt(prev); } else { if (lineIndex > 0) { return '\n'; } else { return '\0'; } } }

Target:
public char peekPrevious() { if (index > 0) { int prev = index - 1; return line.charAt(prev); } else { if (lineIndex > 0) { return '\n'; } else { return END; } } }
Source:
StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = osBean instanceof UnixOperatingSystemMXBean; this.linux = osBean.getName().indexOf("Linux") == 0; }

Target:
StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = (osBean instanceof UnixOperatingSystemMXBean); this.linux = (osBean.getName().indexOf("Linux") == 0); }
Source:
public void shouldUserCancelSubmittedStateBeResolvedToUserCancelledState() { cancelStatusResolver = new CancelStatusResolver(); ChargeEntity mockChargeEntity = mock(ChargeEntity.class); when(mockChargeEntity.getStatus()).thenReturn(ChargeStatus.USER_CANCEL_SUBMITTED.getValue()); Optional<InternalExternalStatus> result = cancelStatusResolver.resolve(mockChargeEntity); assertTrue(result.isPresent()); ChargeStatus chargeStatus = (ChargeStatus) result.get(); assertThat(chargeStatus.getValue(), is(ChargeStatus.USER_CANCELLED.getValue())); }

Target:
public void shouldUserCancelSubmittedStateBeResolvedToUserCancelledState() { cancelStatusResolver = new CancelStatusResolver(); ChargeEntity mockChargeEntity = mock(ChargeEntity.class); when(mockChargeEntity.getStatus()).thenReturn(ChargeStatus.USER_CANCEL_SUBMITTED.getValue()); Optional<Status> result = cancelStatusResolver.resolve(mockChargeEntity); assertTrue(result.isPresent()); ChargeStatus chargeStatus = (ChargeStatus) result.get(); assertThat(chargeStatus.getValue(), is(ChargeStatus.USER_CANCELLED.getValue())); }
Source:
protected void markAsMerged(Diff diff, MergeMode mode, boolean mergeRightToLeft, Registry mergerRegistry) { if (isInTerminalState(diff)) { return; } updateDiffStateAdapter(diff); if (AbstractMerger.isAccepting(diff, mergeRightToLeft)) { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); final Set<Diff> rejections = MergeDependenciesUtil.getAllResultingRejections(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : Sets.difference(implied, rejections)) { impliedDiff.setState(DifferenceState.MERGED); } for (Diff impliedRejection : rejections) { impliedRejection.setState(DifferenceState.DISCARDED); } } else { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : implied) { impliedDiff.setState(DifferenceState.DISCARDED); } } }

Target:
protected void markAsMerged(Diff diff, MergeMode mode, boolean mergeRightToLeft, Registry mergerRegistry) { if (isInTerminalState(diff)) { return; } if (isAccepting(diff, mergeRightToLeft)) { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); final Set<Diff> rejections = MergeDependenciesUtil.getAllResultingRejections(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : Sets.difference(implied, rejections)) { impliedDiff.setState(MERGED); } for (Diff impliedRejection : rejections) { impliedRejection.setState(DISCARDED); } } else { final Set<Diff> implied = MergeDependenciesUtil.getAllResultingMerges(diff, mergerRegistry, mergeRightToLeft); for (Diff impliedDiff : implied) { impliedDiff.setState(DISCARDED); } } }
Source:
public void execute() { if (Strings.isNullOrEmpty(getCfgName())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Empty configuration name provided"); } if (getCfgName().equalsIgnoreCase(RoleService.EnableDynamicApiChecker.key())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Restricted configuration update not allowed"); } Configuration cfg = _configService.updateConfiguration(this); if (cfg != null) { ConfigurationResponse response = _responseGenerator.createConfigurationResponse(cfg); response.setResponseName(getCommandName()); if (getZoneId() != null) { response.setScope("zone"); } if (getClusterId() != null) { response.setScope("cluster"); } if (getStoragepoolId() != null) { response.setScope("storagepool"); } if (getAccountId() != null) { response.setScope("account"); } if (getImageStoreId() != null) { response.setScope("imagestore"); } response.setValue(value); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update config"); } }

Target:
public void execute() { if (Strings.isNullOrEmpty(getCfgName())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Empty configuration name provided"); } if (getCfgName().equalsIgnoreCase(RoleService.EnableDynamicApiChecker.key())) { throw new ServerApiException(ApiErrorCode.PARAM_ERROR, "Restricted configuration update not allowed"); } Configuration cfg = _configService.updateConfiguration(this); if (cfg != null) { ConfigurationResponse response = _responseGenerator.createConfigurationResponse(cfg); response.setResponseName(getCommandName()); if (getZoneId() != null) { response.setScope("zone"); } if (getClusterId() != null) { response.setScope("cluster"); } if (getStoragepoolId() != null) { response.setScope("storagepool"); } if (getAccountId() != null) { response.setScope("account"); } response.setValue(value); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update config"); } }
Source:
private ApnsClient buildApnsClient(final iOSVariant iOSVariant) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { if (ApnsUtil.checkValidity(iOSVariant.getCertificate(), iOSVariant.getPassphrase().toCharArray())) { try { final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate()); final ApnsClientBuilder builder = new ApnsClientBuilder(); builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } final ApnsClient apnsClient = builder.build(); stream.close(); return apnsClient; } catch (Exception e) { logger.error("Error reading certificate", e); } } else { return null; } } throw new IllegalArgumentException("Not able to construct APNS client"); }

Target:
private ApnsClient buildApnsClient(final iOSVariant iOSVariant) { if (iOSVariant.getCertificate() != null && iOSVariant.getPassphrase() != null) { try(final ByteArrayInputStream stream = new ByteArrayInputStream(iOSVariant.getCertificate())) { final ApnsClientBuilder builder = new ApnsClientBuilder(); builder.setClientCredentials(stream, iOSVariant.getPassphrase()); if (ProxyConfiguration.hasHttpProxyConfig()) { if (ProxyConfiguration.hasBasicAuth()) { String user = ProxyConfiguration.getProxyUser(); String pass = ProxyConfiguration.getProxyPass(); builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress(), user, pass)); } else { builder.setProxyHandlerFactory(new HttpProxyHandlerFactory(ProxyConfiguration.proxyAddress())); } } else if (ProxyConfiguration.hasSocksProxyConfig()) { builder.setProxyHandlerFactory(new Socks5ProxyHandlerFactory(ProxyConfiguration.socks())); } final ApnsClient apnsClient = builder.build(); return apnsClient; } catch (Exception e) { logger.error("Error reading certificate", e); } } throw new IllegalArgumentException("Not able to construct APNS client"); }