auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testFilenameBatchedNotUnique() throws Exception { ExportToFileClient client = new ExportToFileClient(); Properties props = new Properties(); props.put("nonce", Long.toString(System.currentTimeMillis())); props.put("type", "csv"); props.put("outdir", m_dir); props.put("period", "1"); props.put("with-schema", "true"); props.put("batched", "true"); props.put("uniquenames", "false"); client.configure(props); final AdvertisedDataSource source = constructTestSource(false, 0); final ExportToFileClient.ExportToFileDecoder decoder = client.constructExportDecoder(source); long l = System.currentTimeMillis(); vtable.addRow(l, l, l, 0, l, l, (byte) 1, (short) 2, 3, 4, 5.5, 6, "xx", new BigDecimal(88), GEOG_POINT, GEOG); vtable.advanceRow(); byte[] rowBytes = ExportEncoder.encodeRow(vtable, "mytable", 0, 1L); ExportRow row = ExportRow.decodeRow(null, 0, 0L, rowBytes); decoder.onBlockStart(row); decoder.processRow(row); decoder.onBlockCompletion(row); boolean validName = true; final File dir = new File(m_dir); final File[] subdirs = dir.listFiles(); List<File> remainingFiles = new ArrayList<>(); if (subdirs != null) { for (File file : subdirs) { if (file.isDirectory()) { remainingFiles.addAll(Arrays.asList(file.listFiles())); } else if (!file.getName().matches("\\d\\-mytable.*\\.[a-z]{3,4}")) { validName = false; break; } } for (File file : remainingFiles) { if (!file.getName().matches("\\d\\-mytable.*\\.[a-z]{3,4}")) { System.out.println(file.getName()); validName = false; break; } } } assertTrue(validName); }

Target:
public void testFilenameBatchedNotUnique() throws Exception { ExportToFileClient client = new ExportToFileClient(); Properties props = new Properties(); props.put("nonce", Long.toString(System.currentTimeMillis())); props.put("type", "csv"); props.put("outdir", m_dir); props.put("period", "1"); props.put("with-schema", "true"); props.put("batched", "true"); props.put("uniquenames", "false"); client.configure(props); final AdvertisedDataSource source = constructTestSource(false, 0); final ExportToFileClient.ExportToFileDecoder decoder = client.constructExportDecoder(source); long l = System.currentTimeMillis(); vtable.addRow(l, l, l, 0, l, l, (byte) 1, (short) 2, 3, 4, 5.5, 6, "xx", new BigDecimal(88), GEOG_POINT, GEOG); vtable.advanceRow(); byte[] rowBytes = ExportEncoder.encodeRow(vtable, "mytable", 0, 1L); ExportRow row = ExportRow.decodeRow(null, 0, 0L, rowBytes); decoder.onBlockStart(row); decoder.processRow(row); decoder.onBlockCompletion(row); boolean validName = true; final File dir = new File(m_dir); final File[] subdirs = dir.listFiles(); List<File> allFiles = new ArrayList<>(); if (subdirs != null) { for (File file : subdirs) { if (file.isDirectory()) { allFiles.addAll(Arrays.asList(file.listFiles())); } else { allFiles.add(file); } } for (File file : allFiles) { if (!(file.getName().matches("\\d\\-mytable\\.[a-z]{3}") || file.getName().matches("\\d\\-mytable-schema\\.json"))) { validName = false; break; } } } assertTrue(validName); }
Source:
public boolean removeVertex(final V v) { final Set<Tuple2<V, I>> edges = adjacent.remove(v); if (edges != null) { inDegrees.remove(v); for (final Tuple2<V, I> edge : edges) { final V neighbor = (V) edge.get(0); final int inDegree = inDegrees.get(neighbor) - 1; inDegrees.put(neighbor, inDegree); if (inDegree == 0) { rootVertices.add(neighbor); } } rootVertices.remove(v); return true; } else { LOG.log(Level.WARNING, "The vertex {0} does exists", new Object[]{v}); return false; } }

Target:
public boolean removeVertex(final V v) { final Map<V, I> edges = adjacent.remove(v); if (edges != null) { inDegrees.remove(v); for (final Map.Entry<V, I> edge : edges.entrySet()) { final V neighbor = edge.getKey(); final int inDegree = inDegrees.get(neighbor) - 1; inDegrees.put(neighbor, inDegree); if (inDegree == 0) { rootVertices.add(neighbor); } } rootVertices.remove(v); for (Map.Entry<V, Map<V, I>> entry : adjacent.entrySet()) { entry.getValue().remove(v); } return true; } else { LOG.log(Level.WARNING, "The vertex {0} does exists", new Object[]{v}); return false; } }
Source:
public SummaryCard(String webUrl) throws CardBuilderException { this.cardType = CardType.SUMMARY; webUrl(webUrl); MetaTagModel metaTagModel = MetaTagExtractor.getMetaTags(this.webUrl); summary(new Summary(metaTagModel)); setAppLinkIos(metaTagModel.getAppLinkIos()); setAppLinkAndroid(metaTagModel.getAppLinkAndroid()); }

Target:
public SummaryCard(String webUrl) throws CardBuilderException { super(webUrl); this.cardType = CardType.SUMMARY; summary(new Summary(this.getMetaTagModel())); }
Source:
private Set<Achievement> loadMulti(String category) { Set<Achievement> achievement = new HashSet<>(); for (String key : mainConfig.getConfigurationSection(category).getKeys(false)) { String innerSection = category + "." + key; achievement.addAll(loadInner(innerSection, category)); } return achievement; }

Target:
private Set<Achievement> loadMulti(String category) { Set<Achievement> achievement = new HashSet<>(); for (String key : mainConfig.getShallowKeys(category)) { String innerSection = category + "." + key; achievement.addAll(loadInner(innerSection, category, key)); } return achievement; }
Source:
public Object load(int operatorId, long windowId) { Object obj = null; try { obj = retrieve(generateKey(operatorId, windowId)); logger.info("retrieved object from store key region ", generateKey(operatorId, windowId), applicationId); } catch (Exception ex) { logger.info("while loading {}", operatorId, windowId, ex); throw new RuntimeException(ex); } return obj; }

