auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object eval(Object[] args, EvaluationContext ec) { if(!locationUpdatesRequested) requestLocationUpdates(); <START> if(location == null) return ""; <END> return location.getDisplayText(); }</code><technical_language>of coding styles try adhere is braces for conditional bodies. more verbose easier add else statements is consistent rest of codebase</technical_language>

Target:
public Object eval(Object[] args, EvaluationContext ec) { if (!locationUpdatesRequested) { requestLocationUpdates(); } if (location == null) { return ""; } return location.getDisplayText(); }
Source:
<code>protected String doInBackground(String... params) { <START> String response = ""; <END> Map<String, String> request_params = new HashMap<String, String>(); request_params.put("grant_type", "refresh_token"); request_params.put("refresh_token", token.getRefreshToken()); request_params.put("scope", "PRODUCTION"); APIUtilities apiUtilities = new APIUtilities(); apiUtilities.setEndPoint(IdentityProxy.getInstance().getAccessTokenURL()); apiUtilities.setHttpMethod("POST"); apiUtilities.setRequestParamsMap(request_params); Map<String, String> headers = new HashMap<String, String>(); Log.e("proxy", IdentityProxy.clientID + ":" + IdentityProxy.clientSecret); String authorizationString = "Basic " + new String( Base64.encodeBase64((IdentityProxy.clientID + ":" + IdentityProxy.clientSecret).getBytes()) ); headers.put("Authorization", authorizationString); headers.put("Content-Type", "application/x-www-form-urlencoded"); Map<String, String> response_params = ServerApiAccess.postDataAPI(apiUtilities, headers); response = response_params.get("response"); responseCode = response_params.get("status"); Log.d(TAG, response); return response; }</code><technical_language>Is right assign empty string default of response? complications do if "null"</technical_language>

Target:
protected String doInBackground(String... params) { String response = null; Map<String, String> requestParams = new HashMap<String, String>(); requestParams.put(Constants.GRANT_TYPE, Constants.REFRESH_TOKEN); requestParams.put(Constants.REFRESH_TOKEN, token.getRefreshToken()); requestParams.put(SCOPE_LABEL, PRODUCTION_LABEL); EndPointInfo apiUtilities = new EndPointInfo(); apiUtilities.setEndPoint(IdentityProxy.getInstance().getAccessTokenURL()); apiUtilities.setHttpMethod(HTTP_METHODS.POST); apiUtilities.setRequestParamsMap(requestParams); byte[] credentials = Base64.encodeBase64((IdentityProxy.clientID + COLON + IdentityProxy.clientSecret).getBytes()); String encodedCredentials = new String(credentials); Map<String, String> headers = new HashMap<String, String>(); String authorizationString = Constants.AUTHORIZATION_MODE + encodedCredentials; headers.put(Constants.AUTHORIZATION_HEADER, authorizationString); headers.put(Constants.CONTENT_TYPE_HEADER, Constants.DEFAULT_CONTENT_TYPE); Map<String, String> responseParams = null; try { responseParams = ServerUtilities.postDataAPI(apiUtilities, headers); } catch (IDPTokenManagerException e) { Log.e(TAG, "Failed to contact server." + e); } response = responseParams.get(Constants.SERVER_RESPONSE_BODY); responseCode = responseParams.get(Constants.SERVER_RESPONSE_STATUS); return response; }
Source:
<code>private Answer executeRequest(ShutDownVpcVspCommand cmd) { try { isNuageVspElementLoaded(); _nuageVspElementClient.shutdownVpc(cmd.getDomainUuid(), cmd.getVpcUuid(), cmd.getDomainTemplateName()); return new ShutDownVpcVspAnswer(cmd, true, "Shutdown VPC " + cmd.getVpcUuid()); <START> } catch (Exception e) { <END> s_logger.error("Failure during " + cmd, e); return new ShutDownVpcVspAnswer(cmd, e); } }</code><technical_language>unchecked checked exceptions caught? catching expected checked exceptions, allow unchecked exceptions simply bubble out</technical_language>

Target:
private Answer executeRequest(ShutDownVpcVspCommand cmd) { try { isNuageVspElementLoaded(); _nuageVspElementClient.shutdownVpc(cmd.getDomainUuid(), cmd.getVpcUuid(), cmd.getDomainTemplateName()); return new Answer(cmd, true, "Shutdown VPC " + cmd.getVpcUuid() + " on Nuage VSD " + _hostName); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failure during " + cmd + " on Nuage VSD " + _hostName, e); return new Answer(cmd, e); } }
Source:
<code>public void registerStageTaskRecoveryCallback(StageTaskRecoveryCallback stageTaskRecoveryCallback) { <START> checkState(!this.stageTaskRecoveryCallback.isPresent(), "stageTaskRecoveryCallback should only be registered once"); <END> this.stageTaskRecoveryCallback = Optional.of(stageTaskRecoveryCallback); }</code><technical_language>nit: ..</technical_language>

Target:
public synchronized void registerStageTaskRecoveryCallback(StageTaskRecoveryCallback stageTaskRecoveryCallback) { checkState(!this.stageTaskRecoveryCallback.isPresent(), "stageTaskRecoveryCallback should be registered only once"); this.stageTaskRecoveryCallback = Optional.of(requireNonNull(stageTaskRecoveryCallback, "stageTaskRecoveryCallback is null")); }
Source:
<code>public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); Framework.doPrivileged(() -> { if (um != null) { createUsersAndGroups(um); } <START> }); <END> }</code><technical_language>if (um != null) { Framework.doPrivileged(() -> createUsersAndGroups(um)); }</technical_language>

