auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String[] getStringArrayProperty(Map properties, String key) { if (properties == null) return null; Object value = properties.get(key); List<String> r = new ArrayList<String>(); if (value == null) r = Collections.EMPTY_LIST; if (value instanceof String) r = Collections.singletonList((String) value); if (value instanceof String[]) { String[] values = (String[]) value; for (String <START> value2 : <END> values) { if (value2 != null) r.add(value2); } } if (value instanceof Collection) { Collection values = (Collection) value; List result = new ArrayList(values.size()); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { result.add(v); } } } return (r.size() == 0) ? null : r.toArray(new String[r.size()]); }</code><technical_language>rename val v</technical_language>

Target:
public static String[] getStringArrayProperty(Map properties, String key) { if (properties == null) return null; Object value = properties.get(key); List<String> r = new ArrayList<String>(); if (value == null) r = Collections.EMPTY_LIST; if (value instanceof String) r = Collections.singletonList((String) value); if (value instanceof String[]) { String[] values = (String[]) value; for (String v : values) { if (v != null) r.add(v); } } if (value instanceof Collection) { Collection values = (Collection) value; List result = new ArrayList(values.size()); for (Iterator iter = values.iterator(); iter.hasNext();) { Object v = iter.next(); if (v instanceof String) { result.add(v); } } } return (r.size() == 0) ? null : r.toArray(new String[r.size()]); }
Source:
<code>private String formatWifiNameList(Set<String> ssids) { if (ssids != null) { ssids = new TreeSet<>(ssids); StringBuilder sb = new StringBuilder(); for (String ssid : ssids) { if (sb.length() > 0) { sb.append(", "); } sb.append(ssid.replaceFirst("^\"", "").replaceFirst("\"$", "")); } return sb.toString(); } <START> return null; <END> }</code><technical_language>Yeah of course. edit above</technical_language>

Target:
private String formatWifiNameList(Set<String> ssids) { Set<String> formatted = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (String ssid : ssids) { formatted.add(ssid.replaceFirst("^\"", "").replaceFirst("\"$", "")); } return TextUtils.join(", ", formatted); }
Source:
<code>public ContainerAsyncClient getContainerAsyncClient() { return new ContainerAsyncClient(new AzureBlobStorageBuilder() <START> .url(Utility.stripLastPathSegment(getBlobUrl()).toString()) <END> .pipeline(blobAsyncRawClient.azureBlobStorage.httpPipeline())); }</code><technical_language>want strip first, last. Blob names slashes in them. Example: https://myaccoutn/blob.core.windows.net/containername/blobname/stillblobname/evenMoreOfTheSameBlobNameContainingSlashes. wrong this utility method does, in case ask renamed represent doing</technical_language>

Target:
public ContainerAsyncClient getContainerAsyncClient() { try { BlobURLParts parts = URLParser.parse(getBlobUrl()); return new ContainerAsyncClient(new AzureBlobStorageBuilder() .url(String.format("%s://%s/%s", parts.scheme(), parts.host(), parts.containerName())) .pipeline(blobAsyncRawClient.azureBlobStorage.httpPipeline())); } catch (UnknownHostException e) { throw new RuntimeException(e); } }
Source:
<code>private void readLoop(long ledgerId, CompletableFuture<LedgerMetadata> promise) { LedgerMetadata current = currentLocalValue.get(); lm.readLedgerMetadata(ledgerId, (rc, read) -> { if (rc != BKException.Code.OK) { promise.completeExceptionally(BKException.create(rc)); <START> } else if (current.getVersion().equals(read.getVersion())) { <END> promise.complete(current); } else if (updateLocalValue.test(current, read)) { promise.complete(read); } else { readLoop(ledgerId, promise); } }); }</code><technical_language>compare - is version implementation implemented</technical_language>

Target:
private void readLoop(long ledgerId, CompletableFuture<LedgerMetadata> promise) { LedgerMetadata current = currentLocalValue.get(); lm.readLedgerMetadata(ledgerId, (rc, read) -> { if (rc != BKException.Code.OK) { LOG.error("{} Failed to read metadata from store, rc = {}", logContext, rc); promise.completeExceptionally(BKException.create(rc)); } else if (current.getVersion().compare(read.getVersion()) == Version.Occurred.CONCURRENTLY) { promise.complete(current); } else if (updateLocalValue.updateValue(current, read)) { promise.complete(read); } else { readLoop(ledgerId, promise); } }); }
Source:
<code>public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; <START> this.m_srcBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); <END> this.m_dstBuffer = ByteBuffer.allocateDirect(Constants.SSL_CHUNK_SIZE + 128); this.m_partialLength = ByteBuffer.allocate(4); }</code><technical_language>cleaners for direct byte buffer allocations</technical_language>

Target:
public SSLBufferDecrypter(SSLEngine sslEngine) { this.m_sslEngine = sslEngine; }
Source:
<code>public TracePackageExportOperation(TracePackageTraceElement[] <START> traceExportElements, <END> boolean useCompression, boolean useTar, String fileName) { super(fileName); fTraceExportElements = Arrays.copyOf(traceExportElements,traceExportElements.length); fUseCompression = useCompression; fUseTar = useTar; fResources = new HashSet<>(); }</code><technical_language>null right code calls if new code calls null, fail (NPE). add a check now. add null annotations later</technical_language>

Target:
public TracePackageExportOperation(TracePackageTraceElement[] traceExportElements, boolean useCompression, boolean useTar, String fileName) { super(fileName); fTraceExportElements = (traceExportElements == null ? null : Arrays.copyOf(traceExportElements, traceExportElements.length)); fUseCompression = useCompression; fUseTar = useTar; fResources = new HashSet<>(); }
Source:
<code>public boolean useAjaxTabs() { ConfigurationService configurationService = Framework.getService(ConfigurationService.class); <START> if (configurationService.getBoolean(AJAX_TAB_PROPERTY, true)) { <END> return canUseAjaxTabs(); } return false; }</code><technical_language>Default false</technical_language>