Target:
public Object load(int operatorId, long windowId) { Object obj = null; try { obj = retrieve(generateKey(operatorId, windowId)); logger.debug("retrieved object from store key region ", generateKey(operatorId, windowId), applicationId); } catch (Exception ex) { throw new RuntimeException(ex); } return obj; }
Source:
public String getConsumerAutoOffsetResetConfig() { return _consumerProps.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "NOT SET"); }

Target:
public String getConsumerAutoOffsetResetConfig() { return _consumerProps.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, ""); }
Source:
public void dispose() { phone.mCM.unregisterForAvailable(this); phone.mCM.unregisterForOffOrNotAvailable(this); ((CDMAPhone) phone).mRuimRecords.unregisterForRecordsLoaded(this); phone.mCM.unregisterForNVReady(this); phone.mCM.unregisterForDataStateChanged(this); ((CDMAPhone) phone).mCT.unregisterForVoiceCallEnded(this); ((CDMAPhone) phone).mCT.unregisterForVoiceCallStarted(this); ((CDMAPhone) phone).mSST.unregisterForCdmaDataConnectionAttached(this); ((CDMAPhone) phone).mSST.unregisterForCdmaDataConnectionDetached(this); ((CDMAPhone) phone).mSST.unregisterForRoamingOn(this); ((CDMAPhone) phone).mSST.unregisterForRoamingOff(this); this.removeCallbacksAndMessages(null); phone.getContext().unregisterReceiver(this.alarmReceiver); phone.getContext().unregisterReceiver(this.screenOnOffReceiver); destroyAllDataConnectionList(); this.netstat = null; this.mActiveDataConnection = null; this.filter = null; this.filterS = null; this.screenOnOffReceiver = null; this.mDataConnectionTracker = null; this.dataEnabled = null; this.phone = null; }

Target:
public void dispose() { phone.mCM.unregisterForAvailable(this); phone.mCM.unregisterForOffOrNotAvailable(this); ((CDMAPhone) phone).mRuimRecords.unregisterForRecordsLoaded(this); phone.mCM.unregisterForNVReady(this); phone.mCM.unregisterForDataStateChanged(this); ((CDMAPhone) phone).mCT.unregisterForVoiceCallEnded(this); ((CDMAPhone) phone).mCT.unregisterForVoiceCallStarted(this); ((CDMAPhone) phone).mSST.unregisterForCdmaDataConnectionAttached(this); ((CDMAPhone) phone).mSST.unregisterForCdmaDataConnectionDetached(this); ((CDMAPhone) phone).mSST.unregisterForRoamingOn(this); ((CDMAPhone) phone).mSST.unregisterForRoamingOff(this); phone.getContext().unregisterReceiver(this.alarmReceiver); phone.getContext().unregisterReceiver(this.screenOnOffReceiver); destroyAllDataConnectionList(); }
Source:
public DotRunnableThread(final List<DotRunnable> allListeners) { this.listeners = getListeners(allListeners); this.flushers = getFlushers(allListeners); this.networkCacheFlushThread.start(); }

Target:
public DotRunnableThread(final List<DotRunnable> allListeners) { this.listeners = getListeners(allListeners); this.flushers = getFlushers(allListeners); }
Source:
public void visitToken(DetailAST ast) { final DetailAST landNode = ast.findFirstToken(TokenTypes.EXPR) .findFirstToken(TokenTypes.LAND); if (landNode == null) { if (checkOnNextLine(ast)) { log(ast, MSG_KEY); } } else { final DetailAST notEqualNode = landNode.findFirstToken(TokenTypes.NOT_EQUAL); final DetailAST instanceOfNode = landNode.findFirstToken(TokenTypes.LITERAL_INSTANCEOF); if (notEqualNode != null && instanceOfNode != null && notEqualNode.findFirstToken(TokenTypes.LITERAL_NULL) != null) { final DetailAST dotNode1 = getDotNode(notEqualNode); final DetailAST dotNode2 = getDotNode(instanceOfNode); final String string1; if (dotNode1 == null) { string1 = getIdentNode(notEqualNode).getText(); } else { final DetailAST identNode1 = getIdentNode(dotNode1); string1 = getText(identNode1); } final String string2; if (dotNode2 == null) { string2 = getIdentNode(instanceOfNode).getText(); } else { final DetailAST identNode2 = getIdentNode(dotNode2); string2 = getText(identNode2); } if (string1.equals(string2)) { log(ast, MSG_KEY); } } } }

Target:
public void visitToken(DetailAST ast) { final DetailAST landNode = getExprChildNode(ast, TokenTypes.LAND); if (landNode == null) { if (checkOuterNotEqual(ast) || checkOuterInstanceOf(ast)) { log(ast, MSG_KEY); } } else { final DetailAST notEqualNode = landNode.findFirstToken(TokenTypes.NOT_EQUAL); final DetailAST instanceOfNode = landNode.findFirstToken(TokenTypes.LITERAL_INSTANCEOF); if (isTextEqual(instanceOfNode, notEqualNode)) { log(ast, MSG_KEY); } } }
Source:
@Test void testHashJoinLeftOuterJoinPushDownSort() { final String sql = "select * from\n" + "(select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp UNION ALL select ename from sales.emp) r left outer join\n" + "(select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus UNION ALL select ename from sales.bonus) s\n" + "on r.ename=s.ename\n" + "order by r.ename nulls first"; Query.create(sql) .removeRule(EnumerableRules.ENUMERABLE_MERGE_JOIN_RULE) .removeRule(EnumerableRules.ENUMERABLE_BATCH_NESTED_LOOP_JOIN_RULE) .removeRule(SortJoinTransposeRule.INSTANCE) .removeRule(SortJoinCopyRule.INSTANCE) .removeRule(EnumerableRules.ENUMERABLE_SORT_RULE) .check(); }

