auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void update(float percent) { if (userList == null) { return; } String csvData; try { csvData = formulaCSVData == null ? "" : formulaCSVData.interpretString(sprite); } catch (InterpretationException exception) { csvData = ""; } int columnToExtract; try { columnToExtract = formulaColumnToExtract == null ? 0 : formulaColumnToExtract.interpretInteger(sprite); } catch (InterpretationException interpretationException) { columnToExtract = 0; } columnToExtract--; char separator = ','; Pattern pattern = Pattern.compile("^(?:\".*?\"|[^,;]*?)([,;])"); Matcher matcher = pattern.matcher(csvData); if (matcher.find()) { separator = matcher.group(1).charAt(0); } if (separator != ',' && separator != ';') { separator = ','; } userList.reset(); boolean resetList = true; try { CSVParser parser = new CSVParserBuilder().withSeparator(separator).build(); CSVReader reader = new CSVReaderBuilder(new StringReader(csvData)).withCSVParser(parser) .build(); List<String[]> allRows = reader.readAll(); if (allRows.size() > 0 && columnToExtract >= 0) { for (String[] row : allRows) { if (row.length <= columnToExtract) { userList.addListItem(""); } else { resetList = false; userList.addListItem(row[columnToExtract]); } } if (resetList) { userList.reset(); } } } catch (IOException | CsvException exception) { userList.reset(); } }

Target:
protected void update(float percent) { if (userList == null) { return; } String csvData; try { csvData = formulaCSVData == null ? "" : formulaCSVData.interpretString(sprite); int columnToExtract; columnToExtract = formulaColumnToExtract == null ? 0 : formulaColumnToExtract.interpretInteger(sprite); columnToExtract--; char separator = ','; Pattern pattern = Pattern.compile("^(?:\".*?\"|[^,;]*?)([,;])"); Matcher matcher = pattern.matcher(csvData); if (matcher.find()) { separator = matcher.group(1).charAt(0); } if (separator != ',' && separator != ';') { separator = ','; } userList.reset(); boolean resetList = true; CSVParser parser = new CSVParserBuilder().withSeparator(separator).build(); CSVReader reader = new CSVReaderBuilder(new StringReader(csvData)).withCSVParser(parser) .build(); List<String[]> allRows = reader.readAll(); if (allRows.size() > 0 && columnToExtract >= 0) { for (String[] row : allRows) { if (row.length <= columnToExtract) { userList.addListItem(""); } else { resetList = false; userList.addListItem(row[columnToExtract]); } } if (resetList) { userList.reset(); } } } catch (IOException | CsvException | InterpretationException exception) { userList.reset(); } }
Source:
public static void logoutUser(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String userName = sharedPreferences.getString(Constants.USERNAME, Constants.NO_USERNAME); new GoogleLoginHandler((AppCompatActivity) context).getGoogleSignInClient().signOut(); LogoutTask logoutTask = new LogoutTask(context, userName); logoutTask.execute(); sharedPreferences.edit() .putString(Constants.TOKEN, Constants.NO_TOKEN) .putString(Constants.USERNAME, Constants.NO_USERNAME) .putString(Constants.GOOGLE_EXCHANGE_CODE, Constants.NO_GOOGLE_EXCHANGE_CODE) .putString(Constants.GOOGLE_EMAIL, Constants.NO_GOOGLE_EMAIL) .putString(Constants.GOOGLE_USERNAME, Constants.NO_GOOGLE_USERNAME) .putString(Constants.GOOGLE_ID, Constants.NO_GOOGLE_ID) .putString(Constants.GOOGLE_LOCALE, Constants.NO_GOOGLE_LOCALE) .putString(Constants.GOOGLE_ID_TOKEN, Constants.NO_GOOGLE_ID_TOKEN) .apply(); WebViewActivity.clearCookies(); }

Target:
public static void logoutUser(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String userName = sharedPreferences.getString(Constants.USERNAME, Constants.NO_USERNAME); GoogleLoginHandler googleLoginHandler = new GoogleLoginHandler((AppCompatActivity) context); googleLoginHandler.getGoogleSignInClient().signOut(); LogoutTask logoutTask = new LogoutTask(context, userName); logoutTask.execute(); sharedPreferences.edit() .putString(Constants.TOKEN, Constants.NO_TOKEN) .putString(Constants.USERNAME, Constants.NO_USERNAME) .putString(Constants.GOOGLE_EXCHANGE_CODE, Constants.NO_GOOGLE_EXCHANGE_CODE) .putString(Constants.GOOGLE_EMAIL, Constants.NO_GOOGLE_EMAIL) .putString(Constants.GOOGLE_USERNAME, Constants.NO_GOOGLE_USERNAME) .putString(Constants.GOOGLE_ID, Constants.NO_GOOGLE_ID) .putString(Constants.GOOGLE_LOCALE, Constants.NO_GOOGLE_LOCALE) .putString(Constants.GOOGLE_ID_TOKEN, Constants.NO_GOOGLE_ID_TOKEN) .apply(); WebViewActivity.clearCookies(); }
Source:
public Href(final CharSequence txt) { this.params = new HashMap<String, List<String>>(0); final URI link = Href.createURI(txt.toString()); final String query = link.getRawQuery(); if (query == null) { this.uri = link; } else { final String href = link.toString(); this.uri = URI.create( href.substring(0, href.length() - query.length() - 1) ); final String[] pairs = query.split("&"); for (final String pair : pairs) { final String[] parts = pair.split("=", 2); final String key = Href.decode(parts[0]); final String value; if (parts.length > 1) { value = Href.decode(parts[1]); } else { value = ""; } this.params.putIfAbsent(key, new LinkedList<String>()); this.params.get(key).add(value); } } }

Target:
public Href(final CharSequence txt) { this.params = new TreeMap<String, List<String>>(); final URI link = Href.createURI(txt.toString()); final String query = link.getRawQuery(); if (query == null) { this.uri = link; } else { final String href = link.toString(); this.uri = URI.create( href.substring(0, href.length() - query.length() - 1) ); final String[] pairs = query.split("&"); for (final String pair : pairs) { final String[] parts = pair.split("=", 2); final String key = Href.decode(parts[0]); final String value; if (parts.length > 1) { value = Href.decode(parts[1]); } else { value = ""; } if (!this.params.containsKey(key)) { this.params.put(key, new LinkedList<String>()); } this.params.get(key).add(value); } } }
Source:
private Object convertValue() { if (declaredType instanceof Class<?>) { Class<?> clazz = (Class<?>) declaredType; try { return getValueFromMap(clazz); } catch (ClassCastException e) { if (clazz.isArray()) { return handleArrayProperty(clazz); } return null; } } else if (ParameterizedType.class.isInstance(declaredType)) { return handleCollectionTypes((ParameterizedType) declaredType); } else { LOG.debug("ValueMapTypeConverter doesn't support non-class types {}", declaredType); return null; } }