Target:
public void populate(CoreSession session) throws ClientException { UserManager um = Framework.getLocalService(UserManager.class); if (um != null) { Framework.doPrivileged(() -> createUsersAndGroups(um)); } }
Source:
<code>private String getDistanceLabel(Location otherLocation) { <START> final int distance = getDistance(otherLocation); <END> if (showImperial) { final double feet = distance * METER_TO_FEET; if (feet < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_feet, (int)feet); } else { return getString(R.string.nearby_distance_in_miles, feet / ONE_MILE); } } else { if (distance < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_meters, distance); } else { return getString(R.string.nearby_distance_in_kilometers, distance / ONE_KM_D); } } }</code><technical_language>good rename distance "meters"</technical_language>

Target:
private String getDistanceLabel(Location otherLocation) { final int meters = getDistance(otherLocation); if (showImperial) { final double feet = meters * METER_TO_FEET; if (feet < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_feet, (int)feet); } else { return getString(R.string.nearby_distance_in_miles, feet / ONE_MILE); } } else { if (meters < ONE_THOUSAND) { return getString(R.string.nearby_distance_in_meters, meters); } else { return getString(R.string.nearby_distance_in_kilometers, meters / ONE_THOUSAND_D); } } }
Source:
<code>protected Response addVm(VmStatic staticVm, VM vm, Guid storageDomainId, Guid templateId) { VmManagementParametersBase params = new VmManagementParametersBase(staticVm); params.setVmPayload(getPayload(vm)); if (vm.isSetMemoryPolicy() && vm.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(vm.getMemoryPolicy().isBallooning()); } params.setStorageDomainId(storageDomainId); params.setDiskInfoDestinationMap(getDisksToClone(vm.getDisks(), templateId)); params.setMakeCreatorExplicitOwner(shouldMakeCreatorExplicitOwner()); if (vm.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(vm.isConsoleDeviceEnabled()); <START> } <END> return performCreate(VdcActionType.AddVm, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class)); }</code><technical_language>same. "else"</technical_language>

Target:
protected Response addVm(VmStatic staticVm, VM vm, Guid storageDomainId, Guid templateId) { VmManagementParametersBase params = new VmManagementParametersBase(staticVm); params.setVmPayload(getPayload(vm)); if (vm.isSetMemoryPolicy() && vm.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(vm.getMemoryPolicy().isBallooning()); } params.setStorageDomainId(storageDomainId); params.setDiskInfoDestinationMap(getDisksToClone(vm.getDisks(), templateId)); params.setMakeCreatorExplicitOwner(shouldMakeCreatorExplicitOwner()); params.setConsoleEnabled(vm.isSetConsole() && vm.getConsole().isSetEnabled() ? vm.getConsole().isEnabled() : !getConsoleDevicesForEntity(templateId).isEmpty()); return performCreate(VdcActionType.AddVm, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class)); }
Source:
<code>public void completesTerminationFutureExceptionallyIfActorFails() throws Exception { final ActorSystem actorSystem = actorSystemResource.getActorSystem(); final ActorRef supervisor = SupervisorActor.startSupervisorActor(actorSystem); final SupervisorActor.StartAkkaRpcActorResponse startResponse = SupervisorActor.startAkkaRpcActor( supervisor, terminationFuture -> Props.create(SimpleActor.class, terminationFuture), "foobar"); final SupervisorActor.ActorRegistration actorRegistration = startResponse.orElseThrow(cause -> new AssertionError("Expected the start to succeed.", cause)); final CompletableFuture<Void> terminationFuture = actorRegistration.getTerminationFuture(); assertThat(terminationFuture.isDone(), is(false)); final CompletableFuture<Terminated> actorSystemTerminationFuture = actorSystem.getWhenTerminated().toCompletableFuture(); final FlinkException cause = new FlinkException("Test cause."); actorRegistration.getActorRef().tell(Fail.exceptionally(cause), ActorRef.noSender()); try { terminationFuture.get(); fail("Expected the termination future being completed exceptionally"); } catch (ExecutionException expected) { <START> final Throwable ignored = ExceptionUtils.findThrowable(expected, e -> e.equals(cause)) <END> .orElseThrow(() -> new FlinkException("Unexpected exception", expected)); } actorSystemTerminationFuture.join(); }</code><technical_language>assign throwable in place? in completesTerminationFutureExceptionallyIfActorStopsExceptionally()</technical_language>

Target:
public void completesTerminationFutureExceptionallyIfActorFails() throws Exception { final ActorSystem actorSystem = actorSystemResource.getActorSystem(); final ActorRef supervisor = SupervisorActor.startSupervisorActor(actorSystem, actorSystem.getDispatcher()); final SupervisorActor.ActorRegistration actorRegistration = startAkkaRpcActor(supervisor, "foobar"); final CompletableFuture<Void> terminationFuture = actorRegistration.getTerminationFuture(); assertThat(terminationFuture.isDone(), is(false)); final CompletableFuture<Terminated> actorSystemTerminationFuture = actorSystem.getWhenTerminated().toCompletableFuture(); final FlinkException cause = new FlinkException("Test cause."); actorRegistration.getActorRef().tell(Fail.exceptionally(cause), ActorRef.noSender()); try { terminationFuture.get(); fail("Expected the termination future being completed exceptionally"); } catch (ExecutionException expected) { ExceptionUtils.findThrowable(expected, e -> e.equals(cause)) .orElseThrow(() -> new FlinkException("Unexpected exception", expected)); } actorSystemTerminationFuture.join(); }
Source:
<code>private byte[] doCipherAction( byte[] data, byte[] additionalAuthData, byte[] keyBytes, byte[] ivBytes, int opmode) throws AEADBadTagException { try { ByteBuffer secretKeyAndSaltBuffer = ByteBuffer.wrap(keyBytes); byte[] secretKeyBytes = new byte[keyBytes.length - <START> SALT_LEN]; <END> byte[] salt = new byte[SALT_LEN]; secretKeyAndSaltBuffer.get(secretKeyBytes); secretKeyAndSaltBuffer.get(salt); SecretKeySpec key = new SecretKeySpec(secretKeyBytes, getAlgorithmName()); ByteBuffer nonceBuffer = ByteBuffer.allocate(SALT_LEN + ivBytes.length); nonceBuffer.put(salt); nonceBuffer.put(ivBytes); GCMParameterSpec gcmParams = new GCMParameterSpec(mChecksumLen * 8, nonceBuffer.array()); mCipher.init(opmode, key, gcmParams); mCipher.updateAAD(additionalAuthData); ByteBuffer inputBuffer = ByteBuffer.wrap(data); int outputLen = data.length; if (opmode == Cipher.ENCRYPT_MODE) outputLen += mChecksumLen; ByteBuffer outputBuffer = ByteBuffer.allocate(outputLen); mCipher.doFinal(inputBuffer, outputBuffer); return outputBuffer.array(); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ShortBufferException e) { if (e instanceof AEADBadTagException) { throw (AEADBadTagException) e; } String errorMessage = Cipher.ENCRYPT_MODE == opmode ? "Failed to encrypt data: " : "Failed to decrypt data: "; throw new IllegalArgumentException(errorMessage, e); } }</code><technical_language>This able a constant if SALT_LEN is for algorithms</technical_language>