Target:
@Test void testHashJoinLeftOuterJoinPushDownSort() { final String sql = "select * from\n" + "(select contactno, email from customer.contact_peek) r left outer join\n" + "(select acctno, type from customer.account) s\n" + "on r.contactno=s.acctno and r.email=s.type\n" + "order by r.contactno desc, r.email desc"; Query.create(sql) .removeRule(EnumerableRules.ENUMERABLE_MERGE_JOIN_RULE) .removeRule(EnumerableRules.ENUMERABLE_BATCH_NESTED_LOOP_JOIN_RULE) .removeRule(EnumerableRules.ENUMERABLE_SORT_RULE) .check(); }
Source:
public void convertAttributeToUnique(PerunSession session, int attrId) throws InternalErrorException, AttributeNotExistsException, AttributeAlreadyMarkedUniqueException { AttributeDefinition attrDef = getAttributeDefinitionById(session, attrId); if(attrDef.isUnique()) throw new AttributeAlreadyMarkedUniqueException("Cannot convert attribute because it is already marked as unique", attrDef); if(attrDef.getNamespace().startsWith(NS_ENTITYLESS_ATTR)) throw new InternalErrorException("entityless atributes cannot be converted to unique"); if(!Arrays.asList("def","opt").contains(attrDef.getNamespace().split(":")[4])) { throw new InternalErrorException("only 'def' and 'opt' attributes can be converted to unique"); } log.info("converting attribute to unique",attrDef.getName()); attrDef.setUnique(true); this.updateAttributeDefinition(session, attrDef); long startTime = System.currentTimeMillis(); attributesManagerImpl.convertAttributeValuesToUnique(session, attrDef); long endTime = System.currentTimeMillis(); log.debug("attribute was converted to unique in ms",attrDef.getName(),(endTime-startTime)); }

Target:
public void convertAttributeToUnique(PerunSession session, int attrId) throws InternalErrorException, AttributeNotExistsException, AttributeAlreadyMarkedUniqueException { AttributeDefinition attrDef = getAttributeDefinitionById(session, attrId); if(attrDef.isUnique()) throw new AttributeAlreadyMarkedUniqueException("Cannot convert attribute because it is already marked as unique", attrDef); if(attrDef.getNamespace().startsWith(NS_ENTITYLESS_ATTR)) throw new InternalErrorException("entityless atributes cannot be converted to unique"); if(!Arrays.asList("def","opt").contains(attrDef.getNamespace().split(":")[4])) { throw new InternalErrorException("only 'def' and 'opt' attributes can be converted to unique"); } log.info("converting attribute to unique",attrDef.getName()); attrDef.setUnique(true); this.updateAttributeDefinition(session, attrDef); long startTime = System.currentTimeMillis(); attributesManagerImpl.convertAttributeValuesToUnique(session, attrDef); long endTime = System.currentTimeMillis(); log.debug("Attribute was converted to unique in ms",attrDef.getName(),(endTime-startTime)); }
Source:
public void visitSwitchStatement(SwitchStatementTree tree) { tree.cases().stream().forEach(this::checkCaseClause); super.visitSwitchStatement(tree); }

Target:
public void visitSwitchStatement(SwitchStatementTree tree) { tree.cases().forEach(this::checkCaseClause); super.visitSwitchStatement(tree); }
Source:
public void testCompanionAd() throws Exception { Log.v(TAG, "Beginning testCompanionAd"); super.playVideo(); assertTrue("Companion ad not found in preroll ad break.", toCompanionAdCheck(5000)); toEndOfAdCheck(); assertTrue("Companion ad not found in midroll ad break.", toCompanionAdCheck(35000)); toEndOfAdCheck(); assertTrue("Companion ad not found in postroll ad break.", toCompanionAdCheck(112000)); Log.v(TAG, "Finished testCompanionAd"); }

Target:
public void testCompanionAd() throws Exception { Log.v(TAG, "Beginning testCompanionAd"); super.playVideo(); assertTrue("Companion ad not found in preroll ad break.", waitForCompanionAdCheck(msecToPreroll, ADTYPE_PREROLL)); waitForEndOfAdCheck(ADTYPE_PREROLL); assertTrue("Companion ad not found in midroll ad break.", waitForCompanionAdCheck(msecToMidroll, ADTYPE_MIDROLL)); waitForEndOfAdCheck(ADTYPE_MIDROLL); assertTrue("Companion ad not found in postroll ad break.", waitForCompanionAdCheck(msecToPostroll, ADTYPE_POSTROLL)); Log.v(TAG, "Finished testCompanionAd"); }
Source:
public void accumulateTuple(Tuple.WindowedTuple<KeyValPair<KeyT, InputValT>> tuple) { KeyValPair<KeyT, InputValT> kvData = tuple.getValue(); KeyT key = kvData.getKey(); for (Window window : tuple.getWindows()) { AccumT accum = dataStorage.get(window, key); if (accum == null) { accum = accumulation.defaultAccumulatedValue(); } InputValT inputValue = kvData.getValue(); AccumT newValue = accumulation.accumulate(accum, inputValue); if (earlyTriggerMillis > 0 || lateTriggerMillis > 0) { updatedKeyStorage.put(window, key); } dataStorage.put(window, key, newValue); } }

Target:
public void accumulateTuple(Tuple.WindowedTuple<KeyValPair<KeyT, InputValT>> tuple) { KeyValPair<KeyT, InputValT> kvData = tuple.getValue(); KeyT key = kvData.getKey(); for (Window window : tuple.getWindows()) { AccumT accum = dataStorage.get(window, key); if (accum == null) { accum = accumulation.defaultAccumulatedValue(); } InputValT inputValue = kvData.getValue(); AccumT newValue = accumulation.accumulate(accum, inputValue); if ((earlyTriggerMillis > 0 || lateTriggerMillis > 0 || earlyTriggerCount > 0 || lateTriggerCount > 0) && useUpdatedKeyStorage()) { updatedKeyStorage.put(window, key); } dataStorage.put(window, key, newValue); } }
Source:
public static void removeDuplicate(NetworkTopology topology, Collection<Node> mutableExcludedNodes, List<String> mutableExcludedScopes, int ancestorGen) { if (mutableExcludedNodes == null || mutableExcludedNodes.size() == 0 || mutableExcludedScopes == null || mutableExcludedScopes.size() == 0 || topology == null) { return; } Iterator<Node> iterator = mutableExcludedNodes.iterator(); while (iterator.hasNext() && (!mutableExcludedScopes.isEmpty())) { Node node = iterator.next(); Node ancestor = topology.getAncestor(node, ancestorGen); if (ancestor == null) { LOG.warn("Fail to get ancestor generation " + ancestorGen + " of node :" + node); continue; } List<String> duplicateList = mutableExcludedScopes.stream() .filter(scope -> scope.startsWith(ancestor.getNetworkFullPath())) .collect(Collectors.toList()); mutableExcludedScopes.removeAll(duplicateList); mutableExcludedScopes.stream().forEach(scope -> { if (ancestor.getNetworkFullPath().startsWith(scope)) { iterator.remove(); } }); } }