Target:
private Object convertValue() { if (declaredType instanceof Class<?>) { Class<?> clazz; try { clazz = (Class<?>) declaredType; if(clazz.isArray()){ return handleArrayProperty(clazz); }else{ return getValueFromMap(clazz); } } catch (ClassCastException e) { return null; } } else if (ParameterizedType.class.isInstance(declaredType)) { return handleCollectionTypes((ParameterizedType) declaredType); } else { LOG.debug("ValueMapTypeConverter doesn't support non-class types {}", declaredType); return null; } }
Source:
public Disk get() { Disks disks = parent.list(); for (Disk disk : disks.getDisks()) { if (disk.getId().equals(diskId)) { return disk; } } return notFound(); }

Target:
public Disk get() { org.ovirt.engine.core.common.businessentities.Disk disk = parent.getDisk(asGuid(diskId)); if (disk == null) { return notFound(); } return map(disk); }
Source:
private static @CheckForNull ByteBuffer maybeTranscode(@Nonnull byte[] data, @CheckForNull String charset) { if (charset == null) { return null; } else { Charset cs = charset.isEmpty() ? Charset.defaultCharset() : Charset.forName(charset); if (cs.equals(StandardCharsets.UTF_8)) { return null; } else { return StandardCharsets.UTF_8.encode(cs.decode(ByteBuffer.wrap(data))); } } }

Target:
private static @CheckForNull ByteBuffer maybeTranscode(@Nonnull byte[] data, @CheckForNull String charset) { Charset cs = transcodingCharset(charset); if (cs == null) { return null; } else { return StandardCharsets.UTF_8.encode(cs.decode(ByteBuffer.wrap(data))); } }
Source:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) throws PaymentApiException { final PaymentPluginApi pluginApi = getPaymentPluginApi(pluginName); final Pagination<PaymentTransactionInfoPlugin> paymentTransactionInfoPlugins; try { paymentTransactionInfoPlugins = pluginApi.searchPayments(searchKey, offset, limit, properties, tenantContext); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(e, ErrorCode.PAYMENT_PLUGIN_SEARCH_PAYMENTS, pluginName, searchKey); } final Multimap<UUID, PaymentTransactionInfoPlugin> payments = HashMultimap.<UUID, PaymentTransactionInfoPlugin>create(); for (final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin : paymentTransactionInfoPlugins) { payments.put(paymentTransactionInfoPlugin.getKbPaymentId(), paymentTransactionInfoPlugin); } final Collection<Payment> results = new LinkedList<Payment>(); for (final UUID paymentId : payments.keys()) { final Payment result = toPayment(paymentId, withPluginInfo ? payments.get(paymentId) : ImmutableList.<PaymentTransactionInfoPlugin>of(), withAttempts, internalTenantContext); if (result != null) { results.add(result); } } return new DefaultPagination<Payment>(paymentTransactionInfoPlugins, limit, results.iterator()); }

Target:
public Pagination<Payment> searchPayments(final String searchKey, final Long offset, final Long limit, final String pluginName, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext tenantContext, final InternalTenantContext internalTenantContext) throws PaymentApiException { final PaymentPluginApi pluginApi = getPaymentPluginApi(pluginName); final Pagination<PaymentTransactionInfoPlugin> paymentTransactionInfoPlugins; try { paymentTransactionInfoPlugins = pluginApi.searchPayments(searchKey, offset, limit, properties, tenantContext); } catch (final PaymentPluginApiException e) { throw new PaymentApiException(e, ErrorCode.PAYMENT_PLUGIN_SEARCH_PAYMENTS, pluginName, searchKey); } final Multimap<UUID, PaymentTransactionInfoPlugin> payments = HashMultimap.<UUID, PaymentTransactionInfoPlugin>create(); for (final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin : paymentTransactionInfoPlugins) { if (paymentTransactionInfoPlugin.getKbPaymentId() == null) { log.debug("Plugin returned a payment without a kbPaymentId for searchKey {}", pluginName, searchKey); } else { payments.put(paymentTransactionInfoPlugin.getKbPaymentId(), paymentTransactionInfoPlugin); } } final Collection<Payment> results = new LinkedList<Payment>(); for (final UUID paymentId : payments.keys()) { final Payment result = toPayment(paymentId, withPluginInfo ? payments.get(paymentId) : ImmutableList.<PaymentTransactionInfoPlugin>of(), withAttempts, internalTenantContext); if (result != null) { results.add(result); } } return new DefaultPagination<Payment>(paymentTransactionInfoPlugins, limit, results.iterator()); }
Source:
public Optional<PlanNode> apply(PlanNode node, Context context) { Set<Rule> matching = Sets.filter(ruleSet.rules(), rule -> rule.getPattern().matches(node)); return Optional.ofNullable(Iterables.getOnlyElement(matching, null)) .flatMap(rule -> rule.apply(node, context)); }

Target:
public Optional<PlanNode> apply(PlanNode node, Context context) { Set<Rule> matching = ruleSet.rules().stream().filter(rule -> rule.getPattern().matches(node)).collect(toSet()); if (matching.size() == 0) { return empty(); } return getOnlyElement(matching).apply(node, context); }
Source:
public void markAsModified(Integer updatedBy, Date updatedAt) { Map<String, Object> params = new HashMap<>(); params.put("updated_at", updatedAt); params.put("updated_by", updatedBy); int affected = jdbcTemplate.update( markAsModifiedSql, params ); Validate.validState( affected == 1, "Unexpected number of affected rows after updating collections: %d", affected ); }

Target:
public void markAsModified(Integer updatedBy, Date updatedAt) { Map<String, Object> params = new HashMap<>(); params.put("updated_at", updatedAt); params.put("updated_by", updatedBy); int affected = jdbcTemplate.update( markAsModifiedSql, params ); Validate.validState( affected == 1, "Unexpected number of affected rows after updating collection: %d", affected ); }
Source:
private static void initVimKeys() { KeyMap km = CodeMirror.cloneKeyMap("vim"); for (String s : new String[] {"A", "C", "O", "R", "U", "Ctrl-C"}) { km.remove(s); } CodeMirror.addKeyMap("vim_ro", km); }