Target:
private byte[] doCipherAction( byte[] data, byte[] additionalAuthData, byte[] keyBytes, byte[] ivBytes, int opmode) throws AEADBadTagException { try { ByteBuffer secretKeyAndSaltBuffer = ByteBuffer.wrap(keyBytes); byte[] secretKeyBytes = new byte[keyBytes.length - mSaltLen]; byte[] salt = new byte[mSaltLen]; secretKeyAndSaltBuffer.get(secretKeyBytes); secretKeyAndSaltBuffer.get(salt); SecretKeySpec key = new SecretKeySpec(secretKeyBytes, getAlgorithmName()); ByteBuffer nonceBuffer = ByteBuffer.allocate(mSaltLen + ivBytes.length); nonceBuffer.put(salt); nonceBuffer.put(ivBytes); GCMParameterSpec gcmParams = new GCMParameterSpec(mChecksumLen * 8, nonceBuffer.array()); mCipher.init(opmode, key, gcmParams); mCipher.updateAAD(additionalAuthData); ByteBuffer inputBuffer = ByteBuffer.wrap(data); int outputLen = data.length; if (opmode == Cipher.ENCRYPT_MODE) outputLen += mChecksumLen; ByteBuffer outputBuffer = ByteBuffer.allocate(outputLen); mCipher.doFinal(inputBuffer, outputBuffer); return outputBuffer.array(); } catch (AEADBadTagException e) { throw (AEADBadTagException) e; } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ShortBufferException e) { String errorMessage = Cipher.ENCRYPT_MODE == opmode ? "Failed to encrypt data: " : "Failed to decrypt data: "; throw new IllegalArgumentException(errorMessage, e); } }
Source:
<code>public void close() throws IOException { if(!completedFiles.isEmpty()) { <START> for(File file: completedFiles) <END> { file.delete(); } throw new ISE(String.format("%d writers needs to be closed before closing smoosher.", filesInProcess.size())); } if (currOut != null) { currOut.close(); } File metaFile = metaFile(baseDir); try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaFile), Charsets.UTF_8))) { out.write(String.format("v1,%d,%d", maxChunkSize, outFiles.size())); out.write("\n"); for (Map.Entry<String, Metadata> entry : internalFiles.entrySet()) { final Metadata metadata = entry.getValue(); out.write( joiner.join( entry.getKey(), metadata.getFileNum(), metadata.getStartOffset(), metadata.getEndOffset() ) ); out.write("\n"); } } }</code><technical_language>a space for</technical_language>

Target:
public void close() throws IOException { if (!completedFiles.isEmpty() || !filesInProcess.isEmpty()) { for (File file: completedFiles) { file.delete(); } for (File file: filesInProcess) { file.delete(); } throw new ISE(String.format("%d writers needs to be closed before closing smoosher.", filesInProcess.size() + completedFiles.size())); } if (currOut != null) { currOut.close(); } File metaFile = metaFile(baseDir); try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaFile), Charsets.UTF_8))) { out.write(String.format("v1,%d,%d", maxChunkSize, outFiles.size())); out.write("\n"); for (Map.Entry<String, Metadata> entry : internalFiles.entrySet()) { final Metadata metadata = entry.getValue(); out.write( joiner.join( entry.getKey(), metadata.getFileNum(), metadata.getStartOffset(), metadata.getEndOffset() ) ); out.write("\n"); } } }
Source:
<code>public void handle(String tenantId, List<T> items) throws Exception { List<R> results = null; List<T> retries = null; Exception lastException = null; processor.initialise(tenantId, items); if (processor.getType() == ProcessorType.ManyToMany) { try { results = processor.processManyToMany(tenantId, items); } catch (Exception e) { retries = items; } } else { <START> for (int i = 0; i < items.size(); i++) { <END> try { if (processor.getType() == ProcessorType.OneToMany) { List<R> result = processor.processOneToMany(tenantId, items.get(i)); if (resultHandler != null && result != null && !result.isEmpty()) { if (results == null) { results = new ArrayList<R>(); } results.addAll(result); } } else { R result = processor.processOneToOne(tenantId, items.get(i)); if (resultHandler != null && result != null) { if (results == null) { results = new ArrayList<R>(); } results.add(result); } } } catch (Exception e) { if (retryHandler != null) { if (retries == null) { retries = new ArrayList<T>(); } retries.add(items.get(i)); lastException = e; } } } } processor.cleanup(tenantId, items); if (results != null && !results.isEmpty()) { resultHandler.handle(tenantId, results); } if (retries != null && !retries.isEmpty()) { if (getRetryCount() > 0) { retryHandler.handle(tenantId, retries); } else { throw lastException; } } }</code><technical_language>a stream here, instead of a loop? Due operations done loop, I this is a perfect candidate for streams :)</technical_language>