Target:
public static void removeDuplicate(NetworkTopology topology, Collection<Node> mutableExcludedNodes, List<String> mutableExcludedScopes, int ancestorGen) { if (CollectionUtils.isEmpty(mutableExcludedNodes) || CollectionUtils.isEmpty(mutableExcludedScopes) || topology == null) { return; } Iterator<Node> iterator = mutableExcludedNodes.iterator(); while (iterator.hasNext() && (!mutableExcludedScopes.isEmpty())) { Node node = iterator.next(); Node ancestor = topology.getAncestor(node, ancestorGen); if (ancestor == null) { LOG.warn("Fail to get ancestor generation " + ancestorGen + " of node :" + node); continue; } List<String> duplicateList = mutableExcludedScopes.stream() .filter(scope -> scope.startsWith(ancestor.getNetworkFullPath())) .collect(Collectors.toList()); mutableExcludedScopes.removeAll(duplicateList); mutableExcludedScopes.stream().forEach(scope -> { if (ancestor.getNetworkFullPath().startsWith(scope)) { iterator.remove(); } }); } }
Source:
private Map<Binary, Descriptors.EnumValueDescriptor> makeLookupStructure(Descriptors.EnumDescriptor enumType) { Map<Binary, Descriptors.EnumValueDescriptor> lookupStructure = new HashMap<Binary, Descriptors.EnumValueDescriptor>(); if (extraMetadata.containsKey(METADATA_ENUM_PREFIX + enumType.getFullName())) { String enumNameNumberPairs = extraMetadata.get(METADATA_ENUM_PREFIX + enumType.getFullName()); if (StringUtils.isBlank(enumNameNumberPairs)) { LOG.info("No enum is written for " + enumType.getFullName()); return lookupStructure; } for (String enumItem : enumNameNumberPairs.split(METADATA_ENUM_ITEM_SEPARATOR)) { String[] nameAndNumber = enumItem.split(METADATA_ENUM_KEY_VALUE_SEPARATOR); if (nameAndNumber.length != 2) { throw new BadConfigurationException("Invalid enum bookkeeper from the metadata: " + enumNameNumberPairs); } lookupStructure.put(Binary.fromString(nameAndNumber[0]), enumType.findValueByNumberCreatingIfUnknown(Integer.parseInt(nameAndNumber[1]))); } } else { List<Descriptors.EnumValueDescriptor> enumValues = enumType.getValues(); for (Descriptors.EnumValueDescriptor value : enumValues) { String name = value.getName(); lookupStructure.put(Binary.fromString(name), enumType.findValueByName(name)); } } return lookupStructure; }

Target:
private Map<Binary, Descriptors.EnumValueDescriptor> makeLookupStructure(Descriptors.EnumDescriptor enumType) { Map<Binary, Descriptors.EnumValueDescriptor> lookupStructure = new HashMap<Binary, Descriptors.EnumValueDescriptor>(); if (extraMetadata.containsKey(METADATA_ENUM_PREFIX + enumType.getFullName())) { String enumNameNumberPairs = extraMetadata.get(METADATA_ENUM_PREFIX + enumType.getFullName()); if (enumNameNumberPairs == null || enumNameNumberPairs.trim().isEmpty()) { LOG.debug("No enum is written for " + enumType.getFullName()); return lookupStructure; } for (String enumItem : enumNameNumberPairs.split(METADATA_ENUM_ITEM_SEPARATOR)) { String[] nameAndNumber = enumItem.split(METADATA_ENUM_KEY_VALUE_SEPARATOR); if (nameAndNumber.length != 2) { throw new BadConfigurationException("Invalid enum bookkeeper from the metadata: " + enumNameNumberPairs); } lookupStructure.put(Binary.fromString(nameAndNumber[0]), enumType.findValueByNumberCreatingIfUnknown(Integer.parseInt(nameAndNumber[1]))); } } else { List<Descriptors.EnumValueDescriptor> enumValues = enumType.getValues(); for (Descriptors.EnumValueDescriptor value : enumValues) { String name = value.getName(); lookupStructure.put(Binary.fromString(name), enumType.findValueByName(name)); } } return lookupStructure; }
Source:
public GatewayResponse authorise(AuthorisationGatewayRequest request) { logger.info("Calling Stripe for authorisation of charge [{}]", request.getChargeExternalId()); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse .GatewayResponseBuilder .responseBuilder(); try { Response tokenResponse = createToken(request); Response sourceResponse = createSource( request, tokenResponse.readEntity(StripeTokenResponse.class).getId() ); Response authorisationResponse = createCharge( request, sourceResponse.readEntity(StripeSourcesResponse.class).getId() ); return responseBuilder.withResponse(StripeAuthorisationResponse.of(authorisationResponse)).build(); } catch(GatewayClientException e) { logger.error( "There was error calling Stripe. Reason: {}", e.getResponse().readEntity(StripeErrorResponse.class).getError().getMessage() ); return responseBuilder.withGatewayError( new GatewayError( "Stripe returned unexpected response", ErrorType.UNEXPECTED_HTTP_STATUS_CODE_FROM_GATEWAY) ).build(); } }

Target:
public GatewayResponse authorise(AuthorisationGatewayRequest request) { logger.info("Calling Stripe for authorisation of charge [{}]", request.getChargeExternalId()); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse .GatewayResponseBuilder .responseBuilder(); try { Response tokenResponse = createToken(request); Response sourceResponse = createSource( request, tokenResponse.readEntity(StripeTokenResponse.class).getId() ); Response authorisationResponse = createCharge( request, sourceResponse.readEntity(StripeSourcesResponse.class).getId() ); return responseBuilder.withResponse(StripeAuthorisationResponse.of(authorisationResponse)).build(); } catch(GatewayClientException e) { logger.error( "There was error calling Stripe. Reason: {}", e.getResponse().readEntity(StripeErrorResponse.class).getError().getMessage() ); return responseBuilder.withGatewayError( new GatewayError( "There was an internal server error. ErrorId:" + UUID.randomUUID(), ErrorType.UNEXPECTED_HTTP_STATUS_CODE_FROM_GATEWAY) ).build(); } }
Source:
public void shouldUseUpsertOnUpdate() throws IOException { String documentId = "1"; SampleEntity sampleEntity = SampleEntity.builder() .id(documentId) .message("test message") .version(System.currentTimeMillis()) .build(); Map<String, Object> doc = getResultsMapper().getEntityMapper().mapObject(sampleEntity); UpdateRequest updateRequest = new UpdateRequest() .doc(doc) .upsert(doc); UpdateQuery updateQuery = new UpdateQueryBuilder() .withClass(SampleEntity.class) .withId(documentId) .withUpdateRequest(updateRequest) .build(); elasticsearchTemplate.update(updateQuery); GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); assertThat(indexedEntity).isNotNull(); assertThat(indexedEntity.getId()).isEqualTo(documentId); }