Target:
public boolean useAjaxTabs() { ConfigurationService configurationService = Framework.getService(ConfigurationService.class); if (configurationService.isBooleanTrue(AJAX_TAB_PROPERTY)) { return canUseAjaxTabs(); } return false; }
Source:
<code>public static void savePage(Long listingId, String[] p1q1) { Listing listing = Listing.getByListingId(listingId); validation.required(p1q1).key("p1q1"); validation.isTrue(ValidationUtils.stringArrayValuesAreNotTooLong(p1q1, 30)).key("p1q1").message("Invalid values"); if(validation.hasErrors()) { flash.put("body", params.get("body")); for(Map.Entry<String, List<Error>> entry : validation.errorsMap().entrySet()) { String key = entry.getKey(); String value = entry.getValue().get(0).message(); flash.put(key, value); } redirect(String.format("/page/%d/%d", PAGE_ID, listing.id)); } if (listing.serviceSubmitted) { <START> redirect(listing.summaryPageUrl()); <END> } else { Gson gson = new Gson(); Page page = new Page(listingId, PAGE_ID); page.responses.put("p1q1", gson.toJson(p1q1)); page.insert(); listing.addResponsePage(page, PAGE_ID, supplierDetailsFromCookie.get("supplierEmail")); redirect(listing.nextPageUrl(PAGE_ID, listing.id)); } }</code><technical_language>a flash message changes listing? is this happen if spoofed a POST request, in case messaging necessary better</technical_language>

Target:
public static void savePage(Long listingId, String[] p1q1) { Listing listing = Listing.getByListingId(listingId); if (listing.serviceSubmitted) { redirect(listing.summaryPageUrl()); } validation.required(p1q1).key("p1q1"); validation.isTrue(ValidationUtils.stringArrayValuesAreNotTooLong(p1q1, 30)).key("p1q1").message("Invalid values"); if(validation.hasErrors()) { flash.put("body", params.get("body")); for(Map.Entry<String, List<Error>> entry : validation.errorsMap().entrySet()) { String key = entry.getKey(); String value = entry.getValue().get(0).message(); flash.put(key, value); } redirect(String.format("/page/%d/%d", PAGE_ID, listing.id)); } Gson gson = new Gson(); Page page = new Page(listingId, PAGE_ID); page.responses.put("p1q1", gson.toJson(p1q1)); page.insert(); listing.addResponsePage(page, PAGE_ID, supplierDetailsFromCookie.get("supplierEmail")); redirect(listing.nextPageUrl(PAGE_ID, listing.id)); }
Source:
<code>private void updateConsoleAddressPartiallyOverridden(VDSGroup cluster) { AsyncQuery query = new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { @SuppressWarnings("unchecked") <START> boolean toShowWarning = isConsoleAddressPartiallyOverridden((List<VDS>) ((VdcQueryReturnValue) returnValue).getReturnValue()); <END> setConsoleAddressPartiallyOverridden(toShowWarning); } } ); Frontend.RunQuery( VdcQueryType.GetHostsByClusterId, new GetHostsByClusterIdParameters(cluster.getId()), query ); }</code><technical_language>fetch hosts in cluster for a single boolean? please write a query retrieve it</technical_language>

Target:
private void updateConsoleAddressPartiallyOverridden(VDSGroup cluster) { AsyncQuery query = new AsyncQuery(this, new INewAsyncCallback() { @Override public void OnSuccess(Object target, Object returnValue) { boolean toShowWarning = (Boolean) ((VdcQueryReturnValue) returnValue).getReturnValue(); setConsoleAddressPartiallyOverridden(toShowWarning); } } ); Frontend.RunQuery( VdcQueryType.GetHostsInClusterPartiallyOverridden, new GetHostsInClusterPartiallyOverriddenParameters(cluster.getId()), query ); }
Source:
<code>public Email read( ObjectDataInput in ) throws IOException { <START> return null; <END> }</code><technical_language>is a specific reason for returning null? return empty Email object instead</technical_language>

Target:
public Email read( ObjectDataInput in ) throws IOException { return deserialize( in ); }
Source:
<code>protected <K, V> EntryListener<K, V> putAllEntryListenerBuilder(Consumer<EntryEvent<K, V>> f) { return new EntryAdapter<K, V>() { public void entryAdded(EntryEvent<K, V> event) { f.accept(event); } public void entryRemoved(EntryEvent<K, V> event) { <START> System.out.println("entryRemoved " + event); <END> } public void entryEvicted(EntryEvent<K, V> event) { entryRemoved(event); } @Override public void mapEvicted(MapEvent event) { } @Override public void mapCleared(MapEvent event) { System.out.println("mapCleared " + event); } }; }</code><technical_language>soon longer need System.outs (probably inserted for debugging?), please remove them</technical_language>