Target:
private static void initVimKeys() { KeyMap km = CodeMirror.cloneKeyMap("vim"); for (String s : new String[] {"A", "C", "O", "R", "U", "Ctrl-C"}) { km.remove(s); } CodeMirror.addKeyMap("vim_ro", km); CodeMirror.mapVimKey("j", "gj"); CodeMirror.mapVimKey("k", "gk"); CodeMirror.mapVimKey("Down", "gj"); CodeMirror.mapVimKey("Up", "gk"); }
Source:
public TimeDetectorStrategyCallbackImpl(@NonNull Context context) { mContext = context; mContentResolver = context.getContentResolver(); PowerManager powerManager = context.getSystemService(PowerManager.class); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mAlarmManager = context.getSystemService(AlarmManager.class); mSystemClockUpdateThreshold = SystemProperties.getInt("ro.time_detector_update_diff", SYSTEM_CLOCK_UPDATE_THRESHOLD_DEFAULT); }

Target:
public TimeDetectorStrategyCallbackImpl(@NonNull Context context) { mContext = Objects.requireNonNull(context); mContentResolver = Objects.requireNonNull(context.getContentResolver()); PowerManager powerManager = context.getSystemService(PowerManager.class); mWakeLock = Objects.requireNonNull( powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG)); mAlarmManager = Objects.requireNonNull(context.getSystemService(AlarmManager.class)); mSystemClockUpdateThresholdMillis = SystemProperties.getInt("ro.sys.time_detector_update_diff", SYSTEM_CLOCK_UPDATE_THRESHOLD_MILLIS_DEFAULT); }
Source:
public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; if (!knownSensorAccuracies.contains(sensor)) { onAccuracyChanged(sensor, event.accuracy); } int valuesViewId; if (sensor == accelSensor) { valuesViewId = R.id.diagnose_accelerometer_values_txt; } else if (sensor == magSensor) { valuesViewId = R.id.diagnose_compass_values_txt; } else if (sensor == gyroSensor) { valuesViewId = R.id.diagnose_gyro_values_txt; } else if (sensor == rotationVectorSensor) { valuesViewId = R.id.diagnose_rotation_values_txt; } else if (sensor == lightSensor) { valuesViewId = R.id.diagnose_light_values_txt; } else { Log.e(TAG, "Receiving values for unknown sensor " + sensor); return; } float[] values = event.values; setArrayValuesInUi(valuesViewId, values); if (sensor == rotationVectorSensor) { float[] matrix = new float[9]; SensorManager.getRotationMatrixFromVector(matrix, event.values); for (int row = 0; row < 3; ++row) { switch(row) { case 0: valuesViewId = R.id.diagnose_rotation_matrix_row1_txt; break; case 1: valuesViewId = R.id.diagnose_rotation_matrix_row2_txt; break; case 2: default: valuesViewId = R.id.diagnose_rotation_matrix_row3_txt; } float[] rowValues = new float[3]; System.arraycopy(matrix, row * 3 + 0, rowValues, 0, 3); setArrayValuesInUi(valuesViewId, rowValues); } } }

Target:
public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; if (!knownSensorAccuracies.contains(sensor)) { onAccuracyChanged(sensor, event.accuracy); } int valuesViewId; if (sensor == accelSensor) { valuesViewId = R.id.diagnose_accelerometer_values_txt; } else if (sensor == magSensor) { valuesViewId = R.id.diagnose_compass_values_txt; } else if (sensor == gyroSensor) { valuesViewId = R.id.diagnose_gyro_values_txt; } else if (sensor == rotationVectorSensor) { valuesViewId = R.id.diagnose_rotation_values_txt; } else if (sensor == lightSensor) { valuesViewId = R.id.diagnose_light_values_txt; } else { Log.e(TAG, "Receiving values for unknown sensor " + sensor); return; } float[] values = event.values; setArrayValuesInUi(valuesViewId, values); if (sensor == rotationVectorSensor) { float[] matrix = new float[9]; SensorManager.getRotationMatrixFromVector(matrix, event.values); for (int row = 0; row < 3; ++row) { switch(row) { case 0: valuesViewId = R.id.diagnose_rotation_matrix_row1_txt; break; case 1: valuesViewId = R.id.diagnose_rotation_matrix_row2_txt; break; case 2: default: valuesViewId = R.id.diagnose_rotation_matrix_row3_txt; } float[] rowValues = new float[3]; for (int col = 0; col < 3; ++col) { rowValues[col] = matrix[row * 3 + col]; } setArrayValuesInUi(valuesViewId, rowValues); } } }
Source:
public Boolean get(HttpServletRequest request, HttpServletResponse response) { if (this.isHTTPSForwardedProtoResolver.get(request, response)) { return false; } return this.secureRequiredExceptForLocalhostResolver.get(request, response); }

Target:
public Boolean get(HttpServletRequest request, HttpServletResponse response) { String xForwardedProtoValue = request.getHeader(HEADER_FORWARDED_PROTO); return HTTPS.equalsIgnoreCase(xForwardedProtoValue); }
Source:
public static Datum createFromInt4(DataType type, int val) { switch (type.getType()) { case INT4: return new Int4Datum(val); case DATE: return new DateDatum(val); default: throw new TajoRuntimeException(Errors.ResultCode.UNSUPPORTED_DATATYPE, type.getType().name()); } }

Target:
public static Datum createFromInt4(DataType type, int val) { switch (type.getType()) { case INT4: return new Int4Datum(val); case DATE: return new DateDatum(val); default: throw new TajoRuntimeException(new UnsupportedDataTypeException(type.getType().name())); } }
Source:
private void loadIncludedFeatures(Feature feature, FeatureParser featureParser, Map<String, Feature> features, IProgressMonitor monitor) throws ProvisionException { FeatureEntry[] featureEntries = feature.getEntries(); for (FeatureEntry featureEntrie : featureEntries) { if (monitor.isCanceled()) throw new OperationCanceledException(); FeatureEntry entry = featureEntrie; if (entry.isRequires() || entry.isPlugin()) continue; String key = entry.getId() + VERSION_SEPARATOR + entry.getVersion(); if (features.containsKey(key)) continue; URI includedFeatureURI = getFeatureURI(entry.getId(), entry.getVersion()); Feature includedFeature = parseFeature(featureParser, includedFeatureURI, monitor); if (includedFeature == null) { LogHelper.log(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.ErrorReadingFeature, includedFeatureURI))); } else { features.put(key, includedFeature); loadIncludedFeatures(includedFeature, featureParser, features, monitor); } } }

Target:
private void loadIncludedFeatures(Feature feature, FeatureParser featureParser, Map<String, Feature> features, IProgressMonitor monitor) throws ProvisionException { FeatureEntry[] featureEntries = feature.getEntries(); for (FeatureEntry featureEntry : featureEntries) { if (monitor.isCanceled()) throw new OperationCanceledException(); FeatureEntry entry = featureEntry; if (entry.isRequires() || entry.isPlugin()) continue; String key = entry.getId() + VERSION_SEPARATOR + entry.getVersion(); if (features.containsKey(key)) continue; URI includedFeatureURI = getFeatureURI(entry.getId(), entry.getVersion()); Feature includedFeature = parseFeature(featureParser, includedFeatureURI, monitor); if (includedFeature == null) { LogHelper.log(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.ErrorReadingFeature, includedFeatureURI))); } else { features.put(key, includedFeature); loadIncludedFeatures(includedFeature, featureParser, features, monitor); } } }
Source:
public void init(Map<String, String> options, ConfigurationSource cfg) { super.initCfg(cfg); FormattingPreferences prefs = new FormattingPreferences(); String maxLineLength = options.get("maxLineLength"); String wrapLongLines = options.get("wrapLongLines"); String tabInsteadOfSpaces = options.get("tabInsteadOfSpaces"); String tabWidth = options.get("tabWidth"); String splitMultiAttrs = options.get("splitMultiAttrs"); String wellFormedValidation = options.get("wellFormedValidation"); prefs.setMaxLineLength(maxLineLength != null ? Integer.valueOf(maxLineLength) : null); prefs.setWrapLongLines(wrapLongLines != null ? Boolean.valueOf(wrapLongLines) : null); prefs.setTabInsteadOfSpaces(tabInsteadOfSpaces != null ? Boolean.valueOf(tabInsteadOfSpaces) : null); prefs.setTabWidth(tabWidth != null ? Integer.valueOf(tabWidth) : null); prefs.setSplitMultiAttrs(splitMultiAttrs != null ? Boolean.valueOf(splitMultiAttrs) : null); if (wellFormedValidation != null) prefs.setWellFormedValidation(wellFormedValidation); this.formatter = new XmlDocumentFormatter(options.getOrDefault("lineending", System.lineSeparator()), prefs); }

Target:
public void init(Map<String, String> options, ConfigurationSource cfg) { super.initCfg(cfg); FormattingPreferences prefs = new FormattingPreferences(); String maxLineLength = options.get("maxLineLength"); String wrapLongLines = options.get("wrapLongLines"); String tabInsteadOfSpaces = options.get("tabInsteadOfSpaces"); String tabWidth = options.get("tabWidth"); String splitMultiAttrs = options.get("splitMultiAttrs"); String wellFormedValidation = options.get("wellFormedValidation"); prefs.setMaxLineLength(maxLineLength != null ? Integer.valueOf(maxLineLength) : null); prefs.setWrapLongLines(wrapLongLines != null ? Boolean.valueOf(wrapLongLines) : null); prefs.setTabInsteadOfSpaces(tabInsteadOfSpaces != null ? Boolean.valueOf(tabInsteadOfSpaces) : null); prefs.setTabWidth(tabWidth != null ? Integer.valueOf(tabWidth) : null); prefs.setSplitMultiAttrs(splitMultiAttrs != null ? Boolean.valueOf(splitMultiAttrs) : null); if (wellFormedValidation != null) { prefs.setWellFormedValidation(wellFormedValidation); } this.formatter = new XmlDocumentFormatter(options.getOrDefault("lineending", System.lineSeparator()), prefs); }
Source:
public void doCapture_shouldCaptureAChargeForANonSandboxAccount() throws Exception { String gatewayTxId = "theTxId"; ChargeEntity charge = createNewChargeWith("worldpay",1L, AUTHORISATION_SUCCESS, gatewayTxId); ChargeEntity chargeSpy = spy(charge); mockChargeDaoOperations(chargeSpy); worldpayWillRespondWithSuccess(gatewayTxId, null); when(mockedProviders.byName(charge.getPaymentGatewayName())).thenReturn(mockedPaymentProvider); GatewayResponse response = cardCaptureService.doCapture(charge.getExternalId()); assertThat(response.isSuccessful(), is(true)); InOrder inOrder = Mockito.inOrder(chargeSpy); inOrder.verify(chargeSpy).setStatus(CAPTURE_READY); inOrder.verify(chargeSpy).setStatus(CAPTURE_SUBMITTED); ArgumentCaptor<ChargeEntity> chargeEntityCaptor = ArgumentCaptor.forClass(ChargeEntity.class); verify(mockedChargeEventDao).persistChargeEventOf(chargeEntityCaptor.capture(), eq(Optional.empty())); verify(mockPaymentRequestDao).updateChargeTransactionStatus(charge.getExternalId(), CAPTURE_READY); verify(mockPaymentRequestDao).updateChargeTransactionStatus(charge.getExternalId(), CAPTURE_SUBMITTED); assertThat(chargeEntityCaptor.getValue().getStatus(), is(CAPTURE_SUBMITTED.getValue())); ArgumentCaptor<CaptureGatewayRequest> request = ArgumentCaptor.forClass(CaptureGatewayRequest.class); verify(mockedPaymentProvider, times(1)).capture(request.capture()); assertThat(request.getValue().getTransactionId(), is(gatewayTxId)); verify(mockUserNotificationService).notifyPaymentSuccessEmail(chargeSpy); }