Target:
public void shouldUseUpsertOnUpdate() throws IOException { Map<String, Object> doc = new HashMap<>(); doc.put("id", "1"); doc.put("message", "test"); UpdateRequest updateRequest = new UpdateRequest() .doc(doc) .upsert(doc); UpdateQuery updateQuery = new UpdateQueryBuilder() .withClass(SampleEntity.class) .withId("1") .withUpdateRequest(updateRequest).build(); UpdateRequest request = ((UpdateRequestBuilder) ReflectionTestUtils .invokeMethod(elasticsearchTemplate, "prepareUpdate", updateQuery)) .request(); assertThat(request).isNotNull(); assertThat(request.upsertRequest()).isNotNull(); }
Source:
public RelOptCost computeSelfCost(final RelOptPlanner planner, final RelMetadataQuery mq) { double cost = 1.0; if (queryBuilder.getFilter() != null) { cost *= 0.1; } if (queryBuilder.getGrouping() != null) { cost *= 0.5; } if (queryBuilder.getLimitSpec() != null) { cost *= 0.5; } return planner.getCostFactory().makeCost(cost, 0, 0); }

Target:
public RelOptCost computeSelfCost(final RelOptPlanner planner, final RelMetadataQuery mq) { double cost = COST_BASE; if (queryBuilder.getFilter() != null) { cost *= COST_FILTER_MULTIPLIER; } if (queryBuilder.getGrouping() != null) { cost *= COST_GROUPING_MULTIPLIER; } if (queryBuilder.getLimitSpec() != null) { cost *= COST_LIMIT_MULTIPLIER; } return planner.getCostFactory().makeCost(cost, 0, 0); }
Source:
public static TaskExecutorMemoryConfiguration create(Configuration config) { return new TaskExecutorMemoryConfiguration( getConfigurationValue(config, FRAMEWORK_HEAP_MEMORY), getConfigurationValue(config, TASK_HEAP_MEMORY), getConfigurationValue(config, FRAMEWORK_OFF_HEAP_MEMORY), getConfigurationValue(config, TASK_OFF_HEAP_MEMORY), getConfigurationValue(config, NETWORK_MEMORY_MIN), getConfigurationValue(config, NETWORK_MEMORY_MAX), config.getOptional(NETWORK_MEMORY_FRACTION).orElse(NETWORK_MEMORY_FRACTION.defaultValue()), getConfigurationValue(config, MANAGED_MEMORY_SIZE), config.getOptional(MANAGED_MEMORY_FRACTION).orElse(MANAGED_MEMORY_FRACTION.defaultValue()), getConfigurationValue(config, JVM_METASPACE), getConfigurationValue(config, JVM_OVERHEAD_MIN), getConfigurationValue(config, JVM_OVERHEAD_MAX), config.getOptional(JVM_OVERHEAD_FRACTION).orElse(JVM_OVERHEAD_FRACTION.defaultValue()), getConfigurationValue(config, TOTAL_PROCESS_MEMORY) ); }

Target:
public static TaskExecutorMemoryConfiguration create(Configuration config) { return new TaskExecutorMemoryConfiguration( getConfigurationValue(config, FRAMEWORK_HEAP_MEMORY), getConfigurationValue(config, TASK_HEAP_MEMORY), getConfigurationValue(config, FRAMEWORK_OFF_HEAP_MEMORY), getConfigurationValue(config, TASK_OFF_HEAP_MEMORY), getConfigurationValue(config, NETWORK_MEMORY_MAX), getConfigurationValue(config, MANAGED_MEMORY_SIZE), getConfigurationValue(config, JVM_METASPACE), getConfigurationValue(config, JVM_OVERHEAD_MAX), getConfigurationValue(config, TOTAL_FLINK_MEMORY), getConfigurationValue(config, TOTAL_PROCESS_MEMORY) ); }
Source:
public void containsOnlyViolations(ViolationExpectation... expectedViolations) { isNotNull(); List<ViolationExpectation> actualViolations = new ArrayList<>(); ViolationExpectationPropertiesToTest referencePropertiesToTest; if ( expectedViolations.length == 0 ) { referencePropertiesToTest = ViolationExpectationPropertiesToTest.all(); } else { referencePropertiesToTest = expectedViolations[0].propertiesToTest; for ( ViolationExpectation expectedViolation : expectedViolations ) { if ( !referencePropertiesToTest.equals( expectedViolation.propertiesToTest ) ) { throw new IllegalArgumentException( String.format( "Expected violations are not testing the properties consistently: %1$s - %2$s", expectedViolations[0], expectedViolation ) ); } } } for ( ConstraintViolation<?> violation : actual ) { actualViolations.add( new ViolationExpectation( violation, referencePropertiesToTest ) ); } Assertions.assertThat( actualViolations ).containsExactlyInAnyOrder( expectedViolations ); }