Target:
protected <K, V> EntryListener<K, V> putAllEntryListenerBuilder(Consumer<EntryEvent<K, V>> f) { return new EntryAdapter<K, V>() { public void entryAdded(EntryEvent<K, V> event) { f.accept(event); } public void entryRemoved(EntryEvent<K, V> event) { } public void entryEvicted(EntryEvent<K, V> event) { entryRemoved(event); } @Override public void mapEvicted(MapEvent event) { } @Override public void mapCleared(MapEvent event) { } }; }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Ean)) { return false; } <START> final Ean other = (Ean) o; <END> if (this.device != null ? !this.device.getDeviceIdentification().equals(other.device.getDeviceIdentification()) : other.device != null) { return false; } if (this.code != null ? !this.code.equals(other.code) : other.code != null) { return false; } if (this.description != null ? !this.description.equals(other.description) : other.description != null) { return false; } return true; }</code><technical_language>Checking if device is equal other Eans device like: Objects.equals(this.device, other.device);, I is benefit involve deviceIdentification (unless multiple devices share identification, Eans considered equal). For Eans hashCode consider if form cleaner: return Objects.hash(code, description, device);</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Ean)) { return false; } final Ean other = (Ean) o; final boolean isDeviceEqual = Objects.equals(this.device, other.device); final boolean isCodeEqual = Objects.equals(this.code, other.code); final boolean isDescriptionEqual = Objects.equals(this.description, other.description); return isDeviceEqual && isCodeEqual && isDescriptionEqual; }
Source:
<code>private void addCrewMember(org.atlasapi.media.entity.CrewMember legacy, CrewMember translated) { translated.withName(legacy.name()); <START> if (Objects.nonNull(legacy.role())) { <END> translated.withRole(CrewMember.Role.fromKey(legacy.role().key())); } }</code><technical_language>This is a bit non-standard. Objects.nonNull in filters for Java 8 streams, in this case do legacy.role() != null. more instantly recognisable</technical_language>

Target:
private void addCrewMember(org.atlasapi.media.entity.CrewMember legacy, CrewMember translated) { translated.withName(legacy.name()); if (null != legacy.role()) { translated.withRole(CrewMember.Role.fromKey(legacy.role().key())); } }
Source:
<code>static ForkJoinPool getInstance(final ConfigContext config) { Validate.notNull(config, "Configuration context is null"); int processors = Runtime.getRuntime().availableProcessors(); final String parallelismSysProp = System.getProperty(SYSTEM_FORK_JOIN_POOL_PARALLELISM_KEY); if (parallelismSysProp != null) { try { processors = Integer.valueOf(System.getProperty(SYSTEM_FORK_JOIN_POOL_PARALLELISM_KEY)); } catch (NumberFormatException e) { } } <START> final int parallelism = Math.min(config.getMaximumConnections() - 2, <END> processors); return new ForkJoinPool(parallelism); }</code><technical_language>need guarantee result is a positive integer (or max connections > 2)</technical_language>

Target:
static ForkJoinPool getInstance(final ConfigContext config) { Validate.notNull(config, "Configuration context is null"); final int maximumConnections = Validate.notNull( config.getMaximumConnections(), "Maximum connections setting is null"); Validate.isTrue(maximumConnections > 0, "Maximum connections is not greater than zero"); final int parallelism = calculateParallelism(maximumConnections); return new ForkJoinPool(parallelism); }
Source:
<code><START> protected OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { <END> if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; }</code><technical_language>Do need expose this right now? prefer private if need expose now</technical_language>

Target:
OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) { if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) { Set<String> defaultScopes = defaultScopes(grantRequest); tokenResponse = OAuth2AccessTokenResponse.withResponse(tokenResponse) .scopes(defaultScopes) .build(); } return tokenResponse; }
Source:
<code>public static Single<Integer> processMetadata(String path) throws IOException { Map<MetadataType, Metadata> metadataMap = Metadata.readMetadata(path); Metadata metadata = metadataMap.get(MetadataType.IPTC); <START> byte[] b = new byte[0]; <END> try { b = ((IPTC) metadata).getDataSets().get("SpecialInstructions").get(0).getData(); } catch (NullPointerException e) { return Single.just(ImageUtils.IMAGE_OK); } for (int i = 0; i < b.length; i++) { if (b[i] == 70 && b[i + 1] == 66 && b[i + 2] == 77 && b[i + 3] == 68) { Timber.d("Contains FBMD"); return Single.just(ImageUtils.FILE_FBMD); } } return Single.just(ImageUtils.IMAGE_OK); }</code><technical_language>rename a more meaningful name. :)</technical_language>

Target:
public Single<Integer> processMetadata(String path) throws IOException { Map<MetadataType, Metadata> metadataMap = Metadata.readMetadata(path); Metadata metadata = metadataMap.get(MetadataType.IPTC); byte[] dataInBytes = new byte[0]; try { dataInBytes = ((IPTC) metadata).getDataSets().get("SpecialInstructions").get(0).getData(); } catch (NullPointerException e) { return Single.just(ImageUtils.IMAGE_OK); } if (dataInBytes[0] == 70 && dataInBytes[1] == 66 && dataInBytes[2] == 77 && dataInBytes[3] == 68) { Timber.d("Contains FBMD"); return Single.just(ImageUtils.FILE_FBMD); } return Single.just(ImageUtils.IMAGE_OK); }
Source:
<code>public void isConnWithSameDetailsExistFileDomains() { StorageServerConnections newNFSConnection = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection1 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection2 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 600, 0); List<StorageServerConnections> connections = Arrays.asList(connection1, connection2); when(storageConnDao.getAllForStorage(newNFSConnection.getConnection())).thenReturn(connections); <START> doReturn(newNFSConnection.getId()).when(command).isConnWithSameDetailsExists(newNFSConnection, <END> null); }</code><technical_language>missing assert statement in changed tests</technical_language>

Target:
public void isConnWithSameDetailsExistFileDomains() { StorageServerConnections newNFSConnection = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection1 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 300, 0); StorageServerConnections connection2 = createNFSConnection( "multipass.my.domain.tlv.company.com:/export/allstorage/data2", StorageType.NFS, NfsVersion.V4, 600, 0); List<StorageServerConnections> connections = Arrays.asList(connection1, connection2); when(storageConnDao.getAllForStorage(newNFSConnection.getConnection())).thenReturn(connections); boolean isExists = !command.isConnWithSameDetailsExists(newNFSConnection, null).isEmpty(); assertTrue(isExists); }
Source:
<code>public void onNext(final ContextStop contextStop) { LOG.log(Level.FINE, "Wait {0} milliseconds at maximum for the PS server to be closed", CLOSE_TIMEOUT_MS); try { parameterServer.close(CLOSE_TIMEOUT_MS); LOG.fine("Succeed to close PS server cleanly"); } catch (InterruptedException | TimeoutException | ExecutionException e) { <START> LOG.log(Level.INFO, "Fail to close PS server cleanly", e); <END> } psNetworkSetup.unregisterConnectionFactory(); }</code><technical_language>I critical, give WARNING log Exception occurred</technical_language>