Target:
public void doCapture_shouldCaptureAChargeForANonSandboxAccount() throws Exception { String gatewayTxId = "theTxId"; ChargeEntity charge = createNewChargeWith("worldpay",1L, AUTHORISATION_SUCCESS, gatewayTxId); ChargeEntity chargeSpy = spy(charge); mockChargeDaoOperations(chargeSpy); worldpayWillRespondWithSuccess(gatewayTxId, null); when(mockedProviders.byName(charge.getPaymentGatewayName())).thenReturn(mockedPaymentProvider); GatewayResponse response = cardCaptureService.doCapture(charge.getExternalId()); assertThat(response.isSuccessful(), is(true)); InOrder inOrder = Mockito.inOrder(chargeSpy); inOrder.verify(chargeSpy).setStatus(CAPTURE_READY); inOrder.verify(chargeSpy).setStatus(CAPTURE_SUBMITTED); ArgumentCaptor<ChargeEntity> chargeEntityCaptor = ArgumentCaptor.forClass(ChargeEntity.class); verify(mockedChargeEventDao).persistChargeEventOf(chargeEntityCaptor.capture(), eq(Optional.empty())); InOrder inOrderVerifier = inOrder(mockStatusUpdater); inOrderVerifier.verify(mockStatusUpdater).updateChargeTransactionStatus(charge.getExternalId(), CAPTURE_READY); inOrderVerifier.verify(mockStatusUpdater).updateChargeTransactionStatus(charge.getExternalId(), CAPTURE_SUBMITTED); assertThat(chargeEntityCaptor.getValue().getStatus(), is(CAPTURE_SUBMITTED.getValue())); ArgumentCaptor<CaptureGatewayRequest> request = ArgumentCaptor.forClass(CaptureGatewayRequest.class); verify(mockedPaymentProvider, times(1)).capture(request.capture()); assertThat(request.getValue().getTransactionId(), is(gatewayTxId)); verify(mockUserNotificationService).notifyPaymentSuccessEmail(chargeSpy); }
Source:
public void loadScript(File file) throws FileNotFoundException, ScriptException { logger.info("Loading Script " + file.getName()); String extension = getFileExtension(file); ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByExtension(extension); if (engine != null) { try { engine.put("RuleSet", RuleSet.class); engine.put("Rule", Rule.class); engine.put("State", State.class); engine.put("Command", Command.class); engine.put("ChangedEventTrigger", ChangedEventTrigger.class); engine.put("CommandEventTrigger", CommandEventTrigger.class); engine.put("Event", Event.class); engine.put("EventTrigger", EventTrigger.class); engine.put("ShutdownTrigger", ShutdownTrigger.class); engine.put("StartupTrigger", StartupTrigger.class); engine.put("TimerTrigger", TimerTrigger.class); engine.put("TriggerType", TriggerType.class); engine.put("ItemRegistry", scriptManager.getItemRegistry()); engine.put("DateTime", org.joda.time.DateTime.class); engine.put("oh", Openhab.class); engine.put("DateTimeType", DateTimeType.class); engine.put("DecimalType", DecimalType.class); engine.put("HSBType", HSBType.class); engine.put("IncreaseDecreaseType", IncreaseDecreaseType.class); engine.put("OnOffType", OnOffType.class); engine.put("OpenClosedType", OpenClosedType.class); engine.put("PercentType", PercentType.class); engine.put("PointType", PointType.class); engine.put("StopMoveType", StopMoveType.class); engine.put("UpDownType", UpDownType.class); engine.put("StringType", StringType.class); engine.eval(new FileReader(file)); Invocable inv = (Invocable) engine; RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules"); rules.addAll(ruleSet.getRules()); } catch (Exception e) { logger.error("error loading script " + file.getName(), e); } } }

Target:
public void loadScript(File file) throws FileNotFoundException, ScriptException, NoSuchMethodException { logger.info("Loading Script " + file.getName()); String extension = getFileExtension(file); ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByExtension(extension); if (engine != null) { initializeSciptGlobals(); engine.eval(new FileReader(file)); Invocable inv = (Invocable) engine; RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules"); rules.addAll(ruleSet.getRules()); } }
Source:
public static void setUp() { rand = new Random(); CacheFactory cf = new CacheFactory(); cf.set(LOG_LEVEL, "info"); cf.set(MCAST_PORT, "0"); cf.set(LOCATORS, ""); cache = cf.create(); port = AvailablePortHelper.getRandomAvailableTCPPort(); server = new GeodeRedisServer("localhost", port); client = new Jedis("localhost", port, 100000); server.start(); }

Target:
public static void setUp() { rand = new Random(); CacheFactory cacheFactory = new CacheFactory(); cacheFactory.set(LOG_LEVEL, "info"); cacheFactory.set(MCAST_PORT, "0"); cacheFactory.set(LOCATORS, ""); cache = cacheFactory.create(); port = AvailablePortHelper.getRandomAvailableTCPPort(); server = new GeodeRedisServer("localhost", port); client = new Jedis("localhost", port, 100000); server.start(); }
Source:
public int getBatchSize() { return getContextValue("batchSize") == null ? DEFAULT_BATCH_SIZE : Integer.parseInt(getContextValue("batchSize").toString()); }

Target:
public int getBatchSize() { return getContextValue("batchSize") == null ? DEFAULT_BATCH_SIZE : (Integer.parseInt(getContextValue("batchSize").toString()) > 0 ? Integer.parseInt(getContextValue("batchSize").toString()) : DEFAULT_BATCH_SIZE); }
Source:
private CqlQuery constructQuery(TableReference tableRef, byte[] metadata) { StringBuilder queryBuilder = new StringBuilder(); TableMetadata tableMetadata = CassandraKeyValueServices.getMetadataOrDefaultToGeneric(metadata); boolean appendHeavyReadLight = tableMetadata.isAppendHeavyAndReadLight(); Map<String, String> settings = new HashMap<>(); settings.put("bloom_filter_fp_chance", falsePositive(tableMetadata.hasNegativeLookups(), appendHeavyReadLight)); settings.put("caching", "'KEYS_ONLY'"); settings.put("compaction", getCompaction(appendHeavyReadLight)); settings.put("compression", getCompression(tableMetadata.getExplicitCompressionBlockSizeKB())); settings.put("gc_grace_seconds", Integer.toString(config.gcGraceSeconds())); settings.put("id", "'%s'"); settings.put("populate_io_cache_on_flush", cachePriorityIsHottest(tableMetadata)); settings.put("speculative_retry", "'NONE'"); queryBuilder.append("CREATE TABLE IF NOT EXISTS \"%s\".\"%s\"" + " ( " + ROW + " blob, " + COLUMN + " blob, " + TIMESTAMP + " bigint, " + VALUE + " blob, " + "PRIMARY KEY (" + ROW + ", " + COLUMN + ", " + TIMESTAMP + ")) " + "WITH COMPACT STORAGE "); settings.forEach((option, value) -> queryBuilder.append("AND " + option + " = " + value + " ")); queryBuilder.append("AND CLUSTERING ORDER BY (" + COLUMN + " ASC, " + TIMESTAMP + " ASC) "); return CqlQuery.builder() .safeQueryFormat(queryBuilder.toString()) .addArgs( SafeArg.of("keyspace", config.getKeyspaceOrThrow()), SafeArg.of("internalTableName", CassandraKeyValueServiceImpl.internalTableName(tableRef)), SafeArg.of("cfId", getUuidForTable(tableRef))) .build(); }

Target:
private CqlQuery constructQuery(TableReference tableRef, byte[] metadata) { TableMetadata tableMetadata = CassandraKeyValueServices.getMetadataOrDefaultToGeneric(metadata); boolean appendHeavyReadLight = tableMetadata.isAppendHeavyAndReadLight(); String keyspace = wrapInQuotes(config.getKeyspaceOrThrow()); String internalTableName = wrapInQuotes(CassandraKeyValueServiceImpl.internalTableName(tableRef)); String query = SchemaBuilder.createTable(keyspace, internalTableName) .ifNotExists() .addPartitionKey(ROW, DataType.blob()) .addClusteringColumn(COLUMN, DataType.blob()) .addClusteringColumn(TIMESTAMP, DataType.bigint()) .addColumn(VALUE, DataType.blob()) .withOptions() .bloomFilterFPChance(falsePositive(tableMetadata.hasNegativeLookups(), appendHeavyReadLight)) .caching(SchemaBuilder.Caching.KEYS_ONLY) .compactionOptions(getCompaction(appendHeavyReadLight)) .compactStorage() .compressionOptions(getCompression(tableMetadata.getExplicitCompressionBlockSizeKB())) .dcLocalReadRepairChance(0.1) .gcGraceSeconds(config.gcGraceSeconds()) .minIndexInterval(128) .maxIndexInterval(2048) .populateIOCacheOnFlush(tableMetadata.getCachePriority() == CachePriority.HOTTEST) .speculativeRetry(SchemaBuilder.noSpeculativeRetry()) .clusteringOrder(COLUMN, SchemaBuilder.Direction.ASC) .clusteringOrder(TIMESTAMP, SchemaBuilder.Direction.ASC) .buildInternal(); return CqlQuery.builder() .safeQueryFormat(query + " AND id = '%s'") .addArgs(SafeArg.of("cfId", getUuidForTable(tableRef))) .build(); }
Source:
protected DefaultIndexBuilder fillIndexBuilder(Path path) throws Exception { final KieProject project = getProject(path); if (project == null) { logger.error("Unable to index " + path.toUri().toString() + ": project could not be resolved."); return null; } final Package pkg = getPackage(path); if (pkg == null) { logger.error("Unable to index " + path.toUri().toString() + ": package could not be resolved."); return null; } final DefaultIndexBuilder builder = new DefaultIndexBuilder(Paths.convert(path).getFileName(), project, pkg); String formContent = ioService.readAllString(path); FormDefinition formDefinition = formDefinitionSerializer.deserialize(formContent); if (formDefinition != null) { builder.setPackageName(pkg.getPackageName()); Resource resParts = new Resource(formDefinition.getName(), ResourceType.FORM); FormDefinitionVisitor visitor = new FormDefinitionVisitor(resParts); visitor.visit(formDefinition); addReferencedResourcesToIndexBuilder(builder, visitor); FormModel model = formDefinition.getModel(); if (model != null) { FormModelVisitorProvider provider = visitorProviders.get(model.getClass()); if (provider != null) { FormModelVisitor modelVisitor = provider.getVisitor(); modelVisitor.index(model); addReferencedResourcesToIndexBuilder(builder, modelVisitor); } } } else { logger.error("Unable to read FormDefinition on " + path.toUri().toString() + "."); return null; } return builder; }

Target:
protected DefaultIndexBuilder fillIndexBuilder(Path path) throws Exception { final DefaultIndexBuilder builder = getIndexBuilder(path); if (builder == null) { return null; } String formContent = ioService.readAllString(path); FormDefinition formDefinition = formDefinitionSerializer.deserialize(formContent); if (formDefinition != null) { Resource resParts = new Resource(formDefinition.getName(), ResourceType.FORM); FormDefinitionVisitor visitor = new FormDefinitionVisitor(resParts); visitor.visit(formDefinition); addReferencedResourcesToIndexBuilder(builder, visitor); FormModel model = formDefinition.getModel(); if (model != null) { FormModelVisitorProvider provider = visitorProviders.get(model.getClass()); if (provider != null) { FormModelVisitor modelVisitor = provider.getVisitor(); modelVisitor.index(model); addReferencedResourcesToIndexBuilder(builder, modelVisitor); } } } else { logger.error("Unable to read FormDefinition on " + path.toUri().toString() + "."); return null; } return builder; }
Source:
public void registerCriticalComponent(CriticalComponent criticalComponent) { final CriticalComponentImpl component = new CriticalComponentImpl(criticalComponent); boolean existing = false; for (CriticalComponentImpl csi : this.criticalServiceList) { if (criticalComponent.equals(csi.getCriticalComponent())) { existing = true; } } if (!existing) { this.criticalServiceList.add(component); } logger.debug("Added " + criticalComponent.getCriticalComponentName() + ", with timeout = " + criticalComponent.getCriticalComponentTimeout() + ", list contains " + this.criticalServiceList.size() + " critical services"); }

Target:
public void registerCriticalComponent(CriticalComponent criticalComponent) { final CriticalComponentImpl component = new CriticalComponentImpl(criticalComponent); boolean existing = false; for (CriticalComponentImpl csi : this.criticalComponentList) { if (criticalComponent.equals(csi.getCriticalComponent())) { existing = true; break; } } if (!existing) { this.criticalComponentList.add(component); } logger.debug(new StringBuilder("Added ").append(criticalComponent.getCriticalComponentName()) .append(", with timeout = ").append(criticalComponent.getCriticalComponentTimeout()) .append(", list contains ").append(this.criticalComponentList.size()).append(" critical services") .toString()); }
Source:
private synchronized void authorize(Instant expiry) { if(expiringSAMLAuth == null) throw new MarkLogicInternalException("ExpiringSAMLAuth cannot be null"); if(expiry!=null && expiry!=expiringSAMLAuth.getExpiry()) return; expiringSAMLAuth = authorizer.apply(expiringSAMLAuth); if(expiringSAMLAuth==null) throw new IllegalArgumentException("SAML Authentication cannot be null"); if(expiringSAMLAuth.getAuthorizationToken() == null) throw new IllegalArgumentException("SAML Authentication token cannot be null"); authorizationTokenValue = expiringSAMLAuth.getAuthorizationToken(); if(expiringSAMLAuth.getExpiry() == null) throw new IllegalArgumentException("SAML authentication does not have expiry value."); threshold = Instant.now().plusSeconds((expiringSAMLAuth.getExpiry().getEpochSecond())/2); }

Target:
private synchronized void authorize(Instant expiry) { if(expiry == null && expiringSAMLAuth != null) { return; } if(expiry!=null && expiry!=expiringSAMLAuth.getExpiry()) { return; } expiringSAMLAuth = authorizer.apply(expiringSAMLAuth); if(expiringSAMLAuth==null) { throw new IllegalArgumentException("SAML Authentication cannot be null"); } if(expiringSAMLAuth.getAuthorizationToken() == null) { throw new IllegalArgumentException("SAML Authentication token cannot be null"); } authorizationTokenValue = expiringSAMLAuth.getAuthorizationToken(); if(expiringSAMLAuth.getExpiry() == null) { throw new IllegalArgumentException("SAML authentication does not have expiry value."); } if(expiringSAMLAuth.getExpiry().isBefore(Instant.now())) { throw new IllegalArgumentException("SAML authentication token has expired."); } long current = Instant.now().getEpochSecond(); threshold = current+ (expiringSAMLAuth.getExpiry().getEpochSecond() - current)/2; }
Source:
public Optional<SanitizedSecret> getSanitizedSecretFor(Client client, String name, String version) { checkNotNull(client); checkArgument(!name.isEmpty()); checkNotNull(version); return (Optional<SanitizedSecret>)dslContext.transactionResult(configuration -> { Optional<SecretSeries> secretSeries = getSecretSeriesFor(client, name); if (!secretSeries.isPresent()) { return Optional.empty(); } Optional<SecretContent> secretContent = secretContentDAO.getSecretContentBySecretIdAndVersion( secretSeries.get().getId(), version); if (!secretContent.isPresent()) { return Optional.empty(); } SecretSeriesAndContent seriesAndContent = SecretSeriesAndContent.of( secretSeries.get(), secretContent.get()); return Optional.of(SanitizedSecret.fromSecretSeriesAndContent(seriesAndContent)); }); }

Target:
public Optional<SanitizedSecret> getSanitizedSecretFor(Client client, String name, String version) { checkNotNull(client); checkArgument(!name.isEmpty()); checkNotNull(version); return dslContext.<Optional<SanitizedSecret>>transactionResult(configuration -> { Optional<SecretSeries> secretSeries = getSecretSeriesFor(client, name); if (!secretSeries.isPresent()) { return Optional.empty(); } Optional<SecretContent> secretContent = secretContentDAO.getSecretContentBySecretIdAndVersion( secretSeries.get().getId(), version); if (!secretContent.isPresent()) { return Optional.empty(); } SecretSeriesAndContent seriesAndContent = SecretSeriesAndContent.of( secretSeries.get(), secretContent.get()); return Optional.of(SanitizedSecret.fromSecretSeriesAndContent(seriesAndContent)); }); }
Source:
public ValidationResult passthroughProfileIsSupported() { StoragePool dataCenter = dcDao.get(getNetwork().getDataCenterId()); Version dcCompVer = dataCenter.getCompatibilityVersion(); return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_PASSTHROUGH_PROFILE_NOT_SUPPORTED) .when(vnicProfile.isPassthrough() && !FeatureSupported.sriov(dcCompVer)); }

Target:
public ValidationResult passthroughProfileIsSupported() { StoragePool dataCenter = dcDao.get(getNetwork().getDataCenterId()); Version dcCompatibilityVersion = dataCenter.getCompatibilityVersion(); return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_PASSTHROUGH_PROFILE_NOT_SUPPORTED) .when(vnicProfile.isPassthrough() && !FeatureSupported.sriov(dcCompatibilityVersion)); }
Source:
private org.apache.hadoop.conf.Configuration getHadoopConfiguration() { org.apache.hadoop.conf.Configuration configuration = new org.apache.hadoop.conf.Configuration(); for (Object entrySetObject : getConfig().entrySet()) { Map.Entry entrySet = (Map.Entry) entrySetObject; configuration.set("" + entrySet.getKey(), "" + entrySet.getValue()); } String hadoopConfDir = getString(HADOOP_CONF_DIR, null); if (hadoopConfDir != null) { LOGGER.info("hadoop conf dir", hadoopConfDir); File dir = new File(hadoopConfDir); if (dir.isDirectory()) { for (String xmlFilename : HADOOP_CONF_FILENAMES) { File file = new File(dir, xmlFilename); if (file.isFile()) { LOGGER.info("adding resource: %s to Hadoop configuration", file); try { ByteArrayInputStream in = new ByteArrayInputStream(FileUtils.readFileToByteArray(file)); configuration.addResource(in); } catch (Exception ex) { LOGGER.warn("error adding resource: " + xmlFilename + " to Hadoop configuration", ex); } } } StringBuilder sb = new StringBuilder(); SortedSet<String> keys = new TreeSet<>(); for (Map.Entry<String, String> entry : configuration) { keys.add(entry.getKey()); } LOGGER.debug("Hadoop configuration:%n%s", sb.toString()); } else { LOGGER.warn("configuration property %s is not a directory", HADOOP_CONF_DIR); } } return configuration; }

Target:
private org.apache.hadoop.conf.Configuration getHadoopConfiguration() { org.apache.hadoop.conf.Configuration configuration = new org.apache.hadoop.conf.Configuration(); for (Object entrySetObject : getConfig().entrySet()) { Map.Entry entrySet = (Map.Entry) entrySetObject; configuration.set("" + entrySet.getKey(), "" + entrySet.getValue()); } loadHadoopConfigs(configuration); return configuration; }
Source:
public void testListMembersWithRole() throws IOException { GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); List<GHUser> admins = org.listMembersWithRole("admin").asList(); assertFalse(admins.isEmpty()); }

Target:
public void testListMembersWithRole() throws IOException { GHOrganization org = gitHub.getOrganization(GITHUB_API_TEST_ORG); List<GHUser> admins = org.listMembersWithRole("admin").asList(); assertNotNull(admins); assertTrue(admins.size() >= 12); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("alexanderrtaylor"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("asthinasthi"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("bitwiseman"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("farmdawgnation"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("halkeye"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("jberglund-BSFT"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("kohsuke"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("kohsuke2"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("martinvanzijl"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("PauloMigAlmeida"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("Sage-Pierce"))); assertTrue(admins.stream().anyMatch(ghUser -> ghUser.getLogin().equals("timja"))); }
Source:
public boolean isEnabled() { updateCurrentPage(); Class<?> repositoryClass = null; try { repositoryClass = Class.forName("org.eclipse.mylyn.internal.tasks.ui.search.RepositorySearchResultView"); } catch (ClassNotFoundException e) { e.printStackTrace(); } boolean enabled = true; if (page == null) { enabled = false; } else if (page.getClass() == repositoryClass) { enabled = false; } return enabled; }

Target:
public boolean isEnabled() { ISearchResultPage page = getCurrentPage(); return page != null && !BLACKLISTED_IDS.contains(page.getID()); }
Source:
private List<String> getAllFilePaths() { List<String> paths = new ArrayList<>(); for (RepositoryFileReference ref : RepositoryFactory.getRepository() .getContainedFiles(this.fileDir)) { ref.getSubDirectory().ifPresent(path -> { paths.add(path.toString()); }); if (!ref.getSubDirectory().isPresent()) { paths.add(""); } } return paths; }

Target:
private List<String> getAllFilePaths() { List<String> paths = new ArrayList<>(); for (RepositoryFileReference ref : RepositoryFactory.getRepository() .getContainedFiles(this.fileDir)) { if (!ref.getSubDirectory().isPresent()) { paths.add(ref.getSubDirectory().get().toString()); } else { paths.add(""); } } return paths; }
Source:
private Display getDisplay() { Shell shell = getSite().getShell(); return shell != null ? shell.getDisplay() : Display.getDefault(); }

Target:
private Display getDisplay() { return PlatformUI.getWorkbench().getDisplay(); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; PowerFailureDecorator other = (PowerFailureDecorator) obj; if (powerfailure == null) { if (other.powerfailure != null) return false; } else if (!powerfailure.equals(other.powerfailure)) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof PowerFailureDecorator)) return false; PowerFailureDecorator other = (PowerFailureDecorator) obj; if (!this.hasPowerFailure() && other.hasPowerFailure()) return false; else if (!powerfailure.equals(other.powerfailure)) return false; return true; }
Source:
private boolean isCaseSensitiveUsername(String username, int tenantId){ if (UserStoreMgtDSComponent.getRealmService() != null) { try { if (UserStoreMgtDSComponent.getRealmService().getTenantUserRealm(tenantId) != null) { UserStoreManager userStoreManager = (UserStoreManager) UserStoreMgtDSComponent.getRealmService() .getTenantUserRealm(tenantId).getUserStoreManager(); UserStoreManager userAvailableUserStoreManager = userStoreManager.getSecondaryUserStoreManager (UserCoreUtil.extractDomainFromName(username)); String isUsernameCaseInsensitiveString = userAvailableUserStoreManager.getRealmConfiguration() .getUserStoreProperty(CASE_INSENSITIVE_USERNAME); if (isUsernameCaseInsensitiveString != null) { return !Boolean.parseBoolean(isUsernameCaseInsensitiveString); } } } catch (org.wso2.carbon.user.api.UserStoreException e) { if (log.isDebugEnabled()) { log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as false."); } } } return true; }

Target:
private boolean isCaseSensitiveUsername(String username, int tenantId) { if (UserStoreMgtDSComponent.getRealmService() != null) { try { if (UserStoreMgtDSComponent.getRealmService().getTenantUserRealm(tenantId) != null) { UserStoreManager userStoreManager = (UserStoreManager) UserStoreMgtDSComponent.getRealmService() .getTenantUserRealm(tenantId).getUserStoreManager(); UserStoreManager userAvailableUserStoreManager = userStoreManager.getSecondaryUserStoreManager (UserCoreUtil.extractDomainFromName(username)); String isUsernameCaseInsensitiveString = userAvailableUserStoreManager.getRealmConfiguration() .getUserStoreProperty(CASE_INSENSITIVE_USERNAME); return !Boolean.parseBoolean(isUsernameCaseInsensitiveString); } } catch (org.wso2.carbon.user.api.UserStoreException e) { if (log.isDebugEnabled()) { log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as false."); } } } return true; }
Source:
public CreateRequest process(CreateRequest request) throws PluginExecutionException, StopProcessingException { Subject ownerSubject = getSubject(); final String owner = subjectIdentity.getUniqueIdentifier(ownerSubject); List<ShareableMetacardImpl> shareableMetacards = request .getMetacards() .stream() .filter(ShareableMetacardImpl::isShareableMetacard) .map(ShareableMetacardImpl::from) .filter(shareableMC -> StringUtils.isEmpty(shareableMC.getOwner())) .collect(Collectors.toList()); if (!shareableMetacards.isEmpty() && isGuest(ownerSubject)) { throw new StopProcessingException("Guest user not allowed to create shareable resources"); } shareableMetacards.stream().forEach(shareableMC -> shareableMC.setOwner(owner)); return request; }

Target:
public CreateRequest process(CreateRequest request) throws PluginExecutionException, StopProcessingException { Subject ownerSubject = getSubject(); final String owner = subjectIdentity.getUniqueIdentifier(ownerSubject); List<ShareableMetacardImpl> shareableMetacards = request .getMetacards() .stream() .filter(ShareableMetacardImpl::canShare) .map(ShareableMetacardImpl::createOrThrow) .filter(shareableMetacard -> StringUtils.isEmpty(shareableMetacard.getOwner())) .collect(Collectors.toList()); if (!shareableMetacards.isEmpty() && isGuest(ownerSubject)) { throw new StopProcessingException("Guest user not allowed to create shareable resources"); } shareableMetacards.stream().forEach(shareableMetacard -> shareableMetacard.setOwner(owner)); return request; }