Target:
public void containsOnlyViolations(ViolationExpectation... expectedViolations) { isNotNull(); List<ViolationExpectation> actualViolations = new ArrayList<>(); ViolationExpectationPropertiesToTest referencePropertiesToTest; if ( expectedViolations.length == 0 ) { referencePropertiesToTest = ViolationExpectationPropertiesToTest.all(); } else { referencePropertiesToTest = expectedViolations[0].propertiesToTest; for ( ViolationExpectation expectedViolation : expectedViolations ) { if ( !referencePropertiesToTest.equals( expectedViolation.propertiesToTest ) ) { throw new IllegalArgumentException( String.format( "Expected violations passed in parameter must test the exact same properties but do not: %1$s != %2$s", expectedViolations[0], expectedViolation ) ); } } } for ( ConstraintViolation<?> violation : actual ) { actualViolations.add( new ViolationExpectation( violation, referencePropertiesToTest ) ); } Assertions.assertThat( actualViolations ).containsExactlyInAnyOrder( expectedViolations ); }
Source:
public byte[] serialize(String topic, StreamlineEvent streamlineEvent) { SchemaMetadata schemaMetadata = Utils.getSchemaKey(topic, false); SchemaVersionInfo schemaVersionInfo; try { schemaMetadata = this.schemaRegistryClient.getSchemaMetadataInfo(schemaMetadata.getName()).getSchemaMetadata(); schemaVersionInfo = this.schemaRegistryClient.getLatestSchemaVersionInfo(schemaMetadata.getName()); } catch (SchemaNotFoundException e) { LOG.error("Exception occured while getting SchemaVersionInfo for " + schemaMetadata, e); throw new RuntimeException(e); } if (streamlineEvent == null || streamlineEvent.isEmpty()) { return null; } else { return avroSnapshotSerializer.serialize(getAvroRecord(streamlineEvent, new Schema.Parser().parse(schemaVersionInfo.getSchemaText())), schemaMetadata); } }

Target:
public byte[] serialize(String topic, StreamlineEvent streamlineEvent) { SchemaMetadata schemaMetadata = Utils.getSchemaKey(topic, false); SchemaVersionInfo schemaVersionInfo; try { schemaMetadata = schemaRegistryClient.getSchemaMetadataInfo(schemaMetadata.getName()).getSchemaMetadata(); schemaVersionInfo = schemaRegistryClient.getLatestSchemaVersionInfo(schemaMetadata.getName()); } catch (SchemaNotFoundException e) { LOG.error("Exception occured while getting SchemaVersionInfo for " + schemaMetadata, e); throw new RuntimeException(e); } if (streamlineEvent == null || streamlineEvent.isEmpty()) { return null; } else { return avroSnapshotSerializer.serialize(getAvroRecord(streamlineEvent, new Schema.Parser().parse(schemaVersionInfo.getSchemaText())), schemaMetadata); } }
Source:
public void variantsShouldBeWrittenIntoMongoDb() throws UnknownHostException { String dbName = "VariantsShouldBeWrittenIntoMongoDb"; Variant variant = Mockito.mock(Variant.class); when(variant.getChromosome()).thenReturn("1").thenReturn("2").thenReturn("3"); when(variant.getStart()).thenReturn(1).thenReturn(2).thenReturn(3); when(variant.getReference()).thenReturn("A").thenReturn("B"); when(variant.getAlternate()).thenReturn("B").thenReturn("C"); objectMap.put("db.name", dbName); MongoOperations mongoOperations = MongoDBHelper.getMongoOperationsFromPipelineOptions(objectMap); DBCollection dbCollection = mongoOperations.getCollection(collectionName); BasicDBObject dbObject = new BasicDBObject(); when(variantToMongoDbObjectConverter.convert(any(Variant.class))).thenReturn(dbObject).thenReturn(dbObject); variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations, variantToMongoDbObjectConverter); variantMongoWriter.doWrite(Arrays.asList(variant, variant)); assertEquals(2, dbCollection.count()); JobTestUtils.cleanDBs(dbName); }

Target:
public void variantsShouldBeWrittenIntoMongoDb() throws UnknownHostException { String dbName = "VariantsShouldBeWrittenIntoMongoDb"; Variant variant = Mockito.mock(Variant.class); when(variant.getChromosome()).thenReturn("1").thenReturn("2").thenReturn("3"); when(variant.getStart()).thenReturn(1).thenReturn(2).thenReturn(3); when(variant.getReference()).thenReturn("A").thenReturn("B"); when(variant.getAlternate()).thenReturn("B").thenReturn("C"); objectMap.put(JobParametersNames.DB_NAME, dbName); MongoOperations mongoOperations = MongoDBHelper.getMongoOperationsFromPipelineOptions(objectMap); DBCollection dbCollection = mongoOperations.getCollection(collectionName); BasicDBObject dbObject = new BasicDBObject(); when(variantToMongoDbObjectConverter.convert(any(Variant.class))).thenReturn(dbObject).thenReturn(dbObject); variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations, variantToMongoDbObjectConverter); variantMongoWriter.doWrite(Arrays.asList(variant, variant)); assertEquals(2, dbCollection.count()); JobTestUtils.cleanDBs(dbName); }
Source:
private boolean validateNetworkInterfaces() { Map<String, VmNetworkInterface> interfaceNetworkMap = Entities.interfacesByNetworkName(getVm().getInterfaces()); Set<String> interfaceNetworkNames = interfaceNetworkMap.keySet(); List<Network> clusterNetworks = getNetworkDAO().getAllForCluster(getVm().getvds_group_id()); Set<String> clusterNetworksNames = Entities.objectNames(clusterNetworks); boolean returnValue; returnValue = isVmInterfacesConfigured(interfaceNetworkMap); interfaceNetworkMap.remove(null); return returnValue && isVmInterfacesAttachedToClusterNetworks(clusterNetworksNames, interfaceNetworkNames) && isVmInterfacesAttachedToVmNetworks(clusterNetworks, interfaceNetworkNames); }

Target:
private boolean validateNetworkInterfaces() { Map<String, VmNetworkInterface> interfaceNetworkMap = Entities.interfacesByNetworkName(getVm().getInterfaces()); Set<String> interfaceNetworkNames = interfaceNetworkMap.keySet(); List<Network> clusterNetworks = getNetworkDAO().getAllForCluster(getVm().getvds_group_id()); Set<String> clusterNetworksNames = Entities.objectNames(clusterNetworks); if (!isVmInterfacesConfigured(interfaceNetworkMap)) { return false; } interfaceNetworkMap.remove(null); return isVmInterfacesAttachedToClusterNetworks(clusterNetworksNames, interfaceNetworkNames) && isVmInterfacesAttachedToVmNetworks(clusterNetworks, interfaceNetworkNames); }
Source:
public void patchAddMetadataOnSectionNotExistentTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1) .withName("Collection 1") .build(); WorkspaceItem witem = WorkspaceItemBuilder.createWorkspaceItem(context, col1) .withIssueDate("2019-04-25") .withSubject("ExtraEntry") .build(); configurationService.setProperty("webui.submit.upload.required", false); context.restoreAuthSystemState(); String authToken = getAuthToken(eperson.getEmail(), password); List<Operation> addTitle = new ArrayList<Operation>(); List<Map<String, String>> values = new ArrayList<Map<String, String>>(); Map<String, String> value = new HashMap<String, String>(); value.put("value", "New Title"); values.add(value); addTitle.add(new AddOperation("/sections/not-existing-section/dc.title", values)); String patchBody = getPatchContent(addTitle); getClient(authToken).perform(patch("/api/submission/workspaceitems/" + witem.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isUnprocessableEntity()); }

