auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static String protectPerforceFilename(String name) { ArrayList<SimpleImmutableEntry<String,String>> transmap = new ArrayList<SimpleImmutableEntry<String,String>>() { { add(new SimpleImmutableEntry<>("%", "%25")); add(new SimpleImmutableEntry<>("#", "%23")); add(new SimpleImmutableEntry<>("\\*", "%2A")); add(new SimpleImmutableEntry<>("@", "%40")); } }; String t = name; for (SimpleImmutableEntry<String,String> ent : transmap) { t = t.replaceAll(ent.getKey(), ent.getValue()); } if (name != t) { <START> LOGGER.log(Level.INFO, <END> "protectPerforceFilename: replaced ''{0}'' with ''{1}''", new Object[]{name, t}); } return t; }</code><technical_language>this Level.FINEST</technical_language>

Target:
static String protectPerforceFilename(String name) { String t = name.replaceAll("%", "%25"); t = t.replaceAll("#", "%23"); t = t.replaceAll("\\*", "%2A"); t = t.replaceAll("@", "%40"); if (name != t) { LOGGER.log(Level.FINEST, "protectPerforceFilename: replaced ''{0}'' with ''{1}''", new Object[]{name, t}); } return t; }
Source:
<code>public void setUpRpcClient() throws Exception { retries = 1; RpcConnectionPool.RpcConnectionKey rpcConnectionKey = new RpcConnectionPool.RpcConnectionKey( RpcUtils.getConnectAddress(server.getListenAddress()), DummyProtocol.class, true); <START> client = new AsyncRpcClient(rpcConnectionKey, retries); <END> stub = client.getStub(); }</code><technical_language>needs acquire connection this code block, initialized test functions</technical_language>

Target:
public void setUpRpcClient() throws Exception { retries = 1; RpcConnectionPool.RpcConnectionKey rpcConnectionKey = new RpcConnectionPool.RpcConnectionKey( RpcUtils.getConnectAddress(server.getListenAddress()), DummyProtocol.class, true); client = new AsyncRpcClient(rpcConnectionKey, retries); client.acquire(RpcConnectionPool.DEFAULT_TIMEOUT); stub = client.getStub(); }
Source:
<code>private InputStream filterClean(InputStream in, OperationType opType) throws IOException { in = handleAutoCRLF(in, opType); String filterCommand = getCleanFilterCommand(); if (filterCommand != null) { if (Repository.isRegistered(filterCommand)) { LocalFile buffer = new TemporaryBuffer.LocalFile(null); FilterCommand command = Repository.getCommand(filterCommand, repository, in, buffer); <START> while (command.run() != -1) ; <END> return buffer.openInputStream(); } else { FS fs = repository.getFS(); ProcessBuilder filterProcessBuilder = fs.runInShell(filterCommand, new String[0]); filterProcessBuilder.directory(repository.getWorkTree()); filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY, repository.getDirectory().getAbsolutePath()); ExecutionResult result; try { result = fs.execute(filterProcessBuilder, in); } catch (IOException | InterruptedException e) { throw new IOException(new FilterFailedException(e, filterCommand, getEntryPathString())); } int rc = result.getRc(); if (rc != 0) { throw new IOException(new FilterFailedException(rc, filterCommand, getEntryPathString(), result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE), RawParseUtils.decode(result.getStderr() .toByteArray(MAX_EXCEPTION_TEXT_SIZE)))); } return result.getStdout().openInputStream(); } } return in; }</code><technical_language>Missing braces</technical_language>

Target:
private InputStream filterClean(InputStream in, OperationType opType) throws IOException { in = handleAutoCRLF(in, opType); String filterCommand = getCleanFilterCommand(); if (filterCommand != null) { if (Repository.isRegistered(filterCommand)) { LocalFile buffer = new TemporaryBuffer.LocalFile(null); FilterCommand command = Repository.getCommand(filterCommand, repository, in, buffer); while (command.run() != -1) { } return buffer.openInputStream(); } FS fs = repository.getFS(); ProcessBuilder filterProcessBuilder = fs.runInShell(filterCommand, new String[0]); filterProcessBuilder.directory(repository.getWorkTree()); filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY, repository.getDirectory().getAbsolutePath()); ExecutionResult result; try { result = fs.execute(filterProcessBuilder, in); } catch (IOException | InterruptedException e) { throw new IOException(new FilterFailedException(e, filterCommand, getEntryPathString())); } int rc = result.getRc(); if (rc != 0) { throw new IOException(new FilterFailedException(rc, filterCommand, getEntryPathString(), result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE), RawParseUtils.decode(result.getStderr() .toByteArray(MAX_EXCEPTION_TEXT_SIZE)))); } return result.getStdout().openInputStream(); } return in; }
Source:
<code>public JmsConfiguration incomingOsgpCoreResponsesJmsConfiguration( final JmsConfigurationFactory jmsConfigurationFactory) { <START> return jmsConfigurationFactory.initializeConfiguration("jms.incoming.osgp.core.responses", <END> this.incomingOsgpCoreResponseMessageListener); }</code><technical_language>JMS Template needed here, initialize JMS Template</technical_language>

Target:
public JmsConfiguration incomingOsgpCoreResponsesJmsConfiguration( final JmsConfigurationFactory jmsConfigurationFactory) { return jmsConfigurationFactory.initializeReceiveConfiguration("jms.incoming.osgp.core.responses", this.incomingOsgpCoreResponseMessageListener); }
Source:
<code>public void setUp() throws IOException { InputStream input = InstrumentationRegistry.getContext().getResources() .openRawResource(com.bugsnag.android.test.R.raw.error); <START> File fixtureFile = File.createTempFile("error", ".json"); <END> OutputStream output = new FileOutputStream(fixtureFile); try { byte[] buffer = new byte[1024]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } finally { output.close(); } error = ErrorReader.readError(new Configuration("key"), fixtureFile); }</code><technical_language>[Buffered IO](<LINK_0> improve efficiency of this test</technical_language>

Target:
public static void setUp() throws IOException { InputStream input = InstrumentationRegistry.getContext().getResources() .openRawResource(com.bugsnag.android.test.R.raw.error); File fixtureFile = File.createTempFile("error", ".json"); OutputStream output = new FileOutputStream(fixtureFile); try { byte[] buffer = new byte[1024]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } output.flush(); } finally { output.close(); } error = ErrorReader.readError(new Configuration("key"), fixtureFile); }
Source:
<code><START> public synchronized void setupManager( <END> String startPoint, String inputFile, String protocol, String host, int port, String extention, int ThreadNumber, boolean doDirs, boolean doFiles, boolean recursive, boolean blankExt, Vector extToUse) { totalDone = 0; this.startPoint = startPoint; this.inputFile = inputFile; this.firstPartOfURL = protocol + "://" + host + ":" + port; this.extention = extention; this.protocol = protocol; this.host = host; this.port = port; workerCount = ThreadNumber; this.doFiles = doFiles; this.doDirs = doDirs; this.recursive = recursive; this.blankExt = blankExt; this.extToUse = extToUse; URL url; try { url = new URL(firstPartOfURL + startPoint); } catch (MalformedURLException ex) { LOG.error("Bad URL", ex); } LOG.info("Starting dir/file list based brute forcing"); setpUpHttpClient(); createTheThreads(); workGen = new WorkerGenerator(this); }</code><technical_language>need synchronized? scan start (the other setupManagers synchronized)</technical_language>

Target:
public void setupManager( String startPoint, String inputFile, String protocol, String host, int port, String extention, int ThreadNumber, boolean doDirs, boolean doFiles, boolean recursive, boolean blankExt, Vector extToUse) { totalDone = 0; this.startPoint = startPoint; this.inputFile = inputFile; this.firstPartOfURL = protocol + "://" + host + ":" + port; this.extention = extention; this.protocol = protocol; this.host = host; this.port = port; workerCount = ThreadNumber; this.doFiles = doFiles; this.doDirs = doDirs; this.recursive = recursive; this.blankExt = blankExt; this.extToUse = extToUse; URL url; try { url = new URL(firstPartOfURL + startPoint); } catch (MalformedURLException ex) { LOG.error("Bad URL", ex); } LOG.info("Starting dir/file list based brute forcing"); setpUpHttpClient(); createTheThreads(); workGen = new WorkerGenerator(this); }
Source:
<code>default void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull EnvVars env, @NonNull Launcher launcher, @NonNull TaskListener listener) throws InterruptedException, IOException { <START> if (!Util.isOverridden(SimpleBuildStep.class, this.getClass(), "perform", Run.class, FilePath.class, Launcher.class, TaskListener.class)) { throw new AbstractMethodError(); } this.perform(run, workspace, launcher, listener); <END> }</code><technical_language>suggestion if (Util.isOverridden(SimpleBuildStep.class, this.getClass(), "perform", Run.class, FilePath.class, Launcher.class, TaskListener.class)) { this.perform(run, workspace, launcher, listener); } else { throw new AbstractMethodError(); } easier follow</technical_language>

Target:
default void perform(@NonNull Run<?, ?> run, @NonNull FilePath workspace, @NonNull EnvVars env, @NonNull Launcher launcher, @NonNull TaskListener listener) throws InterruptedException, IOException { if (Util.isOverridden(SimpleBuildStep.class, this.getClass(), "perform", Run.class, FilePath.class, Launcher.class, TaskListener.class)) { this.perform(run, workspace, launcher, listener); } else { throw new AbstractMethodError(); } }
Source:
<code>public RabbitMQTaskQueue(Connection conn, String exchange, String queueName) { try { this.exchangeName = exchange; mqChannel = conn.createChannel(); mqChannel.queueBind(queueName, exchange, queueName); <START> queueUrl = "RabbitMQ-" + conn.getAddress(); <END> this.queueName = queueName; } catch (Exception ex) { log.error("Failed to estabilish connection to RabbitMQ with queue name and URL because {}", queueName, queueUrl, ex.getMessage()); throw new DuraCloudRuntimeException(ex); } }</code><technical_language>queue URL a "RabbitMQ-" prefix? a need change this</technical_language>

Target:
public RabbitMQTaskQueue(Connection conn, String exchange, String queueName) { try { this.exchangeName = exchange; mqChannel = conn.createChannel(); mqChannel.queueBind(queueName, exchange, queueName); queueUrl = "(RabbitMQ) " + conn.getAddress(); this.queueName = queueName; } catch (Exception ex) { log.error("Failed to estabilish connection to RabbitMQ with queue name and URL because {}", queueName, queueUrl, ex.getMessage()); throw new DuraCloudRuntimeException(ex); } }
Source:
<code>public ServiceBundle getServiceBundleByName(String serviceName) { Collection<ServiceBundle> serviceBundles = listServiceBundles(Lists.newArrayList(new QueryParam("name", serviceName))); if (serviceBundles.size() > 1) { <START> LOG.warn("Multiple service bundles have same name: returning first match.", serviceName); <END> return serviceBundles.iterator().next(); } else if (serviceBundles.size() == 1) { return serviceBundles.iterator().next(); } return null; }</code><technical_language>name</technical_language>

Target:
public ServiceBundle getServiceBundleByName(String serviceName) { Collection<ServiceBundle> serviceBundles = listServiceBundles(Lists.newArrayList(new QueryParam("name", serviceName))); if (serviceBundles.size() > 1) { LOG.warn("Multiple service bundles with the same name: returning first match.", serviceName); return serviceBundles.iterator().next(); } else if (serviceBundles.size() == 1) { return serviceBundles.iterator().next(); } return null; }
Source:
<code>public void addData(String guid, String classification, PageOrientation orientation) { DataRightEntry toAdd = new DataRightEntry(); toAdd.setClassification(classification); toAdd.setGuid(guid); toAdd.setOrientation(orientation); getData(); <START> data.add(toAdd); <END> }</code><technical_language>line this --- getData().add(toAdd);</technical_language>

Target:
public void addData(String guid, String classification, PageOrientation orientation) { DataRightEntry toAdd = new DataRightEntry(); toAdd.setClassification(classification); toAdd.setGuid(guid); toAdd.setOrientation(orientation); getData().add(toAdd); }
Source:
<code>public Object visit(ASTMethodDeclaration node, Object data) { <START> ASTCompilationUnit acu = node.getFirstParentOfType(ASTCompilationUnit.class); if (isJUnit5Class(acu) || isJUnit4Class(acu)) { <END> return super.visit(node, data); } if (node.getArity() != 0) { return super.visit(node, data); } String name = node.getName(); if (!"setUp".equals(name) && "setup".equalsIgnoreCase(name)) { addViolation(data, node); } if (!"tearDown".equals(name) && "teardown".equalsIgnoreCase(name)) { addViolation(data, node); } return super.visit(node, data); }</code><technical_language>If protected fields base class, need search for compilation unit call methods - done...</technical_language>

Target:
public Object visit(ASTMethodDeclaration node, Object data) { if (isJUnit5Class || isJUnit4Class) { return super.visit(node, data); } if (node.getArity() != 0) { return super.visit(node, data); } String name = node.getName(); if (!"setUp".equals(name) && "setup".equalsIgnoreCase(name)) { addViolation(data, node); } if (!"tearDown".equals(name) && "teardown".equalsIgnoreCase(name)) { addViolation(data, node); } return super.visit(node, data); }
Source:
<code>public Result apply(TableScanNode tableScanNode, Captures captures, Context context) { if (tableScanNode.getLayout().isPresent()) { return Result.empty(); } Optional<TableLayoutResult> layout = metadata.getLayout( context.getSession(), tableScanNode.getTable(), Constraint.alwaysTrue(), Optional.of(tableScanNode.getOutputSymbols().stream() .map(tableScanNode.getAssignments()::get) .collect(toImmutableSet()))); if (!layout.isPresent() || layout.get().getLayout().getPredicate().isNone()) { return Result.ofPlanNode(new ValuesNode(context.getIdAllocator().getNextId(), tableScanNode.getOutputSymbols(), ImmutableList.of())); <START> } <END> return Result.ofPlanNode(new TableScanNode( tableScanNode.getId(), tableScanNode.getTable(), tableScanNode.getOutputSymbols(), tableScanNode.getAssignments(), Optional.of(layout.get().getLayout().getHandle()), layout.get().getLayout().getPredicate(), TupleDomain.all())); }</code><technical_language>this contains dup code pushPredicateIntoTableScan. Personally I prefer pushing logic avoid accidentally inconsistency</technical_language>

Target:
public Result apply(TableScanNode tableScanNode, Captures captures, Context context) { if (tableScanNode.getTable().getLayout().isPresent()) { return Result.empty(); } TableLayoutResult layout = metadata.getLayout( context.getSession(), tableScanNode.getTable(), Constraint.alwaysTrue(), Optional.of(tableScanNode.getOutputSymbols().stream() .map(tableScanNode.getAssignments()::get) .collect(toImmutableSet()))); if (layout.getLayout().getPredicate().isNone()) { return Result.ofPlanNode(new ValuesNode(context.getIdAllocator().getNextId(), tableScanNode.getOutputSymbols(), ImmutableList.of())); } return Result.ofPlanNode(new TableScanNode( tableScanNode.getId(), layout.getLayout().getNewTableHandle(), tableScanNode.getOutputSymbols(), tableScanNode.getAssignments(), layout.getLayout().getPredicate(), TupleDomain.all())); }
Source:
<code>private Map<String,String> getMappingTable() { Map<String,String> mappings = new HashMap<>(); if (hasMappingTable()) { ResultSet resultSet = session.execute("SELECT project_id,project_name FROM openshift_metrics.metrics_mappings;"); <START> for (Row row: resultSet.all()) { <END> mappings.put(row.getString("project_id"), row.getString("project_name")); } } return mappings; }</code><technical_language>Is a risk this query requires PAGING instead of loading table memory</technical_language>

Target:
private Map<String,String> getMappingTable() { PreparedStatement findMappings = session.prepare( "SELECT project_id, project_name " + "FROM openshift_metrics.metrics_mappings " + "WHERE token(project_id) > ? AND token(project_id) <= ?"); Map<String,String> mappings = new HashMap<>(); if (hasMappingTable()) { for (TokenRange tokenRange : getTokenRanges()) { BoundStatement boundStatement = findMappings.bind().setToken(0, tokenRange.getStart()) .setToken(1, tokenRange.getEnd()); ResultSet resultSet = session.execute(boundStatement); resultSet.forEach(row -> mappings.put(row.getString(0), row.getString(1))); } } mappings.remove("%succeeded"); return mappings; }
Source:
<code><START> public void validate(KerberosCredentials credentials, WebContext context) throws CredentialsException { <END> logger.trace("Try to validate Kerberos Token:" + credentials.getKerberosTicketAsString()); KerberosTicketValidation ticketValidation = this.ticketValidator.validateTicket(credentials.getKerberosTicket()); logger.debug("Kerberos Token validated"); String subject = ticketValidation.username(); logger.debug("Succesfully validated " + subject); KerberosProfile profile = new KerberosProfile(); profile.setId(subject); profile.gssContext = ticketValidation.getGssContext(); credentials.setUserProfile(profile); if (!subject.contains(UserProfile.SEPARATOR)) { subject = KerberosProfile.class.getSimpleName() + UserProfile.SEPARATOR + subject; } logger.debug("Succesfully validated, updated subject: " + subject); }</code><technical_language>call init() method is missing here</technical_language>

Target:
public void validate(KerberosCredentials credentials, WebContext context) throws CredentialsException { init(context); logger.trace("Try to validate Kerberos Token:" + credentials.getKerberosTicketAsString()); KerberosTicketValidation ticketValidation = this.ticketValidator.validateTicket(credentials.getKerberosTicket()); logger.debug("Kerberos Token validated"); String subject = ticketValidation.username(); logger.debug("Succesfully validated " + subject); KerberosProfile profile = new KerberosProfile(); profile.setId(subject); profile.gssContext = ticketValidation.getGssContext(); credentials.setUserProfile(profile); }
Source:
<code>protected List<OvfEntityData> getEntitiesFromStorageOvfDisk() { List<OvfEntityData> ovfEntitiesFromTar = Collections.emptyList(); List<Disk> unregisteredDisks = getBackend().runInternalQuery(VdcQueryType.GetUnregisteredDisks, new GetUnregisteredDisksQueryParameters(getParameters().getStorageDomainId(), getVds().getStoragePoolId())).getReturnValue(); if (!unregisteredDisks.isEmpty()) { Pair<DiskImage, Long> ovfDiskAndSize = getLatestOVFDisk(unregisteredDisks); DiskImage ovfDisk = ovfDiskAndSize.getFirst(); if (ovfDisk != null) { try { VDSReturnValue retrievedByteData = runVdsCommand(VDSCommandType.RetrieveImageData, new ImageHttpAccessVDSCommandParameters(getVdsId(), getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), ovfDisk.getId(), ovfDisk.getImage().getId(), ovfDiskAndSize.getSecond())); if (retrievedByteData.getSucceeded()) { ovfEntitiesFromTar = OvfUtils.getOvfEntities((byte[]) retrievedByteData.getReturnValue(), getParameters().getStorageDomainId()); } } catch (VdcBLLException e) { <START> log.errorFormat("Image data could not be retrieved for disk id {0} in storage domain id {1}", <END> ovfDisk.getId(), getParameters().getStorageDomainId()); } } } return ovfEntitiesFromTar; }</code><technical_language>1. /s/Image/Ovf store 2. this audit log, user able import vms/templates. 3. This audit log displayed ovf disk do - boolean succeeded = false... - try get disk/data...if succesfull succeeded = true - if (!succeeded) ... audit log</technical_language>

Target:
protected List<OvfEntityData> getEntitiesFromStorageOvfDisk() { List<OvfEntityData> ovfEntitiesFromTar = Collections.emptyList(); boolean isUnregisteredDisksRetrieved = false; List<Disk> unregisteredDisks = getBackend().runInternalQuery(VdcQueryType.GetUnregisteredDisks, new GetUnregisteredDisksQueryParameters(getParameters().getStorageDomainId(), getVds().getStoragePoolId())).getReturnValue(); if (!unregisteredDisks.isEmpty()) { Pair<DiskImage, Long> ovfDiskAndSize = getLatestOVFDisk(unregisteredDisks); DiskImage ovfDisk = ovfDiskAndSize.getFirst(); if (ovfDisk != null) { try { VDSReturnValue retrievedByteData = runVdsCommand(VDSCommandType.RetrieveImageData, new ImageHttpAccessVDSCommandParameters(getVdsId(), getParameters().getStoragePoolId(), getParameters().getStorageDomainId(), ovfDisk.getId(), ovfDisk.getImage().getId(), ovfDiskAndSize.getSecond())); if (retrievedByteData.getSucceeded()) { ovfEntitiesFromTar = OvfUtils.getOvfEntities((byte[]) retrievedByteData.getReturnValue(), getParameters().getStorageDomainId()); isUnregisteredDisksRetrieved = true; } } catch (VdcBLLException e) { log.errorFormat("Image data could not be retrieved for disk id {0} in storage domain id {1}", ovfDisk.getId(), getParameters().getStorageDomainId()); } } } if (!isUnregisteredDisksRetrieved) { AuditLogDirector.log(this, AuditLogType.RETRIEVE_OVF_STORE_FAILED); } return ovfEntitiesFromTar; }
Source:
<code>private void waitForInitialNodes() { int initialClusterSize = configuration.transport().initialClusterSize(); if (initialClusterSize > 1) { <START> while (channel.getView().getMembers().size() < initialClusterSize) { <END> try { log.debugf("Waiting for %d nodes, current view has %d", initialClusterSize, channel.getView().getMembers().size()); waitForView(viewId + 1); } catch (InterruptedException e) { log.interruptedWaitingForCoordinator(e); Thread.currentThread().interrupt(); } } log.debugf("Initial cluster size of %d nodes reached", initialClusterSize); } }</code><technical_language>a timeout here</technical_language>

Target:
private void waitForInitialNodes() { int initialClusterSize = configuration.transport().initialClusterSize(); if (initialClusterSize > 1) { long timeout = configuration.transport().initialClusterTimeout(); while (channel.getView().getMembers().size() < initialClusterSize) { try { log.debugf("Waiting for %d nodes, current view has %d", initialClusterSize, channel.getView().getMembers().size()); if(!waitForView(viewId + 1, timeout, TimeUnit.MILLISECONDS)) { throw log.timeoutWaitingForInitialNodes(initialClusterSize, channel.getView().getMembers()); } } catch (InterruptedException e) { log.interruptedWaitingForCoordinator(e); Thread.currentThread().interrupt(); } } log.debugf("Initial cluster size of %d nodes reached", initialClusterSize); } }
Source:
<code>public void remoteAdd(RemoteAddRequest request) throws GitException { String remoteName = request.getName(); if (remoteName == null || remoteName.isEmpty()) { throw new IllegalArgumentException(ERROR_ADD_REMOTE_NAME_MISSING); } StoredConfig config = repository.getConfig(); Set<String> remoteNames = config.getSubsections("remote"); if (remoteNames.contains(remoteName)) { throw new IllegalArgumentException(String.format(ERROR_REMOTE_NAME_ALREADY_EXISTS, remoteName)); } String url = request.getUrl(); <START> if (url == null || url.isEmpty()) { <END> throw new IllegalArgumentException(ERROR_REMOTE_URL_MISSING); } RemoteConfig remoteConfig; try { remoteConfig = new RemoteConfig(config, remoteName); } catch (URISyntaxException exception) { throw new GitException(exception.getMessage(), exception); } try { remoteConfig.addURI(new URIish(url)); } catch (URISyntaxException exception) { throw new IllegalArgumentException("Remote url " + url + " is invalid. "); } List<String> branches = request.getBranches(); if (branches.isEmpty()) { remoteConfig.addFetchRefSpec( new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*").setForceUpdate(true)); } else { for (String branch : branches) { remoteConfig.addFetchRefSpec(new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch) .setForceUpdate(true)); } } remoteConfig.update(config); try { config.save(); } catch (IOException exception) { throw new GitException(exception.getMessage(), exception); } }</code><technical_language><LINK_0></technical_language>

Target:
public void remoteAdd(RemoteAddRequest request) throws GitException { String remoteName = request.getName(); if (isNullOrEmpty(remoteName)) { throw new IllegalArgumentException(ERROR_ADD_REMOTE_NAME_MISSING); } StoredConfig config = repository.getConfig(); Set<String> remoteNames = config.getSubsections("remote"); if (remoteNames.contains(remoteName)) { throw new IllegalArgumentException(String.format(ERROR_REMOTE_NAME_ALREADY_EXISTS, remoteName)); } String url = request.getUrl(); if (isNullOrEmpty(url)) { throw new IllegalArgumentException(ERROR_REMOTE_URL_MISSING); } RemoteConfig remoteConfig; try { remoteConfig = new RemoteConfig(config, remoteName); } catch (URISyntaxException exception) { throw new GitException(exception.getMessage(), exception); } try { remoteConfig.addURI(new URIish(url)); } catch (URISyntaxException exception) { throw new IllegalArgumentException("Remote url " + url + " is invalid. "); } List<String> branches = request.getBranches(); if (branches.isEmpty()) { remoteConfig.addFetchRefSpec( new RefSpec(Constants.R_HEADS + "*" + ":" + Constants.R_REMOTES + remoteName + "/*").setForceUpdate(true)); } else { for (String branch : branches) { remoteConfig.addFetchRefSpec(new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_REMOTES + remoteName + "/" + branch) .setForceUpdate(true)); } } remoteConfig.update(config); try { config.save(); } catch (IOException exception) { throw new GitException(exception.getMessage(), exception); } }
Source:
<code>private void testPreparedQuery(GrillQueryCommands qCom) throws Exception { String sql = "cube select id, name from dim_table"; String result = qCom.getAllPreparedQueries(); Assert.assertEquals("No prepared queries", result); String qh = qCom.prepare(sql); result = qCom.getAllPreparedQueries(); Assert.assertEquals(qh, result); result = qCom.getPreparedStatus(qh); Assert.assertTrue(result.contains("User query:cube select id, name from dim_table")); Assert.assertTrue(result.contains(qh)); result = qCom.executePreparedQuery(qh, false); LOG.debug("Prepared query sync result is " + result); Assert.assertTrue(result.contains("1\tfirst")); String handle = qCom.executePreparedQuery(qh, true); LOG.debug("Perpared query handle is " + handle); String status = qCom.getStatus(handle); <START> while (status.contains("RUNNING") <END> || status.contains("LAUNCHED") || status.contains("QUEUED") || status.contains("NEW")) { Thread.sleep(5000); status = qCom.getStatus(handle); } status = qCom.getStatus(handle); LOG.debug("Prepared Query Status is " + status); Assert.assertTrue(status.contains("Status : SUCCESSFUL")); result = qCom.getQueryResults(handle); LOG.debug("Prepared Query Result is " + result); Assert.assertTrue(result.contains("1\tfirst")); result = qCom.destroyPreparedQuery(qh); LOG.debug("destroy result is " + result); Assert.assertEquals("Successfully destroyed " + qh, result); result = qCom.explainAndPrepare(sql); Assert.assertTrue(result.contains(explainPlan)); }</code><technical_language>want do status.isFinished() instead of status checks. new states added Executed, is checked right</technical_language>

Target:
private void testPreparedQuery(GrillQueryCommands qCom) throws Exception { String sql = "cube select id, name from dim_table"; String result = qCom.getAllPreparedQueries(); Assert.assertEquals("No prepared queries", result); String qh = qCom.prepare(sql); result = qCom.getAllPreparedQueries(); Assert.assertEquals(qh, result); result = qCom.getPreparedStatus(qh); Assert.assertTrue(result.contains("User query:cube select id, name from dim_table")); Assert.assertTrue(result.contains(qh)); result = qCom.executePreparedQuery(qh, false); LOG.warn("XXXXXX Prepared query sync result is " + result); Assert.assertTrue(result.contains("1\tfirst")); String handle = qCom.executePreparedQuery(qh, true); LOG.debug("Perpared query handle is " + handle); while(!client.getQueryStatus(handle).isFinished()) { Thread.sleep(5000); } String status = qCom.getStatus(handle); LOG.debug("Prepared Query Status is " + status); Assert.assertTrue(status.contains("Status : SUCCESSFUL")); result = qCom.getQueryResults(handle); LOG.debug("Prepared Query Result is " + result); Assert.assertTrue(result.contains("1\tfirst")); result = qCom.destroyPreparedQuery(qh); LOG.debug("destroy result is " + result); Assert.assertEquals("Successfully destroyed " + qh, result); result = qCom.explainAndPrepare(sql); Assert.assertTrue(result.contains(explainPlan)); qh = qCom.getAllPreparedQueries(); Assert.assertTrue(result.contains("Prepare handle:"+ qh)); result = qCom.destroyPreparedQuery(qh); Assert.assertEquals("Successfully destroyed " + qh, result); }
Source:
<code>public void displayNewPage(final PageTitle title, final HistoryEntry entry, boolean allowStateLoss) { ACRA.getErrorReporter().putCustomData("api", title.getSite().getApiDomain()); ACRA.getErrorReporter().putCustomData("title", title.toString()); if (drawerLayout.isDrawerOpen(Gravity.START)) { drawerLayout.closeDrawer(Gravity.START); } if (title.isSpecial()) { Utils.visitInExternalBrowser(this, Uri.parse(title.getMobileUri())); return; } resetFragments(allowStateLoss); fragmentContainerView.post(new Runnable() { @Override public void run() { PageViewFragmentInternal frag = getCurPageFragment(); if (frag == null) { return; } if (frag.getTitle() != null && frag.getTitle().equals(title)) { if (!TextUtils.isEmpty(title.getFragment())) { frag.scrollToSection(title.getFragment()); } return; } frag.closeFindInPage(); boolean loadFromCache = entry.getSource() != HistoryEntry.SOURCE_MAIN_PAGE <START> && entry.getSource() != HistoryEntry.SOURCE_LANGUAGE_LINK; <END> frag.displayNewPage(title, entry, loadFromCache, true); app.getSessionFunnel().pageViewed(entry); } }); }</code><technical_language>part is obsolete Dbrant's patch merged earlier today. I image merge conflicts rebase manually</technical_language>

Target:
public void displayNewPage(final PageTitle title, final HistoryEntry entry, boolean allowStateLoss) { ACRA.getErrorReporter().putCustomData("api", title.getSite().getApiDomain()); ACRA.getErrorReporter().putCustomData("title", title.toString()); if (drawerLayout.isDrawerOpen(Gravity.START)) { drawerLayout.closeDrawer(Gravity.START); } if (title.isSpecial()) { Utils.visitInExternalBrowser(this, Uri.parse(title.getMobileUri())); return; } resetFragments(allowStateLoss); fragmentContainerView.post(new Runnable() { @Override public void run() { PageViewFragmentInternal frag = getCurPageFragment(); if (frag == null) { return; } if (frag.getTitle() != null && frag.getTitle().equals(title)) { if (!TextUtils.isEmpty(title.getFragment())) { frag.scrollToSection(title.getFragment()); } return; } frag.closeFindInPage(); frag.displayNewPage(title, entry, false, true); app.getSessionFunnel().pageViewed(entry); } }); }
Source:
<code>public SetConfigurationObjectResponse getSetConfigurationObjectResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final SetConfigurationObjectAsyncRequest request) throws OsgpException { final MeterResponseData meterResponseData = this.configurationService <START> .dequeueSetConfigurationObjectResponse(request.getCorrelationUid()); <END> final SetConfigurationObjectResponse response = new SetConfigurationObjectResponse(); if (meterResponseData != null) { response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); if (meterResponseData.getMessageData() instanceof String) { response.setDescription((String) meterResponseData.getMessageData()); } } else { response.setResult(OsgpResultType.NOT_FOUND); } return response; }</code><technical_language>In SmartMeteringMonitoringEndpoint I response data retrieved a call meterResponseDataService. Calling configurationService obtain response data inconsistent sight. If is reason for this difference, I cleaner if obtaining actual response is treated alike in endpoints</technical_language>

Target:
public SetConfigurationObjectResponse getSetConfigurationObjectResponse( @OrganisationIdentification final String organisationIdentification, @RequestPayload final SetConfigurationObjectAsyncRequest request) { final SetConfigurationObjectResponse response = new SetConfigurationObjectResponse(); try { final MeterResponseData meterResponseData = this.configurationService .dequeueSetConfigurationObjectResponse(request.getCorrelationUid()); response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); if (meterResponseData.getMessageData() instanceof String) { response.setDescription((String) meterResponseData.getMessageData()); } } catch (final FunctionalException e) { if (e.getExceptionType() == FunctionalExceptionType.UNKNOWN_CORRELATION_UID) { response.setResult(OsgpResultType.NOT_FOUND); } else { response.setResult(OsgpResultType.NOT_OK); } } return response; }
Source:
<code>public void testCreate() throws IOException, StripeException { final Account account = Account.retrieve(ACCOUNT_ID, null); LoginLinkCollection stubbedCollection = new LoginLinkCollection(); stubbedCollection.setURL(String.format("/v1/accounts/%s/login_links", account.getId())); account.setLoginLinks(stubbedCollection); stubRequest( APIResource.RequestMethod.POST, String.format("/v1/accounts/%s/login_links", account.getId()), null, LoginLink.class, getResourceAsString("/api_fixtures/login_link.json") ); <START> final LoginLink link = account.getLoginLinks().create(); <END> assertNotNull(link); verifyRequest( APIResource.RequestMethod.POST, String.format("/v1/accounts/%s/login_links", account.getId()) ); }</code><technical_language>I if cleaner account fixture login_links collection instead</technical_language>

Target:
public void testCreate() throws IOException, StripeException { final Account account = Account.retrieve(ACCOUNT_ID, null); final LoginLinkCollection stubbedCollection = new LoginLinkCollection(); stubbedCollection.setURL(String.format("/v1/accounts/%s/login_links", account.getId())); account.setLoginLinks(stubbedCollection); stubRequest( APIResource.RequestMethod.POST, String.format("/v1/accounts/%s/login_links", account.getId()), null, LoginLink.class, getResourceAsString("/api_fixtures/login_link.json") ); final LoginLink link = account.getLoginLinks().create(); assertNotNull(link); verifyRequest( APIResource.RequestMethod.POST, String.format("/v1/accounts/%s/login_links", account.getId()) ); }
Source:
<code>public void onLoaded() { logger.info("Starting Settings Migration Process"); ItemConfigMigrator migrator = new ItemConfigMigrator(); Jenkins j = Jenkins.getInstance(); if (j == null) { <START> throw new IllegalStateException(); <END> } List<Item> items = j.getAllItems(); if (null != items) { for (Item item : items) { if (!migrator.migrate(item)) { logger.info(String.format("Skipping job \"%s\" with type %s", item.getName(), item.getClass().getName())); continue; } } } logger.info("Completed Settings Migration Process"); }</code><technical_language>same, loss of diagnostics FindBugs happy</technical_language>

Target:
public void onLoaded() { logger.info("Starting Settings Migration Process"); ItemConfigMigrator migrator = new ItemConfigMigrator(); Jenkins jenkins = Jenkins.getActiveInstance(); List<Item> items = jenkins.getAllItems(); if (null != items) { for (Item item : items) { if (!migrator.migrate(item)) { logger.info(String.format("Skipping job \"%s\" with type %s", item.getName(), item.getClass().getName())); continue; } } } logger.info("Completed Settings Migration Process"); }
Source:
<code>public void run() { try { try { onClose(); } catch (Exception e) { getLogger().severe(format("Failed to call 'onClose' on channel [%s]", this), e); } try { socketChannel.close(); } catch (IOException e) { getLogger().severe(format("Failed to close [%s]", this), e); } finally { for (ChannelCloseListener closeListener : closeListeners) { try { closeListener.onClose(AbstractChannel.this); } catch (Exception e) { getLogger().severe(format("Failed to process closeListener [%s] on channel [%s]", closeListener, this), e); } } } } finally { <START> System.out.println("Closed channel:" + AbstractChannel.this); <END> } }</code><technical_language>Leftover</technical_language>

Target:
public void run() { try { onClose(); } catch (Exception e) { getLogger().severe(format("Failed to call 'onClose' on channel [%s]", this), e); } try { socketChannel.close(); } catch (IOException e) { getLogger().severe(format("Failed to close [%s]", this), e); } finally { for (ChannelCloseListener closeListener : closeListeners) { try { closeListener.onClose(AbstractChannel.this); } catch (Exception e) { getLogger().severe(format("Failed to process closeListener [%s] on channel [%s]", closeListener, this), e); } } } }
Source:
<code>public void testCreateFileUpload() throws StripeException, InterruptedException, URISyntaxException { File file = new File(getClass().getResource("minimal.pdf").toURI()); Map<String, Object> fileUploadParams = new HashMap<String, Object>(); fileUploadParams.put("purpose", "dispute_evidence"); <START> fileUploadParams.put("file", file); <END> FileUpload fileUpload = FileUpload.create(fileUploadParams); assertEquals(768, fileUpload.getSize().intValue()); assertEquals("application/pdf", fileUpload.getMimeType()); FileUpload retrievedUpload = FileUpload.retrieve(fileUpload.getId()); assertEquals(fileUpload.getId(), retrievedUpload.getId()); assertEquals(768, retrievedUpload.getSize().intValue()); assertEquals("application/pdf", retrievedUpload.getMimeType()); }</code><technical_language>a HashMap is fine, a bit wordy. In future, feel free ImmutableMap: Map<String, Object> fileUploadParams = ImmutableMap.of("purpose", "dispute_evidence", "file", file); NRE though, tests decent</technical_language>

Target:
public void testCreateFileUpload() throws StripeException, InterruptedException, URISyntaxException { URL url = getClass().getResource("minimal.pdf"); File file = new File(url.getPath()); Map<String, Object> fileUploadParams = new HashMap<String, Object>(); fileUploadParams.put("purpose", "dispute_evidence"); fileUploadParams.put("file", file); FileUpload fileUpload = FileUpload.create(fileUploadParams); assertEquals(file.length(), fileUpload.getSize().longValue()); assertEquals("application/pdf", fileUpload.getMimeType()); FileUpload retrievedUpload = FileUpload.retrieve(fileUpload.getId()); assertEquals(fileUpload.getId(), retrievedUpload.getId()); assertEquals(file.length(), retrievedUpload.getSize().longValue()); assertEquals("application/pdf", retrievedUpload.getMimeType()); }
Source:
<code>protected void updateData(final long start, final long end, int nb, @Nullable IProgressMonitor monitor) { Collection<ISegment> data = fDisplayData; final int dataSize = (nb == 0) ? data.size() : nb; if (dataSize == 0 || end == start) { return; } <START> List<Double> xSeries = new ArrayList<>(); <END> List<Double> ySeries = new ArrayList<>(); Iterator<ISegment> modelIter = data.iterator(); for (int i = 0; i < dataSize; i++) { ISegment segment = Iterators.<@Nullable ISegment> getNext(modelIter, null); if (segment != null) { xSeries.add((double) (segment.getStart() - start)); ySeries.add((double) segment.getLength()); } } setXAxis(Doubles.toArray(xSeries)); setSeries(Messages.SegmentStoreScatterGraphViewer_legend, Doubles.toArray(ySeries)); updateDisplay(); }</code><technical_language>seed array dataSize</technical_language>

Target:
protected void updateData(final long start, final long end, int nb, @Nullable IProgressMonitor monitor) { Collection<ISegment> data = fDisplayData; final int dataSize = (nb == 0) ? data.size() : nb; if (dataSize == 0 || end == start) { return; } List<Double> xSeries = new ArrayList<>(dataSize); List<Double> ySeries = new ArrayList<>(dataSize); Iterator<ISegment> modelIter = data.iterator(); while(modelIter.hasNext()) { ISegment segment = modelIter.next(); if (segment != null) { xSeries.add((double) (segment.getStart() - start)); ySeries.add((double) segment.getLength()); } } setXAxis(Doubles.toArray(xSeries)); setSeries(Messages.SegmentStoreScatterGraphViewer_legend, Doubles.toArray(ySeries)); updateDisplay(); }
Source:
<code>public RocksDBOptionsFactory configure(ReadableConfig configuration) { this.backgroundJobs = configuration.get( <START> ConfigOptions.key(BACKGROUND_JOBS_OPTION) <END> .intType() .defaultValue(DEFAULT_BACKGROUND_JOBS)); return this; }</code><technical_language>Nit: turn field a ConfigOption</technical_language>

Target:
public RocksDBOptionsFactory configure(ReadableConfig configuration) { this.backgroundJobs = configuration.get(BACKGROUND_JOBS_OPTION); return this; }
Source:
<code>public static Dictionary<String, Object> configureValidationMarkerPlugin( List<String> enforcedValidators, boolean enforceErrors, boolean enforceWarnings, AdminConfig configAdmin) throws IOException { Dictionary<String, Object> properties = new DictionaryMap<>(); properties.put("enforcedMetacardValidators", enforcedValidators); <START> properties.put("enforceErrors", String.valueOf(enforceErrors)); <END> properties.put("enforceWarnings", String.valueOf(enforceWarnings)); return configureValidationMarkerPlugin(properties, configAdmin); }</code><technical_language>DictionaryMap.of(k1, v1, k2, v2, k3, v3)</technical_language>

Target:
public static Dictionary<String, Object> configureValidationMarkerPlugin( List<String> enforcedValidators, boolean enforceErrors, boolean enforceWarnings, AdminConfig configAdmin) throws IOException { Dictionary<String, Object> properties = new DictionaryMap<>(); properties.put("enforcedMetacardValidators", enforcedValidators); properties.put("enforceErrors", enforceErrors); properties.put("enforceWarnings", enforceWarnings); return configureValidationMarkerPlugin(properties, configAdmin); }
Source:
<code>private String getStringValue(Map<String, Object> dataMap, String key) { <START> return dataMap.containsKey(key) ? (String) dataMap.get(key) : null; <END> }</code><technical_language>get instead of map accesses, work? below. java return (String) dataMap.get(key);</technical_language>

Target:
private String getStringValue(Map<String, Object> dataMap, String key) { return (String) dataMap.get(key); }
Source:
<code><START> public EventStack(final long firstEventTime) { <END> this.eventStack = new Stack<>(); this.firstEventTime = firstEventTime; this.emitable = true; this.includeLast = true; }</code><technical_language>this class Injectable</technical_language>

Target:
public EventStack(final long firstEventTime) { this.eventStack = new Stack<>(); this.firstEventTime = firstEventTime; this.isEmitted = true; this.includeLast = true; }
Source:
<code><START> public static HashMap<String, String> createEnvironment(IServer server, String password) { <END> Map<String, String> launchEnv = null; try { ILaunchConfiguration wc = server.getLaunchConfiguration(false, new NullProgressMonitor()); launchEnv = wc.getAttribute(IExternalLaunchConstants.ENVIRONMENT_VARS_KEY, (Map)null); } catch(CoreException ce) { CDKCoreActivator.pluginLog().logWarning("Unable to load environment for vagrant status call. System environment will be used instead."); } HashMap<String,String> systemEnv = new HashMap<String,String>(System.getenv()); if( launchEnv != null ) { Iterator<String> it = launchEnv.keySet().iterator(); String k = null; while(it.hasNext()) { k = it.next(); systemEnv.put(k, launchEnv.get(k)); } } CDKServer cdkServer = (CDKServer)server.loadAdapter(CDKServer.class, new NullProgressMonitor()); boolean passCredentials = cdkServer.getServer().getAttribute(CDKServer.PROP_PASS_CREDENTIALS, false); if( passCredentials ) { String userKey = cdkServer.getServer().getAttribute(CDKServer.PROP_USER_ENV_VAR, CDKConstants.CDK_ENV_SUB_USERNAME); String passKey = cdkServer.getServer().getAttribute(CDKServer.PROP_PASS_ENV_VAR, CDKConstants.CDK_ENV_SUB_PASSWORD); systemEnv.put(userKey, cdkServer.getUsername()); systemEnv.put(passKey, password); } return systemEnv; }</code><technical_language>return Map interface</technical_language>

Target:
public static Map<String, String> createEnvironment(IServer server, String password) { Map<String, String> launchEnv = null; try { ILaunchConfiguration wc = server.getLaunchConfiguration(false, new NullProgressMonitor()); launchEnv = wc.getAttribute(IExternalLaunchConstants.ENVIRONMENT_VARS_KEY, (Map<String,String>) null); } catch (CoreException ce) { CDKCoreActivator.pluginLog().logWarning( "Unable to load environment for vagrant status call. System environment will be used instead."); } HashMap<String, String> systemEnv = new HashMap<String, String>(System.getenv()); if (launchEnv != null) { Iterator<String> it = launchEnv.keySet().iterator(); String k = null; while (it.hasNext()) { k = it.next(); systemEnv.put(k, launchEnv.get(k)); } } CDKServer cdkServer = (CDKServer) server.loadAdapter(CDKServer.class, new NullProgressMonitor()); boolean passCredentials = cdkServer.getServer().getAttribute(CDKServer.PROP_PASS_CREDENTIALS, false); if (passCredentials) { String userKey = cdkServer.getServer().getAttribute(CDKServer.PROP_USER_ENV_VAR, CDKConstants.CDK_ENV_SUB_USERNAME); String passKey = cdkServer.getServer().getAttribute(CDKServer.PROP_PASS_ENV_VAR, CDKConstants.CDK_ENV_SUB_PASSWORD); systemEnv.put(userKey, cdkServer.getUsername()); systemEnv.put(passKey, password); } return systemEnv; }
Source:
<code><START> private void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { <END> for (final EC2AbstractSlave slave : slaves) { if (slave == null) { LOGGER.warning("Can't raise node for " + t); continue; } Computer c = slave.toComputer(); if (slave.getStopOnTerminate() && c != null) { c.connect(false); } jenkins.addNode(slave); } }</code><technical_language>suggestion private static void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException {</technical_language>

Target:
private static void attachSlavesToJenkins(Jenkins jenkins, List<EC2AbstractSlave> slaves, SlaveTemplate t) throws IOException { for (final EC2AbstractSlave slave : slaves) { if (slave == null) { LOGGER.warning("Can't raise node for " + t); continue; } Computer c = slave.toComputer(); if (slave.getStopOnTerminate() && c != null) { c.connect(false); } jenkins.addNode(slave); } }
Source:
<code>private CalculationParameters(Map<Class<? extends CalculationParameter>, CalculationParameter> parameters) { JodaBeanUtils.notNull(parameters, "parameters"); this.parameters = ImmutableMap.copyOf(parameters); ImmutableMap.Builder<Class<? extends CalculationParameter>, Class<? extends CalculationParameter>> aliases = ImmutableMap.builder(); for (Class<? extends CalculationParameter> type : parameters.keySet()) { Class<?>[] interfaces = type.getInterfaces(); for (Class<?> iface : interfaces) { if (iface != CalculationParameter.class && CalculationParameter.class.isAssignableFrom(iface) && !parameters.containsKey(iface)) { <START> aliases.put(iface.asSubclass(CalculationParameter.class), type); <END> } } } this.aliases = aliases.build(); }</code><technical_language>This fail if values in parameters of classes implement interface is a subtype of CalculationParameter. ambiguous fail, nice provide some explanation</technical_language>

Target:
private CalculationParameters(Map<Class<? extends CalculationParameter>, CalculationParameter> parameters) { JodaBeanUtils.notNull(parameters, "parameters"); this.parameters = ImmutableMap.copyOf(parameters); Map<Class<? extends CalculationParameter>, Class<? extends CalculationParameter>> aliases = new HashMap<>(); for (Class<? extends CalculationParameter> type : parameters.keySet()) { Class<?>[] interfaces = type.getInterfaces(); for (Class<?> iface : interfaces) { if (iface != CalculationParameter.class && CalculationParameter.class.isAssignableFrom(iface) && !parameters.containsKey(iface)) { Class<? extends CalculationParameter> aliasType = iface.asSubclass(CalculationParameter.class); aliases.putIfAbsent(aliasType, type); } } } this.aliases = ImmutableMap.copyOf(aliases); }
Source:
<code>public void testEmpty() { Observable<String> source = Observable.empty(); final AtomicBoolean wasCalled = new AtomicBoolean(false); source.doOnEmpty(new Action0() { @Override public void call() { wasCalled.set(true); } }).subscribe(); assert(wasCalled.get()); <START> } <END></code><technical_language>a unit test for unsubscription good</technical_language>

Target:
public void testEmpty() { Observable<String> source = Observable.empty(); final AtomicBoolean wasCalled = new AtomicBoolean(false); source.doOnEmpty(new Action0() { @Override public void call() { wasCalled.set(true); } }).subscribe(); assertTrue(wasCalled.get()); }