Target:
public void onNext(final ContextStop contextStop) { LOG.log(Level.FINE, "Wait {0} milliseconds at maximum for the PS server to be closed", CLOSE_TIMEOUT_MS); try { parameterServer.close(CLOSE_TIMEOUT_MS); LOG.fine("Succeed to close PS server cleanly"); } catch (InterruptedException | TimeoutException | ExecutionException e) { LOG.log(Level.WARNING, "Fail to close PS server cleanly", e); } psNetworkSetup.unregisterConnectionFactory(); }
Source:
<code>public synchronized Schema addColumn(String name, TypeDesc typeDesc) { String normalized = name; if(fieldsByQualifiedName.containsKey(normalized)) { throw new TajoRuntimeException(new DuplicateColumnException(normalized)); } Column newCol = new Column(normalized, typeDesc); fields.add(newCol); fieldsByQualifiedName.put(newCol.getQualifiedName(), fields.size() - 1); <START> List inputList = new ArrayList<>(); <END> inputList.add(fields.size() - 1); fieldsByName.put(newCol.getSimpleName(), inputList); return this; }</code><technical_language>Please type</technical_language>

Target:
public synchronized Schema addColumn(String name, TypeDesc typeDesc) { String normalized = name; if(fieldsByQualifiedName.containsKey(normalized)) { throw new TajoRuntimeException(new DuplicateColumnException(normalized)); } Column newCol = new Column(normalized, typeDesc); fields.add(newCol); fieldsByQualifiedName.put(newCol.getQualifiedName(), fields.size() - 1); List<Integer> inputList = new ArrayList<>(); inputList.add(fields.size() - 1); fieldsByName.put(newCol.getSimpleName(), inputList); return this; }
Source:
<code>private void assertVolumeAvailable(Volume volume) { <START> assertRandom(new Predicate<VolumeRef>() { <END> @Override public boolean apply(VolumeRef volumeRef) { Volume volume = api.volumeApi().getVolume(volumeRef.dataCenterId(), volumeRef.volumeId()); if (volume == null || volume.metadata() == null) return false; return volume.metadata().state() == State.AVAILABLE; } }, VolumeRef.create(volume.dataCenterId(), volume.id())); }</code><technical_language>this... more convenient for this method named assertPredicate? current name perform arbitrary assertions..</technical_language>

Target:
private void assertVolumeAvailable(Volume volume) { assertPredicate(new Predicate<VolumeRef>() { @Override public boolean apply(VolumeRef volumeRef) { Volume volume = api.volumeApi().getVolume(volumeRef.dataCenterId(), volumeRef.volumeId()); if (volume == null || volume.metadata() == null) return false; return volume.metadata().state() == State.AVAILABLE; } }, VolumeRef.create(volume.dataCenterId(), volume.id())); }
Source:
<code>public List<PersistableBusinessObject> generateDeactivationsToPersist() { <START> List<SubAccount> bosToDeactivate = new ArrayList (); <END> if (!isActive()) { Map<String, Object> fieldValues = new HashMap(); fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, getChartOfAccountsCode()); fieldValues.put(KFSPropertyConstants.ACCOUNT_NUMBER, getAccountNumber()); fieldValues.put(KFSPropertyConstants.ACTIVE, true); Collection<SubAccount> existingSubAccounts = SpringContext.getBean(BusinessObjectService.class) .findMatching(SubAccount.class, fieldValues); bosToDeactivate.addAll(existingSubAccounts); } for (SubAccount subAccount : bosToDeactivate) { subAccount.setActive(false); } return new ArrayList<>(bosToDeactivate); }</code><technical_language>Diamond operator is missing this statement</technical_language>

Target:
public List<PersistableBusinessObject> generateDeactivationsToPersist() { List<SubAccount> bosToDeactivate = new ArrayList<>(); if (!isActive()) { Map<String, Object> fieldValues = new HashMap<>(); fieldValues.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, getChartOfAccountsCode()); fieldValues.put(KFSPropertyConstants.ACCOUNT_NUMBER, getAccountNumber()); fieldValues.put(KFSPropertyConstants.ACTIVE, true); Collection<SubAccount> existingSubAccounts = SpringContext.getBean(BusinessObjectService.class) .findMatching(SubAccount.class, fieldValues); bosToDeactivate.addAll(existingSubAccounts); } for (SubAccount subAccount : bosToDeactivate) { subAccount.setActive(false); } return new ArrayList<>(bosToDeactivate); }
Source:
<code>private void addAPI(API api, int tenantId) throws APIManagementException { int apiId = apiMgtDAO.addAPI(api, tenantId); addLocalScopes(api.getId(), tenantId, api.getUriTemplates()); addURITemplates(apiId, api, tenantId); HashSet<String> endpointRegistryEntries = APIUtil.extractEndpointRegistryEntries(api.getEndpointConfig()); <START> if (!endpointRegistryEntries.isEmpty()) { <END> apiMgtDAO.addAPIServiceCatalogEntryMappings(apiId, endpointRegistryEntries, null); } APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_CREATE.name(), tenantId, api.getId().getApiName(), apiId, api.getId().getVersion(), api.getType(), api.getContext(), api.getId().getProviderName(), api.getStatus()); APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name()); }</code><technical_language>change variable naming here</technical_language>

Target:
private void addAPI(API api, int tenantId) throws APIManagementException { int apiId = apiMgtDAO.addAPI(api, tenantId); addLocalScopes(api.getId(), tenantId, api.getUriTemplates()); addURITemplates(apiId, api, tenantId); HashSet<String> serviceCatalogEntries = APIUtil.extractServiceCatalogEntries(api.getEndpointConfig()); if (!serviceCatalogEntries.isEmpty()) { apiMgtDAO.addAPIServiceCatalogEntryMappings(apiId, serviceCatalogEntries, null); } APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_CREATE.name(), tenantId, api.getId().getApiName(), apiId, api.getId().getVersion(), api.getType(), api.getContext(), api.getId().getProviderName(), api.getStatus()); APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name()); }
Source:
<code><START> public ChargeEntity markChargeAsEligibleForCapture(String externalId) { <END> return chargeDao.findByExternalId(externalId).map(charge -> { ChargeStatus targetStatus = charge.isDelayedCapture() ? AWAITING_CAPTURE_REQUEST : CAPTURE_APPROVED; ChargeStatus currentChargeStatus = fromString(charge.getStatus()); try { updateChargeStatus(charge, targetStatus); } catch (InvalidStateTransitionException e) { logger.error("Charge with state " + currentChargeStatus + " cannot proceed to " + targetStatus + " [charge_external_id={}, charge_status={}]", charge.getExternalId(), currentChargeStatus); throw new IllegalStateRuntimeException(charge.getExternalId()); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }</code><technical_language>i realise this code copied else a red flag calling updateChargeStatus catches InvalidStateTransitionException, other places call don't. i need catch ChargeEntitiy.setStatus throws it, point re-catching it. Also, ChargeEntity.setStatus's signature public void setStatus(ChargeStatus targetStatus) public void setStatus(ChargeStatus targetStatus) throws InvalidStateTransitionException InvalidStateTransitionException is a RuntimeException</technical_language>

Target:
public ChargeEntity markChargeAsEligibleForCapture(String externalId) { return chargeDao.findByExternalId(externalId).map(charge -> { ChargeStatus targetStatus = charge.isDelayedCapture() ? AWAITING_CAPTURE_REQUEST : CAPTURE_APPROVED; try { updateChargeStatus(charge, targetStatus); } catch (InvalidStateTransitionException e) { throw new IllegalStateRuntimeException(charge.getExternalId()); } return charge; }).orElseThrow(() -> new ChargeNotFoundRuntimeException(externalId)); }
Source:
<code>FileRevisionTypedElement getAncestorRevision() { <START> if (ancestor instanceof FileRevisionTypedElement) { <END> return (FileRevisionTypedElement) ancestor; } return null; }</code><technical_language>style nit: braces</technical_language>

Target:
FileRevisionTypedElement getAncestorRevision() { if (ancestor instanceof FileRevisionTypedElement) return (FileRevisionTypedElement) ancestor; return null; }
Source:
<code>private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } <START> else { <END> return key; } }</code><technical_language>drop unnecessary else. private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null || key.isDestroyed()) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher destroyed"); } return key; }</technical_language>

Target:
private SecretKey verifyKeyNotDestroyed() { SecretKey key = this.key; if (key == null) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Spill cipher already destroyed"); } return key; }
Source:
<code>private ITmfEvent parseLine(TmfContext context) { <START> @Nullable <END> ITmfLocation location = context.getLocation(); if (location != null) { try { if (!location.getLocationInfo().equals(fFileInput.getFilePointer())) { seekEvent(location); } } catch (IOException e1) { seekEvent(location); } String line; try { line = fFileInput.readLine(); return parseLine(context.getRank(), line); } catch (IOException e) { Activator.logError(e.getMessage(), e); } } return null; }</code><technical_language>line (or omit?)</technical_language>

Target:
private ITmfEvent parseLine(TmfContext context) { ITmfLocation location = context.getLocation(); if (location != null) { try { if (!location.getLocationInfo().equals(fFileInput.getFilePointer())) { seekEvent(location); } } catch (IOException e1) { seekEvent(location); } String line; try { line = fFileInput.readLine(); return parseLine(context.getRank(), line); } catch (IOException e) { Activator.logError(e.getMessage(), e); } } return null; }
Source:
<code>private ServerErrorCode validateRequest(PartitionId partition, RequestOrResponseType requestType) { if (partition == null) { metrics.badRequestError.inc(); <START> return ServerErrorCode.Bad_Request; <END> } if (storageManager.getStore(partition) == null) { boolean partitionPresent = false; for (ReplicaId replica : partition.getReplicaIds()) { if (replica.getDataNodeId().equals(currentNode)) { partitionPresent = true; break; } } if (partitionPresent) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } else { metrics.partitionUnknownError.inc(); return ServerErrorCode.Partition_Unknown; } } List<? extends ReplicaId> replicaIds = partition.getReplicaIds(); for (ReplicaId replica : replicaIds) { if (replica.getDataNodeId().getHostname().equals(currentNode.getHostname()) && replica.getDataNodeId().getPort() == currentNode.getPort()) { if (replica.getDiskId().getState() == HardwareState.UNAVAILABLE) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } } } if (requestType.equals(RequestOrResponseType.PutRequest) && partition.getPartitionState() == PartitionState.READ_ONLY) { metrics.partitionReadOnlyError.inc(); return ServerErrorCode.Partition_ReadOnly; } if (!isRequestEnabled(requestType, partition)) { metrics.temporarilyUnavailableError.inc(); return ServerErrorCode.Temporarily_Unavailable; } return ServerErrorCode.No_Error; }</code><technical_language>this considered a bad request? null resulted fact partition identified, request is malformed</technical_language>

Target:
private ServerErrorCode validateRequest(PartitionId partition, RequestOrResponseType requestType) { if (partition == null) { metrics.badRequestError.inc(); return ServerErrorCode.Bad_Request; } if (storageManager.getStore(partition) == null) { boolean partitionPresent = false; for (ReplicaId replica : partition.getReplicaIds()) { if (replica.getDataNodeId().equals(currentNode)) { partitionPresent = true; break; } } if (partitionPresent) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } else { metrics.partitionUnknownError.inc(); return ServerErrorCode.Partition_Unknown; } } List<? extends ReplicaId> replicaIds = partition.getReplicaIds(); for (ReplicaId replica : replicaIds) { if (replica.getDataNodeId().getHostname().equals(currentNode.getHostname()) && replica.getDataNodeId().getPort() == currentNode.getPort()) { if (replica.getDiskId().getState() == HardwareState.UNAVAILABLE) { metrics.diskUnavailableError.inc(); return ServerErrorCode.Disk_Unavailable; } } } if (requestType.equals(RequestOrResponseType.PutRequest) && partition.getPartitionState() == PartitionState.READ_ONLY) { metrics.partitionReadOnlyError.inc(); return ServerErrorCode.Partition_ReadOnly; } if (!isRequestEnabled(requestType, partition)) { metrics.temporarilyUnavailableError.inc(); return ServerErrorCode.Temporarily_Disabled; } return ServerErrorCode.No_Error; }
Source:
<code>private Optional<String> readFromResources(final String filePath) { final ClassLoader classLoader = TestDataFileReader.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream(filePath)) { <START> return Optional.of(IOUtils.toString(inputStream, StandardCharsets.UTF_8)); <END> } catch (final NullPointerException | IOException e) { return Optional.empty(); } }</code><technical_language>suggestion return Optional.of(new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)); I enough examples for now, I hope I point</technical_language>

Target:
private Optional<String> readFromResources(final String filePath) { final ClassLoader classLoader = TestDataFileReader.class.getClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream(filePath)) { return Optional.of(new String(inputStream.readAllBytes(), StandardCharsets.UTF_8)); } catch (final NullPointerException | IOException e) { return Optional.empty(); } }
Source:
<code>public ConnectedChannel checkOutConnection(String host, int port, long timeoutInMs) throws IOException, InterruptedException, ConnectionPoolTimeoutException { final Timer.Context context = connectionCheckOutTime.time(); BlockingChannelInfo blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { synchronized (this) { blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { logger.trace("Creating new blocking channel info for host and port {}", host, port); blockingChannelInfo = new BlockingChannelInfo(config, host, port, registry); connections.put(host + port, blockingChannelInfo); } } } <START> context.stop(); <END> return blockingChannelInfo.getBlockingChannel(timeoutInMs); }</code><technical_language>need this in finally</technical_language>

Target:
public ConnectedChannel checkOutConnection(String host, int port, long timeoutInMs) throws IOException, InterruptedException, ConnectionPoolTimeoutException { final Timer.Context context = connectionCheckOutTime.time(); try { BlockingChannelInfo blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { synchronized (this) { blockingChannelInfo = connections.get(host + port); if (blockingChannelInfo == null) { logger.trace("Creating new blocking channel info for host and port {}", host, port); blockingChannelInfo = new BlockingChannelInfo(config, host, port, registry); connections.put(host + port, blockingChannelInfo); } } } return blockingChannelInfo.getBlockingChannel(timeoutInMs); } finally { context.stop(); } }
Source:
<code>public void shutdown(IRecordProcessorCheckpointer iRecordProcessorCheckpointer, ShutdownReason shutdownReason) { LOGGER.warn("SHUTDOWN: {}", shutdownReason.toString()); <START> if(shutdownReason == ShutdownReason.TERMINATE) { <END> LOGGER.warn("Going to checkpoint"); try { iRecordProcessorCheckpointer.checkpoint(); LOGGER.warn("Checkpointed successfully"); } catch (InvalidStateException e) { LOGGER.error(e.getMessage()); } catch (ShutdownException e) { LOGGER.error(e.getMessage()); } } }</code><technical_language>equals(...) instead of "=="</technical_language>

Target:
public void shutdown(IRecordProcessorCheckpointer iRecordProcessorCheckpointer, ShutdownReason shutdownReason) { LOGGER.warn("SHUTDOWN: {}", shutdownReason.toString()); if(shutdownReason.equals(ShutdownReason.TERMINATE)) { LOGGER.warn("Going to checkpoint"); try { iRecordProcessorCheckpointer.checkpoint(); LOGGER.warn("Checkpointed successfully"); } catch (InvalidStateException e) { LOGGER.error(e.getMessage()); } catch (ShutdownException e) { LOGGER.error(e.getMessage()); } } }
Source:
<code>public void testDeleteCommentAsRelation() { <START> CommentManager anotherCommentManager = new CommentManagerImpl(CommentServiceHelper.getCommentService().getConfig()); <END> DocumentModel commentDocModel = createComment(anotherCommentManager); Comment comment = anotherCommentManager.getComment(session, commentDocModel.getId()); assertNotNull(comment); CommentService commentComponent = (CommentService) Framework.getRuntime().getComponent(CommentService.NAME); RelationManager relationManager = Framework.getService(RelationManager.class); CommentServiceConfig config = commentComponent.getConfig(); if (config != null) { Resource commentRes = relationManager.getResource(config.commentNamespace, commentDocModel, null); assertNotNull(commentRes); Graph graph = relationManager.getGraph(config.graphName, commentDocModel.getCoreSession()); Resource predicateRes = new ResourceImpl(config.predicateNamespace); assertTrue(graph.getObjects(commentRes, predicateRes).stream().findAny().isPresent()); } commentManager.deleteComment(session, commentDocModel.getId()); try { anotherCommentManager.getComment(session, commentDocModel.getId()); fail(); } catch (CommentNotFoundException cfe) { assertNotNull(cfe); assertNotNull(cfe.getMessage()); } }</code><technical_language>Framework.getService here</technical_language>