Target:
public void patchAddMetadataOnSectionNotExistentTest() throws Exception { context.turnOffAuthorisationSystem(); parentCommunity = CommunityBuilder.createCommunity(context) .withName("Parent Community") .build(); Community child1 = CommunityBuilder.createSubCommunity(context, parentCommunity) .withName("Sub Community") .build(); Collection col1 = CollectionBuilder.createCollection(context, child1) .withName("Collection 1") .build(); WorkspaceItem witem = WorkspaceItemBuilder.createWorkspaceItem(context, col1) .withIssueDate("2019-04-25") .withSubject("ExtraEntry") .build(); configurationService.setProperty("webui.submit.upload.required", false); context.restoreAuthSystemState(); String authToken = getAuthToken(eperson.getEmail(), password); List<Operation> addTitle = new ArrayList<Operation>(); List<Map<String, String>> values = new ArrayList<Map<String, String>>(); Map<String, String> value = new HashMap<String, String>(); value.put("value", "New Title"); values.add(value); addTitle.add(new AddOperation("/sections/not-existing-section/dc.title", values)); String patchBody = getPatchContent(addTitle); getClient(authToken).perform(patch("/api/submission/workspaceitems/" + witem.getID()) .content(patchBody) .contentType(MediaType.APPLICATION_JSON_PATCH_JSON)) .andExpect(status().isUnprocessableEntity()); getClient(authToken).perform(get("/api/submission/workspaceitems/" + witem.getID())) .andExpect(status().isOk()) .andExpect(jsonPath("$.sections.traditionalpageone['dc.title']").doesNotExist()); }
Source:
protected Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( CVSUIMessages.RemoteFolderElement_fetchingRemoteChildren, new String[] { root.toString() }), 200); try { ICVSRemoteResource[] children = CVSUIPlugin .getPlugin() .getRepositoryManager() .getFoldersForTag(root, tag, Policy.subMonitorFor(monitor, 100)); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager() .filterResources(getWorkingSet(), children); if (tag.getType() == CVSTag.BRANCH) { return getTopLevelFoldersForChildren(children, Policy.subMonitorFor(monitor, 100)); } else { return children; } } finally { monitor.done(); } }

Target:
protected Object[] fetchChildren(Object o, IProgressMonitor monitor) throws TeamException { if (tag.getType() == CVSTag.BRANCH) { monitor = Policy.monitorFor(monitor); monitor.beginTask(NLS.bind( CVSUIMessages.RemoteFolderElement_fetchingRemoteChildren, new String[] { root.toString() }), 100); try { ICVSRemoteResource[] children = CVSUIPlugin .getPlugin() .getRepositoryManager() .getFoldersForTag(root, tag, Policy.subMonitorFor(monitor, 50)); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager() .filterResources(getWorkingSet(), children); return getTopLevelFoldersForChildren(children, Policy.subMonitorFor(monitor, 50)); } finally { monitor.done(); } } ICVSRemoteResource[] children = CVSUIPlugin.getPlugin().getRepositoryManager().getFoldersForTag(root, tag, monitor); if (getWorkingSet() != null) children = CVSUIPlugin.getPlugin().getRepositoryManager().filterResources(getWorkingSet(), children); return children; }
Source:
final Integer[] getDateValues(String filePath, Formatter formatter) { Pattern pattern = DEFAULT_PATH_PATTEN; switch (formatter) { case DEFAULT: case LOWER_DEFAULT: break; case HIVE: pattern = HIVE_PATH_PATTERN; break; default: throw new IAE("Format %s not supported", formatter); } Matcher matcher = pattern.matcher(filePath); Integer[] vals = new Integer[7]; if (matcher.matches()) { for (int i = 1; i <= matcher.groupCount(); i++) { vals[i] = (matcher.group(i) != null) ? Integer.parseInt(matcher.group(i)) : null; } } return vals; }

Target:
final Integer[] getDateValues(String filePath, Formatter formatter) { Pattern pattern = DEFAULT_PATH_PATTERN; switch (formatter) { case DEFAULT: case LOWER_DEFAULT: break; case HIVE: pattern = HIVE_PATH_PATTERN; break; default: throw new IAE("Format %s not supported", formatter); } Matcher matcher = pattern.matcher(filePath); Integer[] vals = new Integer[7]; if (matcher.matches()) { for (int i = 1; i <= matcher.groupCount(); i++) { vals[i] = (matcher.group(i) != null) ? Integer.parseInt(matcher.group(i)) : null; } } return vals; }
Source:
protected ManagedConnectionFactory createMcf(org.jboss.jca.common.api.metadata.ds.DataSource arg0, String arg1, ClassLoader arg2) throws NotFoundException, DeployException { final LocalManagedConnectionFactory managedConnectionFactory = new LocalManagedConnectionFactory(); managedConnectionFactory.setDriverClass(dataSourceConfig.getDriverClass()); if (dataSourceConfig.getUrlDelimiter() != null) { try { managedConnectionFactory.setURLDelimiter(dataSourceConfig.getUrlDelimiter()); } catch (Exception e) { throw ConnectorLogger.ROOT_LOGGER.failedToGetUrlDelimiter(e); } } if (dataSourceConfig.getDataSourceClass() != null) { managedConnectionFactory.setDataSourceClass(dataSourceConfig.getDataSourceClass()); } if (dataSourceConfig.getConnectionProperties() != null) { managedConnectionFactory.setConnectionProperties(buildConfigPropsString(dataSourceConfig .getConnectionProperties())); } if (dataSourceConfig.getConnectionUrl() != null) { managedConnectionFactory.setConnectionURL(dataSourceConfig.getConnectionUrl()); } else { managedConnectionFactory.setConnectionURL(""); } if (dataSourceConfig.getNewConnectionSql() != null) { managedConnectionFactory.setNewConnectionSQL(dataSourceConfig.getNewConnectionSql()); } if (dataSourceConfig.getUrlSelectorStrategyClassName() != null) { managedConnectionFactory.setUrlSelectorStrategyClassName(dataSourceConfig.getUrlSelectorStrategyClassName()); } setMcfProperties(managedConnectionFactory, dataSourceConfig, dataSourceConfig.getStatement()); return managedConnectionFactory; }