Target:
public void handle(String tenantId, List<T> items) throws Exception { List<R> results = null; List<T> retries = null; Exception lastException = null; processor.initialise(tenantId, items); long startTime = 0; if (perfLog.isLoggable(Level.FINEST)) { startTime = System.currentTimeMillis(); } if (processor.getType() == ProcessorType.ManyToMany) { try { results = processor.processManyToMany(tenantId, items); } catch (Exception e) { retries = items; } } else { for (int i = 0; i < items.size(); i++) { try { if (processor.getType() == ProcessorType.OneToMany) { List<R> result = processor.processOneToMany(tenantId, items.get(i)); if (resultHandler != null && result != null && !result.isEmpty()) { if (results == null) { results = new ArrayList<R>(); } results.addAll(result); } } else { R result = processor.processOneToOne(tenantId, items.get(i)); if (resultHandler != null && result != null) { if (results == null) { results = new ArrayList<R>(); } results.add(result); } } } catch (Exception e) { if (retryHandler != null) { if (retries == null) { retries = new ArrayList<T>(); } retries.add(items.get(i)); lastException = e; } } } } if (perfLog.isLoggable(Level.FINEST)) { perfLog.finest("Performance: invoked processor +processor.getClass().getSimpleName()+ duration=" + (System.currentTimeMillis() - startTime) + "ms"); } processor.cleanup(tenantId, items); if (results != null && !results.isEmpty()) { resultHandler.handle(tenantId, results); } if (retries != null && !retries.isEmpty()) { if (getRetryCount() > 0) { retryHandler.handle(tenantId, retries); } else { throw lastException; } } }
Source:
<code>public IStatus validateBeforeSet(Object value) { final BundleContext bundleContext = FrameworkUtil .getBundle(getClass()) .getBundleContext(); final ServiceReference<PreSetValidationService> serviceReference = bundleContext .getServiceReference(PreSetValidationService.class); final PreSetValidationService service = <START> bundleContext.getService(serviceReference); <END> if (service == null) { return Status.OK_STATUS; } final Diagnostic result = service.validate(eStructuralFeature, value); if (result.getSeverity() == Diagnostic.OK) { return Status.OK_STATUS; } final VDiagnostic vDiagnostic = VViewFactory.eINSTANCE.createDiagnostic(); vDiagnostic.getDiagnostics().add(result); vElement.setDiagnostic(vDiagnostic); return BasicDiagnostic.toIStatus(result); }</code><technical_language>Unget service usage</technical_language>

Target:
public IStatus validateBeforeSet(Object value) { final BundleContext bundleContext = FrameworkUtil .getBundle(getClass()) .getBundleContext(); final ServiceReference<PreSetValidationService> serviceReference = bundleContext .getServiceReference(PreSetValidationService.class); if (serviceReference == null) { return super.validateBeforeSet(value); } try { final PreSetValidationService service = bundleContext.getService(serviceReference); if (service == null) { return super.validateBeforeSet(value); } final Diagnostic result = service.validate(eStructuralFeature, value); if (result.getSeverity() == Diagnostic.OK) { return Status.OK_STATUS; } final VDiagnostic vDiagnostic = VViewFactory.eINSTANCE.createDiagnostic(); vDiagnostic.getDiagnostics().add(result); vElement.setDiagnostic(vDiagnostic); return BasicDiagnostic.toIStatus(result); } finally { bundleContext.ungetService(serviceReference); } }
Source:
<code>public void addAdminUserToOrganization( UserInfo user, OrganizationInfo organization, boolean email ) throws Exception { if ( ( user == null ) || ( organization == null ) ) { return; } EntityManager em = emf.getEntityManager( smf.getManagementAppId() ); if(em.getCollection(organization.getUuid() ,"users",Query.fromQL( "select * where uuid ="+user.getUuid() ),Level.IDS ).size() >0){ <START> logger.trace( "Found value: already in collection",user.getName() ); <END> return; } em.addToCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organization.getUuid()), "users", new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid())); if ( email ) { sendAdminUserInvitedEmail( user, organization ); } }</code><technical_language>change debug level wrap in if statement for isDebugEnabled</technical_language>

Target:
public void addAdminUserToOrganization( UserInfo user, OrganizationInfo organization, boolean email ) throws Exception { if ( ( user == null ) || ( organization == null ) ) { return; } EntityManager em = emf.getEntityManager( smf.getManagementAppId() ); if(em.getCollection(organization.getUuid() ,"users",Query.fromQL( "select * where uuid ="+user.getUuid() ),Level.IDS ).size() >0){ if(logger.isDebugEnabled()) { logger.debug( "Found value: already in collection", user.getName() ); } return; } em.addToCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organization.getUuid()), "users", new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid())); if ( email ) { sendAdminUserInvitedEmail( user, organization ); } }
Source:
<code>public RedisConfiguration(ConfigurationPropertyReader propertyReader) { String host = propertyReader.property( OgmProperties.HOST, String.class ) .withDefault( DEFAULT_HOST ) .getValue(); <START> Integer port = propertyReader.property( OgmProperties.PORT, Integer.class ) <END> .withValidator( Validators.PORT ) .withDefault( null ) .getValue(); hosts = HostParser.parse( host, port, DEFAULT_PORT ); databaseNumber = propertyReader.property( OgmProperties.PORT, Integer.class ) .withValidator( Validators.PORT ) .withDefault( RedisURI.DEFAULT_REDIS_PORT ) .getValue(); this.password = propertyReader.property( OgmProperties.PASSWORD, String.class ).getValue(); }</code><technical_language>deprecated PORT (HOST is a (list of) host/port tuple(s) now). add new data stores</technical_language>

Target:
public RedisConfiguration(ConfigurationPropertyReader propertyReader) { String host = propertyReader.property( OgmProperties.HOST, String.class ) .withDefault( DEFAULT_HOST ) .getValue(); this.hosts = HostParser.parse( host, null, DEFAULT_PORT ); this.databaseNumber = propertyReader.property( OgmProperties.DATABASE, Integer.class ) .withValidator( DATABASE_VALIDATOR ) .withDefault( DEFAULT_DATABASE ) .getValue(); this.password = propertyReader.property( OgmProperties.PASSWORD, String.class ).getValue(); this.timeout = propertyReader .property( RedisProperties.TIMEOUT, Integer.class ) .withDefault( (int) DEFAULT_TIMEOUT ) .getValue(); this.ssl = propertyReader .property( RedisProperties.SSL, boolean.class ) .withDefault( false ) .getValue(); }
Source:
<code>public String removeQualifierFromRuleText( String ruleText ) { <START> if( ruleText.startsWith( "%" ) && ruleText.endsWith( "%" ) ) <END> { return ruleText.substring( 1, ruleText.length() - 1 ); } else if( ruleText.startsWith( "%" ) ) { return ruleText.substring( 1 ); } else if( ruleText.endsWith( "%" ) ) { return ruleText.substring( 0, ruleText.length() - 1 ); } else { return ruleText; } }</code><technical_language>String rule = ruleText; if (rule.startsWith("%") rule = substring(1); if (rule.endsWith("%") rule = substring(0, rule.length() - 1); return rule;</technical_language>

Target:
public String removeQualifierFromRuleText( String ruleText ) { String rule = ruleText; if( rule.startsWith( "%" ) ) { rule = rule.substring( 1 ); } if( rule.endsWith( "%" ) ) { rule = rule.substring( 0, rule.length() - 1 ); } return rule; }
Source:
<code>public Map<Cell, Value> getRows(TableReference tableRef, Iterable<byte[]> rows, ColumnSelection columnSelection, long timestamp) { return maybeLog(() -> delegate.getRows(tableRef, rows, columnSelection, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRows on table requesting columns from rows took ms ", tableRef, columnSelection.allColumnsSelected() ? "all" : Iterables.size(columnSelection.getSelectedColumns()), Iterables.size(rows), stopwatch.elapsed(TimeUnit.MILLISECONDS)), (logger, result) -> { <START> long sizeInBytes = 0; <END> for (Entry<Cell, Value> entry : result.entrySet()) { sizeInBytes += Cells.getApproxSizeOfCell(entry.getKey()) + entry.getValue().getContents().length; } logger.log("and returned bytes.", sizeInBytes); }); }</code><technical_language>bit of duplication here</technical_language>

Target:
public Map<Cell, Value> getRows(TableReference tableRef, Iterable<byte[]> rows, ColumnSelection columnSelection, long timestamp) { return maybeLog(() -> delegate.getRows(tableRef, rows, columnSelection, timestamp), (logger, stopwatch) -> logger.log( "Call to KVS.getRows on table requesting columns from rows took ms ", tableRef, columnSelection.allColumnsSelected() ? "all" : Iterables.size(columnSelection.getSelectedColumns()), Iterables.size(rows), stopwatch.elapsed(TimeUnit.MILLISECONDS)), logCellResultSize(0L)); }
Source:
<code><START> public ChainFilter() { <END> this(RowFilter.Chain.newBuilder()); }</code><technical_language>please limit visibility of constructor</technical_language>

Target:
private ChainFilter() { this(RowFilter.Chain.newBuilder()); }
Source:
<code>public FeatureFinderMetaboDetector(File mzMLFile) throws FeatureFinderMetaboException { this.mzMLFile = mzMLFile; <START> FEATURE_XML_FILE = new File(mzMLFile.getName() + "featureXML"); <END> OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME = FeatureFinderMetaboLocator.findFeatureFinderMetabo(); }</code><technical_language>File.createTempFile() here? combine File.deleteOnExit()</technical_language>

Target:
public FeatureFinderMetaboDetector(File mzMLFile) throws MSDKException { this.mzMLFile = mzMLFile; FEATURE_XML_FILE = new File(System.getProperty("java.io.tmpdir") + UUID.randomUUID() + ".featureXML"); OPENMS_FEATURE_FINDER_METABO_LIBRARY_NAME = FeatureFinderMetaboLocator.findFeatureFinderMetabo(); mzMLFILE_PATH = mzMLFile.getAbsolutePath(); FEATURE_XML_FILE_PATH = FEATURE_XML_FILE.getAbsolutePath(); }
Source:
<code>public Identity decode(final byte[] bytes) throws IOException { <START> final String[] parts = new Utf8String(bytes).asString().split(";"); <END> final Map<String, String> map = new HashMap<>(parts.length); for (int idx = 1; idx < parts.length; ++idx) { final String[] pair = parts[idx].split("="); try { map.put(pair[0], CcPlain.decode(pair[1])); } catch (final IllegalArgumentException ex) { throw new DecodingException(ex); } } return new Identity.Simple(CcPlain.decode(parts[0]), map); }</code><technical_language>@ikhvostenkov please SplitText</technical_language>

Target:
public Identity decode(final byte[] bytes) throws IOException { final List<Text> parts = new ListOf<>( new SplitText( new Utf8String(bytes), ";" ) ); final Map<String, String> map = new HashMap<>(parts.size()); for (int idx = 1; idx < parts.size(); ++idx) { final List<Text> pair = new ListOf<>( new SplitText(parts.get(idx), "=") ); try { map.put( new UncheckedText(pair.get(0)).asString(), CcPlain.decode(new UncheckedText(pair.get(1)).asString()) ); } catch (final IllegalArgumentException ex) { throw new DecodingException(ex); } } return new Identity.Simple( CcPlain.decode( new UncheckedText(parts.get(0)).asString() ), map ); }
Source:
<code><START> public void testAddDropColumn() throws Exception { <END> Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL); conn.setAutoCommit(true); try { conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (tenant_id, id, tenant_col) values ('" + TENANT_ID + "', 1, 'Viva Las Vegas')"); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " add tenant_col2 char(1) null"); int count = conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (tenant_id, id, tenant_col2) values ('" + TENANT_ID + "', 2, 'a')"); ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME); rs.next(); assertEquals(2, rs.getInt(1)); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + " where tenant_col2 = 'a'"); rs.next(); assertEquals(1, rs.getInt(1)); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " drop column tenant_col"); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + ""); rs.next(); assertEquals(2, rs.getInt(1)); try { rs = conn.createStatement().executeQuery("select tenant_col from TENANT_TABLE"); } catch (ColumnNotFoundException expected) } finally { conn.close(); } }</code><technical_language>Awesome work far, Eli</technical_language>

Target:
public void testAddDropColumn() throws Exception { Connection conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL); conn.setAutoCommit(true); try { conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col) values (1, 'Viva Las Vegas')"); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " add tenant_col2 char(1) null"); conn.createStatement().executeUpdate("upsert into " + TENANT_TABLE_NAME + " (id, tenant_col2) values (2, 'a')"); ResultSet rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME); rs.next(); assertEquals(2, rs.getInt(1)); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + " where tenant_col2 = 'a'"); rs.next(); assertEquals(1, rs.getInt(1)); conn.createStatement().execute("alter table " + TENANT_TABLE_NAME + " drop column tenant_col"); rs = conn.createStatement().executeQuery("select count(*) from " + TENANT_TABLE_NAME + ""); rs.next(); assertEquals(2, rs.getInt(1)); try { rs = conn.createStatement().executeQuery("select tenant_col from TENANT_TABLE"); fail(); } catch (ColumnNotFoundException expected) } finally { conn.close(); } }
Source:
<code>private String determineJdbcUrl() { StringBuilder url = new StringBuilder(); if (StringUtils.hasText(getJdbcUrl())) { <START> url.append(getJdbcUrl()); <END> } else { url.append("jdbc:mysql://"); url.append(getHost()).append(":").append(getPort()); url.append("/").append(getDb()); url.append("?autoReconnect=true"); url.append("&useSSL=").append(isUseSsl()); url.append("&useUnicode=yes&characterEncoding=UTF-8"); } return url.toString(); }</code><technical_language>nit: stringbuilder here. exit early retain existing logic if present</technical_language>

Target:
private String determineJdbcUrl() { if (StringUtils.hasText(getJdbcUrl())) { return getJdbcUrl(); } StringBuilder url = new StringBuilder(); url.append("jdbc:mysql://"); url.append(getHost()).append(":").append(getPort()); url.append("/").append(getDb()); url.append("?autoReconnect=true"); url.append("&useSSL=").append(isUseSsl()); url.append("&useUnicode=yes&characterEncoding=UTF-8"); return url.toString(); }
Source:
<code>public static String getPlayerNameFromUUID(UUID uuid) { PlayerProfileCache cache = MinecraftServer.getServer().func_152358_ax(); GameProfile maybeGameProfile = cache.func_152652_a( uuid ); if ( maybeGameProfile != null ) { return maybeGameProfile.getName(); } <START> return null; <END> }</code><technical_language>Do return null, Optional</technical_language>

Target:
public static String getPlayerNameFromUUID(UUID uuid) { return UsernameCache.getLastKnownUsername(uuid); }
Source:
<code>public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } <START> callback.onCompletion(null, exception); <END> frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); }</code><technical_language>this callback I</technical_language>

Target:
public void postProcessRequest(RestRequest restRequest, Callback<Void> callback) { Exception exception = null; frontendMetrics.securityServicePostProcessRequestRate.mark(); long startTimeMs = System.currentTimeMillis(); if (!isOpen) { exception = new RestServiceException("SecurityService is closed", RestServiceErrorCode.ServiceUnavailable); } else if (restRequest == null || callback == null) { throw new IllegalArgumentException("RestRequest or Callback is null"); } frontendMetrics.securityServicePostProcessRequestTimeInMs.update(System.currentTimeMillis() - startTimeMs); callback.onCompletion(null, exception); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; <START> HttpSession session = req.getSession(false); <END> if ((req.getHeader("Authorization") != null)) { if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); }</code><technical_language>do get session here? move condition them</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if ((req.getHeader("Authorization") != null)) { HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); }
Source:
<code>public final void registerHandlerFor(String subject) { <START> LOGGER.debug("Registering handler for {}", subject); <END> String serviceName = "taskTriggerHandler"; Method method = ReflectionUtils.findMethod(this.getClass(), "handle", MotechEvent.class); Object obj = CollectionUtils.find( registryService.getListeners(subject), withServiceName(serviceName) ); try { if (method != null && obj == null) { EventListener proxy = new MotechListenerEventProxy(serviceName, this, method); registryService.registerListener(proxy, subject); LOGGER.info(String.format("%s listens on subject %s", serviceName, subject)); } } catch (Exception exp) { LOGGER.error( String.format("%s can not listen on subject %s due to:", serviceName, subject), exp ); } }</code><technical_language>This info if loggin is in info</technical_language>

Target:
public final void registerHandlerFor(String subject) { LOGGER.info("Registering handler for {}", subject); String serviceName = "taskTriggerHandler"; Method method = ReflectionUtils.findMethod(this.getClass(), "handle", MotechEvent.class); Object obj = CollectionUtils.find( registryService.getListeners(subject), withServiceName(serviceName) ); try { if (method != null && obj == null) { EventListener proxy = new MotechListenerEventProxy(serviceName, this, method); registryService.registerListener(proxy, subject); LOGGER.info(String.format("%s listens on subject %s", serviceName, subject)); } } catch (Exception exp) { LOGGER.error( String.format("%s can not listen on subject %s due to:", serviceName, subject), exp ); } }
Source:
<code>public StudentProfile(String fullName, StudentProfileAttributes student, String pictureUrl) { this.pictureUrl = pictureUrl; this.name = fullName; this.shortName = student.shortName; <START> this.gender = Gender.valueOf(student.gender.name()); <END> this.email = student.email; this.institute = student.institute; this.nationality = student.nationality; this.moreInfo = student.moreInfo; }</code><technical_language>this.gender = student.gender</technical_language>

Target:
public StudentProfile(String fullName, StudentProfileAttributes student, String pictureUrl) { this.pictureUrl = pictureUrl; this.name = fullName; this.shortName = student.shortName; this.gender = student.gender; this.email = student.email; this.institute = student.institute; this.nationality = student.nationality; this.moreInfo = student.moreInfo; }
Source:
<code><START> public void handleNewSession(final String sessionId) throws Exception { <END> }</code><technical_language>I reached agreement method signature, double check - users extending this class, right? try this backward-compatible in case users this public method</technical_language>

Target:
public void handleNewSession(final String sessionId) throws Exception { handleNewSession(); }
Source:
<code><START> private Entry lookupUser(String username) throws LdapException { <END> for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { EntryCursor responseCursor = connection.search(userDn, "(&(objectclass=user)(" + attrName + "=" + username + "))", SearchScope.SUBTREE); try { try { if (responseCursor != null && responseCursor.next()) { return responseCursor.get(); } } catch (CursorException e) { logger.debug("LDAP search error", e); return null; } } finally { responseCursor.close(); } } } return null; }</code><technical_language>Nice, I it! suggestion though: I do a logical in LDAP queries. I preferable making multiple queries in for loop</technical_language>

Target:
private Entry lookupUser(String username) throws LdapException { StringBuilder userQuery = new StringBuilder(); userQuery.append("(&(objectclass=user)(|"); boolean hasCondition = false; for (String lookupAttr : lookupAttrs) { String attrName = lookupAttr.trim(); if (!attrName.isEmpty()) { userQuery.append('(').append(attrName).append('=').append(username).append(')'); hasCondition = true; } } userQuery.append("))"); if (!hasCondition) { return null; } logger.debug("LDAP user query " + userQuery.toString()); EntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE); try { try { if (responseCursor != null && responseCursor.next()) { Entry match = responseCursor.get(); logger.debug("LDAP user query result: " + match.getDn()); return match; } } catch (CursorException e) { logger.debug("LDAP search error", e); return null; } } finally { responseCursor.close(); } return null; }
Source:
<code><START> public Multimap<String, String> getQueryParams() { <END> return queryParams; }</code><technical_language>This breaks public API of HttpMessage. in this case, break API returned is able represent query parameter content specification. Nevertheless, recommend wit a Map<String, Collection<String>> guava stuff internal java standard conform interface outer world</technical_language>

Target:
public Map<String, Collection<String>> getQueryParams() { return queryParams; }
Source:
<code>public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { final Jenkins j = Jenkins.get(); final JCloudsSlaveDescriptor jcsd = (JCloudsSlaveDescriptor) j.getDescriptor(JCloudsSlave.class); <START> return jcsd.nodePropertyDescriptors(null); <END> }</code><technical_language>#getDescriptorOrDie() throw exception</technical_language>

Target:
public List<NodePropertyDescriptor> getNodePropertiesDescriptors() { final Jenkins j = Jenkins.get(); final JCloudsSlaveDescriptor jcsd = (JCloudsSlaveDescriptor) j.getDescriptorOrDie(JCloudsSlave.class); return jcsd.nodePropertyDescriptors(null); }
Source:
<code><START> public void addError(String errorMessage, Element element) { <END> errors.add(new ProblemImpl(errorMessage, name, element)); }</code><technical_language>a lot of calls this method, resulting in errors reference BPMN element. a quick look, of do element id reference</technical_language>

Target:
public void addError(String errorMessage, Element element) { errors.add(new ProblemImpl(errorMessage, element)); }
Source:
<code>protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { if (monitor.isCanceled()) { return false; } @Nullable SegmentStoreStatistics totalStats = getTotalStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (totalStats == null) { return false; } @Nullable Map<@NonNull String, @NonNull SegmentStoreStatistics> perTypeStats = getPerTypeStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); <START> if (perTypeStats == null || perTypeStats.isEmpty()) { <END> return false; } fTotalStats = totalStats; fPerSegmentTypeStats = perTypeStats; return true; }</code><technical_language>If segments, map empty, analysis failed, think</technical_language>

Target:
protected boolean executeAnalysis(IProgressMonitor monitor) throws TmfAnalysisException { if (monitor.isCanceled()) { return false; } @Nullable SegmentStoreStatistics totalStats = getTotalStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (totalStats == null) { return false; } @Nullable Map<@NonNull String, @NonNull SegmentStoreStatistics> perTypeStats = getPerTypeStats(TmfTimeRange.ETERNITY.getStartTime().toNanos(), TmfTimeRange.ETERNITY.getEndTime().toNanos(), monitor); if (perTypeStats == null) { return false; } fTotalStats = totalStats; fPerSegmentTypeStats = perTypeStats; return true; }
Source:
<code>public OptionalDouble getValue() { ModelNode result = readAttributeValue(address, attributeName); if (result.isDefined()) { try { return OptionalDouble.of(result.asDouble()); } catch (Exception e) { <START> throw MetricsLogger.LOGGER.unableToConvertAttribute(attributeName, address, e); <END> } } return OptionalDouble.empty(); }</code><technical_language>This blow entire read. Smallrye I if a Metric throws exception is caught logged loop reading metrics continues, other metrics get reported. A failure abort PrometheusExporter loop. providing Optional this log failure fall through</technical_language>

Target:
public OptionalDouble getValue() { ModelNode result = readAttributeValue(address, attributeName); if (result.isDefined()) { try { return OptionalDouble.of(result.asDouble()); } catch (Exception e) { LOGGER.unableToConvertAttribute(attributeName, address, e); } } return OptionalDouble.empty(); }
Source:
<code>public void testCreatePurchaseWithTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; final String requestId = "testCreatePurchaseWithTimeout"; Request.setPerThreadRequestData(new RequestData(requestId)); final String pluginName = mockPaymentProviderPlugin.PLUGIN_NAME; <START> mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds(10000); <END> SpyLogger spyLogger = withSpyLogger(OperationCallbackBase.class, new Callable<Void>() { @Override public Void call() throws Exception { PaymentApiException thrownException = null; try { final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); } catch (PaymentApiException e) { thrownException = e; } assertNotNull(thrownException); Throwable operationException = thrownException.getCause(); assertNotNull(operationException); assertTrue(operationException instanceof OperationException); Throwable timeoutException = operationException.getCause(); assertNotNull(timeoutException); assertTrue(timeoutException instanceof TimeoutException); return null; } }); assertTrue(spyLogger.contains("Calling plugin.*" + pluginName + ".*" + requestId, Optional.of(SpyLogger.LOG_LEVEL_INFO))); assertTrue(spyLogger.contains("TimeoutException.*" + pluginName + ".*" + requestId, Optional.of(SpyLogger.LOG_LEVEL_ERROR))); }</code><technical_language>10s is a lot! :sweat: reduce 1.1s</technical_language>

Target:
public void testCreatePurchaseWithTimeout() throws Exception { final BigDecimal requestedAmount = BigDecimal.TEN; final String paymentExternalKey = "ohhhh"; final String transactionExternalKey = "naaahhh"; final String pluginName = mockPaymentProviderPlugin.PLUGIN_NAME; mockPaymentProviderPlugin.makePluginWaitSomeMilliseconds(1100); SpyLogger spyLogger = withSpyLogger(OperationCallbackBase.class, new Callable<Void>() { @Override public Void call() throws Exception { PaymentApiException thrownException = null; try { final Payment payment = paymentApi.createPurchase(account, account.getPaymentMethodId(), null, requestedAmount, Currency.AED, paymentExternalKey, transactionExternalKey, ImmutableList.<PluginProperty>of(), callContext); } catch (PaymentApiException e) { thrownException = e; } assertNotNull(thrownException); Throwable operationException = thrownException.getCause(); assertNotNull(operationException); assertTrue(operationException instanceof OperationException); Throwable timeoutException = operationException.getCause(); assertNotNull(timeoutException); assertTrue(timeoutException instanceof TimeoutException); return null; } }); assertTrue(spyLogger.contains("Calling plugin.*" + pluginName, Optional.of(SpyLogger.LOG_LEVEL_DEBUG))); assertTrue(spyLogger.contains("TimeoutException.*" + pluginName, Optional.of(SpyLogger.LOG_LEVEL_WARN))); }
Source:
<code>public void onMessage(Message<Long> message) { long payload = message.getMessageObject(); sleepRandom(random, maxProcessingDelayNanos); if (isStopped(payload)) { totalFoundCounter.addAndGet(count); count = 0; if (!completed) { completed = true; listenersCompleteLatch.countDown(); } <START> topic.removeMessageListener(registrationId); <END> } else { count += message.getMessageObject(); } }</code><technical_language>this means a single "-1" close this listener -> messages other workers ignore -> test failure</technical_language>

Target:
public void onMessage(Message<Long> message) { sleepRandomNanos(random, maxProcessingDelayNanos); count += message.getMessageObject(); }
Source:
<code>void open(Open token) { Publisher<? extends Close> p; C buf; try { buf = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null Collection"); p = ObjectHelper.requireNonNull(bufferClose.apply(token), "The bufferClose returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); SubscriptionHelper.cancel(upstream); <START> if (errors.addThrowable(ex)) { <END> subscribers.dispose(); synchronized (this) { buffers = null; } done = true; drain(); } else { RxJavaPlugins.onError(ex); } return; } long idx = index; index = idx + 1; synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } bufs.put(idx, buf); } BufferCloseSubscriber<T, C> bc = new BufferCloseSubscriber<T, C>(this, idx); subscribers.add(bc); p.subscribe(bc); }</code><technical_language>if/else block exact onError(), call here</technical_language>

Target:
void open(Open token) { Publisher<? extends Close> p; C buf; try { buf = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null Collection"); p = ObjectHelper.requireNonNull(bufferClose.apply(token), "The bufferClose returned a null Publisher"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); SubscriptionHelper.cancel(upstream); onError(ex); return; } long idx = index; index = idx + 1; synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } bufs.put(idx, buf); } BufferCloseSubscriber<T, C> bc = new BufferCloseSubscriber<T, C>(this, idx); subscribers.add(bc); p.subscribe(bc); }