Target:
public void testDeleteCommentAsRelation() { CommentManager anotherCommentManager = Framework.getService(CommentManager.class); DocumentModel commentDocModel = createComment(anotherCommentManager); Comment comment = anotherCommentManager.getComment(session, commentDocModel.getId()); assertNotNull(comment); CommentService commentComponent = (CommentService) Framework.getRuntime().getComponent(CommentService.NAME); RelationManager relationManager = Framework.getService(RelationManager.class); CommentServiceConfig config = commentComponent.getConfig(); if (config != null) { Resource commentRes = relationManager.getResource(config.commentNamespace, commentDocModel, null); assertNotNull(commentRes); Graph graph = relationManager.getGraph(config.graphName, commentDocModel.getCoreSession()); Resource predicateRes = new ResourceImpl(config.predicateNamespace); assertTrue(graph.getObjects(commentRes, predicateRes).stream().findAny().isPresent()); } commentManager.deleteComment(session, commentDocModel.getId()); try { anotherCommentManager.getComment(session, commentDocModel.getId()); fail(); } catch (CommentNotFoundException cfe) { assertNotNull(cfe); assertNotNull(cfe.getMessage()); } }
Source:
<code>public void testLotsOfWrites() { Cache<String, String> cache = cache(0); <START> int amount = 5_0000; <END> for (int i = 0; i < amount; ++i) { cache.put("key" + i, "value" + i); } assertEquals(amount, cache.size()); }</code><technical_language>a constant</technical_language>

Target:
public void testLotsOfWrites() { Cache<String, String> cache = cache(0); for (int i = 0; i < 5_000; ++i) { cache.put("key" + i, "value" + i); } }
Source:
<code>public void setUp() throws Exception { File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); <START> System.out.println(tmpDir); <END> conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); conf.setEntryLogSizeLimit(2048); ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); interleavedStorage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager, null, checkpointSource, checkpointer, NullStatsLogger.INSTANCE); for (long entryId = 0; entryId < numWrites; entryId++) { for (long ledgerId = 0; ledgerId < 5; ledgerId++) { if (entryId == 0) { interleavedStorage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes()); interleavedStorage.setFenced(ledgerId); } ByteBuf entry = Unpooled.buffer(128); entry.writeLong(ledgerId); entry.writeLong(entryId * entriesPerWrite); entry.writeBytes(("entry-" + entryId).getBytes()); interleavedStorage.addEntry(entry); } } }</code><technical_language>Is this useful</technical_language>

Target:
public void setUp() throws Exception { File tmpDir = File.createTempFile("bkTest", ".dir"); tmpDir.delete(); tmpDir.mkdir(); File curDir = Bookie.getCurrentDirectory(tmpDir); Bookie.checkDirectoryStructure(curDir); conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(new String[] { tmpDir.toString() }); conf.setEntryLogSizeLimit(2048); ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); interleavedStorage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager, null, checkpointSource, checkpointer, NullStatsLogger.INSTANCE); for (long entryId = 0; entryId < numWrites; entryId++) { for (long ledgerId = 0; ledgerId < 5; ledgerId++) { if (entryId == 0) { interleavedStorage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes()); interleavedStorage.setFenced(ledgerId); } ByteBuf entry = Unpooled.buffer(128); entry.writeLong(ledgerId); entry.writeLong(entryId * entriesPerWrite); entry.writeBytes(("entry-" + entryId).getBytes()); interleavedStorage.addEntry(entry); } } }
Source:
<code>public ItemBucketBCA(Fluid fluid) { super(fluid.getBlock()); this.fluid = new FluidStack(fluid.getID(), FluidContainerRegistry.BUCKET_VOLUME); setContainerItem(Items.bucket); setCreativeTab(BuildcraftAdditions.bcadditions); setUnlocalizedName("bcaBucket." + fluid.getName()); <START> if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) <END> MinecraftForgeClient.registerItemRenderer(this, BucketItemRenderer.INSTANCE); }</code><technical_language>please put in proxy instead, cleaner easier find</technical_language>

Target:
public ItemBucketBCA(Fluid fluid) { super(fluid.getBlock()); this.fluid = new FluidStack(fluid.getID(), FluidContainerRegistry.BUCKET_VOLUME); setContainerItem(Items.bucket); setCreativeTab(BuildcraftAdditions.bcadditions); setUnlocalizedName("bcaBucket." + fluid.getName()); }
Source:
<code><START> public synchronized void releaseEncodedBuffer() { <END> if (temporaryBuffer != null && temporaryBuffer.release()) { temporaryBuffer = null; } }</code><technical_language>Largemessage concurrent accessed used. In case of topic multiple queues. Remember fix loads of concurrent access issue core message other year</technical_language>

Target:
public void releaseEncodedBuffer() { internalReleaseBuffer(1); }
Source:
<code>public void updateSessionAttributes(String id, Map<String, Object> sessionAttributes) { SessionData sessionData = sessionDataMap.get(id); if (sessionData != null && !sessionData.getAllAttributes().equals(sessionAttributes)) { LOGGER.debug( "Storing new attributes for session at context {}", id, _context.getCanonicalContextPath()); <START> synchronized (this) { <END> sessionData.clearAllAttributes(); sessionData.putAllAttributes(sessionAttributes); } } }</code><technical_language>If synchronization control access session data, I suggest reverting map type a simple HashMap synchronizing map opposed this read, put, remove, alter it</technical_language>

Target:
public void updateSessionAttributes(String id, Map<String, Object> sessionAttributes) { synchronized (sessionDataMap) { SessionData sessionData = sessionDataMap.get(id); if (sessionData != null && !sessionData.getAllAttributes().equals(sessionAttributes)) { LOGGER.trace( "Storing new attributes for session at context {}", id, _context.getCanonicalContextPath()); sessionData.clearAllAttributes(); sessionData.putAllAttributes(sessionAttributes); } } }
Source:
<code>protected void say(String text) { try { Voice voice = null; for (Voice currentVoice : tts.getAvailableVoices()) { if (this.locale.getLanguage().equals(currentVoice.getLocale().getLanguage())) { voice = currentVoice; break; } } if (null == voice) { <START> throw new TTSException("Unable to find a voice"); <END> } AudioStream audioStream = tts.synthesize(text, voice, null); try { sink.process(audioStream); } catch (UnsupportedAudioFormatException | UnsupportedAudioStreamException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } } catch (TTSException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } }</code><technical_language>change this? unrelated this PR message is correct anymore system able find a voice, of right locale</technical_language>

Target:
protected void say(String text) { try { Voice voice = null; for (Voice currentVoice : tts.getAvailableVoices()) { if (this.locale.getLanguage().equals(currentVoice.getLocale().getLanguage())) { voice = currentVoice; break; } } if (null == voice) { throw new TTSException("Unable to find a suitable voice"); } AudioStream audioStream = tts.synthesize(text, voice, null); try { sink.process(audioStream); } catch (UnsupportedAudioFormatException | UnsupportedAudioStreamException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } } catch (TTSException e) { logger.error("Error saying '{}': {}", text, e.getMessage()); } }
Source:
<code>public synchronized void serviceStop() throws Exception { if (isSession) { sessionStopped.set(true); } if (this.dagSubmissionTimer != null) { this.dagSubmissionTimer.cancel(); } stopServices(); boolean deleteTezScratchData = this.amConf.getBoolean( TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE, TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE_DEFAULT); LOG.info("Checking whether tez scratch data dir should be deleted, deleteTezScratchData=" <START> + deleteTezScratchData); <END> if (deleteTezScratchData && this.taskSchedulerEventHandler != null && this.taskSchedulerEventHandler.hasUnregistered()) { if (this.tezSystemStagingDir != null) { LOG.info("Deleting tez scratch data dir, path=" + this.tezSystemStagingDir); try { FileSystem fs = this.tezSystemStagingDir.getFileSystem(this.amConf); boolean deletedStagingDir = fs.delete(this.tezSystemStagingDir, true); if (!deletedStagingDir) { LOG.warn("Failed to delete tez scratch data dir, path=" + this.tezSystemStagingDir); } else { LOG.info("Completed deletion of tez scratch data dir, path=" + this.tezSystemStagingDir); } } catch (IOException e) { LOG.warn("Failed to tez scratch data dir", e); } } } super.serviceStop(); }</code><technical_language>LOG.Debug</technical_language>

Target:
public synchronized void serviceStop() throws Exception { if (isSession) { sessionStopped.set(true); } if (this.dagSubmissionTimer != null) { this.dagSubmissionTimer.cancel(); } stopServices(); boolean deleteTezScratchData = this.amConf.getBoolean( TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE, TezConfiguration.TEZ_AM_STAGING_SCRATCH_DATA_AUTO_DELETE_DEFAULT); if (LOG.isDebugEnabled()) { LOG.debug("Checking whether tez scratch data dir should be deleted, deleteTezScratchData=" + deleteTezScratchData); } if (deleteTezScratchData && this.taskSchedulerEventHandler != null && this.taskSchedulerEventHandler.hasUnregistered()) { if (this.tezSystemStagingDir != null) { try { FileSystem fs = this.tezSystemStagingDir.getFileSystem(this.amConf); boolean deletedStagingDir = fs.delete(this.tezSystemStagingDir, true); if (!deletedStagingDir) { LOG.warn("Failed to delete tez scratch data dir, path=" + this.tezSystemStagingDir); } else { LOG.info("Completed deletion of tez scratch data dir, path=" + this.tezSystemStagingDir); } } catch (IOException e) { LOG.warn("Failed to delete tez scratch data dir", e); } } } super.serviceStop(); }
Source:
<code>public String getPassword(SessionContext session, NamedResource resourceKey, int retryIndex) throws IOException { char[] password = null; if (credentialSourceSupplier != null) { CredentialSource credentialSource = null; try { credentialSource = credentialSourceSupplier.get(); } catch (XMLStreamException e) { <START> log.xmlFailedToCreateCredential(e); <END> } password = credentialSource.applyToCredential(PasswordCredential.class, c -> c.getPassword().castAndApply(ClearPassword.class, ClearPassword::getPassword)); } else if (credential != null) { password = credential.castAndApply(PasswordCredential.class, c -> c.getPassword().castAndApply(ClearPassword.class, ClearPassword::getPassword)); } return new String(password); }</code><technical_language>throw log.xmlFailedToCreateCredential(e);</technical_language>

Target:
public String getPassword(SessionContext session, NamedResource resourceKey, int retryIndex) throws IOException { char[] password = null; if (credentialSourceSupplier != null) { CredentialSource credentialSource = null; try { credentialSource = credentialSourceSupplier.get(); } catch (XMLStreamException e) { throw log.xmlFailedToCreateCredential(e); } password = credentialSource.applyToCredential(PasswordCredential.class, c -> c.getPassword().castAndApply(ClearPassword.class, ClearPassword::getPassword)); } else if (credential != null) { password = credential.castAndApply(PasswordCredential.class, c -> c.getPassword().castAndApply(ClearPassword.class, ClearPassword::getPassword)); } if (password == null) { throw log.xmlFailedToCreateCredential(new NullPointerException()); } return new String(password); }