Target:
protected ManagedConnectionFactory createMcf(org.jboss.jca.common.api.metadata.ds.DataSource arg0, String arg1, ClassLoader arg2) throws NotFoundException, DeployException { final LocalManagedConnectionFactory managedConnectionFactory = new LocalManagedConnectionFactory(); managedConnectionFactory.setDriverClass(dataSourceConfig.getDriverClass()); if (dataSourceConfig.getUrlDelimiter() != null) { try { managedConnectionFactory.setURLDelimiter(dataSourceConfig.getUrlDelimiter()); } catch (Exception e) { throw ConnectorLogger.ROOT_LOGGER.failedToGetUrlDelimiter(e); } } if (dataSourceConfig.getDataSourceClass() != null) { managedConnectionFactory.setDataSourceClass(dataSourceConfig.getDataSourceClass()); } if (dataSourceConfig.getConnectionProperties() != null) { managedConnectionFactory.setConnectionProperties(buildConfigPropsString(dataSourceConfig .getConnectionProperties())); } if (dataSourceConfig.getConnectionUrl() != null) { managedConnectionFactory.setConnectionURL(dataSourceConfig.getConnectionUrl()); } if (dataSourceConfig.getNewConnectionSql() != null) { managedConnectionFactory.setNewConnectionSQL(dataSourceConfig.getNewConnectionSql()); } if (dataSourceConfig.getUrlSelectorStrategyClassName() != null) { managedConnectionFactory.setUrlSelectorStrategyClassName(dataSourceConfig.getUrlSelectorStrategyClassName()); } setMcfProperties(managedConnectionFactory, dataSourceConfig, dataSourceConfig.getStatement()); return managedConnectionFactory; }
Source:
public void handleEvent(JSONObject event) { String type = event.getString(MESSAGE_TYPE); String cache = event.getString(MESSAGE_CACHE); if (Strings.areEqual(CallContext.getNodeName(), event.getString(NODE_IDENTIFIER))) { return; } if (Strings.areEqual(type, TYPE_CLEAR)) { CacheManager.clearCoherentCacheLocally(cache); } else if (Strings.areEqual(type, TYPE_REMOVE)) { String key = event.getString(MESSAGE_KEY); CacheManager.removeCoherentCacheKeyLocally(cache, key); } else if (Strings.areEqual(type, TYPE_REMOVE_ALL)) { String discriminator = event.getString(MESSAGE_DISCRIMINATOR); String testValue = event.getString(MESSAGE_TEST_VALUE); CacheManager.coherentCacheRemoveAllLocally(cache, discriminator, testValue); } else if (Strings.areEqual(type, TYPE_PUT)) { String node = event.getString(MESSAGE_NODE); if (!Strings.areEqual(node, CallContext.getNodeName())) { String key = event.getString(MESSAGE_KEY); CacheManager.removeCoherentCacheKeyLocally(cache, key); } } }

Target:
public void handleEvent(JSONObject event) { String type = event.getString(MESSAGE_TYPE); String cache = event.getString(MESSAGE_CACHE); if (Strings.areEqual(CallContext.getNodeName(), event.getString(MESSAGE_NODE))) { return; } if (Strings.areEqual(type, TYPE_CLEAR)) { CacheManager.clearCoherentCacheLocally(cache); } else if (Strings.areEqual(type, TYPE_REMOVE)) { String key = event.getString(MESSAGE_KEY); CacheManager.removeCoherentCacheKeyLocally(cache, key); } else if (Strings.areEqual(type, TYPE_REMOVE_ALL)) { String discriminator = event.getString(MESSAGE_DISCRIMINATOR); String testValue = event.getString(MESSAGE_TEST_VALUE); CacheManager.coherentCacheRemoveAllLocally(cache, discriminator, testValue); } }
Source:
public void updateHybridRoleName(String roleName, String newRoleName) throws UserStoreException { if (this.isExistingRole(newRoleName)) { throw new UserStoreException("Role name: " + newRoleName + " in the system. Please pick another role name."); } String sqlStmt = HybridJDBCConstants.UPDATE_ROLE_NAME_SQL; if (sqlStmt == null) { throw new UserStoreException("The sql statement for update hybrid role name is null"); } Connection dbConnection = null; try { dbConnection = getDBConnection(); if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) { DatabaseUtil.updateDatabase(dbConnection, sqlStmt, newRoleName, roleName, tenantId); } else { DatabaseUtil.updateDatabase(dbConnection, sqlStmt, newRoleName, roleName); } dbConnection.commit(); this.userRealm.getAuthorizationManager().resetPermissionOnUpdateRole(roleName, newRoleName); } catch (SQLException e) { String errorMessage = "Error occurred while updating role name :"+roleName+"to :"+roleName; throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } }

Target:
public void updateHybridRoleName(String roleName, String newRoleName) throws UserStoreException { if (this.isExistingRole(newRoleName)) { throw new UserStoreException("Role name: " + newRoleName + " in the system. Please pick another role name."); } String sqlStmt = HybridJDBCConstants.UPDATE_ROLE_NAME_SQL; if (sqlStmt == null) { throw new UserStoreException("The sql statement for update hybrid role name is null"); } Connection dbConnection = null; try { dbConnection = getDBConnection(); if (sqlStmt.contains(UserCoreConstants.UM_TENANT_COLUMN)) { DatabaseUtil.updateDatabase(dbConnection, sqlStmt, newRoleName, roleName, tenantId); } else { DatabaseUtil.updateDatabase(dbConnection, sqlStmt, newRoleName, roleName); } dbConnection.commit(); this.userRealm.getAuthorizationManager().resetPermissionOnUpdateRole(roleName, newRoleName); } catch (SQLException e) { String errorMessage = "Error occurred while updating role name :" + roleName + "to : " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } }