auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void getApplicationByCandidateIdShouldReturnThreeElementListOfApplicationDTOWhenCandidateIdExists() { List<ApplicationEntity> applicationEntities = Arrays.asList(applicationEntity, applicationEntity, applicationEntity); List<CandidateApplicationDTO> candidateApplicationDTOs = Arrays.asList(dummyCandidateApplicationDTO, dummyCandidateApplicationDTO, dummyCandidateApplicationDTO); given(candidateRepository.findOne(CANDIDATE_ID)).willReturn(candidateEntity); given(applicationsRepository.findByCandidateEntity(candidateEntity, DEFAULT_PAGE_REQUEST)) .willReturn(new PageImpl<ApplicationEntity>(applicationEntities)); given(converterService.convert(applicationEntities, CandidateApplicationDTO.class)) .willReturn(candidateApplicationDTOs); PagingResponse<CandidateApplicationDTO> result = applicationsService .getApplicationsByCandidateId(CANDIDATE_ID, PAGE_NUMBER_ZERO, PAGE_SIZE_TEN); assertThat(result.getTotal(), is(3L)); assertThat(result.getRows(), equalTo(candidateApplicationDTOs)); }

Target:
public void getApplicationByCandidateIdShouldReturnThreeElementListOfApplicationDTOWhenCandidateIdExists() { final List<ApplicationEntity> applicationEntities = Arrays.asList(applicationEntity, applicationEntity, applicationEntity); final List<CandidateApplicationDTO> candidateApplicationDTOs = Arrays.asList(dummyCandidateApplicationDTO, dummyCandidateApplicationDTO, dummyCandidateApplicationDTO); given(candidateRepository.findOne(CANDIDATE_ID)).willReturn(candidateEntity); given(applicationsRepository.findByCandidateEntity(candidateEntity, DEFAULT_PAGE_REQUEST)) .willReturn(new PageImpl<ApplicationEntity>(applicationEntities)); given(converterService.convert(applicationEntities, CandidateApplicationDTO.class)) .willReturn(candidateApplicationDTOs); final PagingResponse<CandidateApplicationDTO> result = applicationsService .getApplicationsByCandidateId(CANDIDATE_ID, PAGE_NUMBER_ZERO, PAGE_SIZE_TEN); assertThat(result.getTotal(), is(3L)); assertThat(result.getRows(), equalTo(candidateApplicationDTOs)); }
Source:
public ByteBuf resumeToken() { return isResumeEnabled() ? SetupFrameFlyweight.resumeToken(setupFrame) : Unpooled.EMPTY_BUFFER; }

Target:
public ByteBuf resumeToken() { return SetupFrameFlyweight.resumeToken(setupFrame); }
Source:
public void setInternalJobState(int state) { try { final Field field = InternalJob.class.getDeclaredField("flags"); field.setAccessible(true); field.set(this, new Integer(state)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }

Target:
public void setInternalJobState(int state) { try { final Field field = InternalJob.class.getDeclaredField("flags"); field.setAccessible(true); field.set(this, new Integer(state)); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private CompletableFuture<JobResult> submitJobAndWaitUntilRunning(JobGraph jobGraph) throws Exception { miniCluster.submitJob(jobGraph).get(); CommonTestUtils.waitUntilJobManagerIsInitialized(() -> miniCluster.getJobStatus(jobGraph.getJobID()).get()); final CompletableFuture<JobResult> jobResultFuture = miniCluster.requestJobResult(jobGraph.getJobID()); assertThat(jobResultFuture.isDone(), is(false)); CommonTestUtils.waitUntilCondition( jobIsRunning(() -> miniCluster.getExecutionGraph(jobGraph.getJobID())), Deadline.fromNow(TESTING_TIMEOUT), 50L); return jobResultFuture; }

Target:
private CompletableFuture<JobResult> submitJobAndWaitUntilRunning(JobGraph jobGraph) throws Exception { miniCluster.submitJob(jobGraph).get(); final CompletableFuture<JobResult> jobResultFuture = miniCluster.requestJobResult(jobGraph.getJobID()); assertThat(jobResultFuture.isDone(), is(false)); CommonTestUtils.waitUntilCondition( jobIsRunning(() -> miniCluster.getExecutionGraph(jobGraph.getJobID())), Deadline.fromNow(TESTING_TIMEOUT), 50L); return jobResultFuture; }
Source:
public void run() { log.info("Starting writer"); try { writerRegistry.register(this); running = true; while (!isCanceled()) { if (Thread.interrupted()) { throw new InterruptedException(); } Collection<Metric> metrics = metricsQueue.poll(batchSize); if (metrics.isEmpty() && lastWorkTime > 0 && maxIdleTime > 0 && System.currentTimeMillis() > lastWorkTime + maxIdleTime) { log.info("Shutting down writer due to dearth of work"); break; } if (metrics.isEmpty()) { log.debug("No work to do, so checking again."); continue; } OpenTsdbClient client = null; try { long processed = 0; client = clientPool.borrowObject(); int errs = clientPool.clearErrorCount(); if (errs > 0) { metricsQueue.incrementError(errs); } for (Metric m : metrics) { String message = convert(m); client.put(message); processed++; } metricsQueue.incrementProcessed(processed); client.flush(); } catch (Exception e) { log.warn("Caught unexpected exception processing messages", e); metricsQueue.addAll(metrics, true); if (client != null) { client.close(); } } finally { if (client != null) { try { clientPool.returnObject(client); } catch(Exception returnException) { log.warn("Failed to return TSDB client to connection pool", returnException); } } client = null; lastWorkTime = System.currentTimeMillis(); } } } catch(InterruptedException ie) { log.info("Exiting due to thread interrupt"); Thread.currentThread().interrupt(); } finally { running = false; writerRegistry.unregister(this); } }

Target:
public void run() { log.info("Starting writer"); try { writerRegistry.register(this); running = true; runUntilCanceled(); } catch(InterruptedException ie) { log.info("Exiting due to thread interrupt"); Thread.currentThread().interrupt(); } finally { running = false; writerRegistry.unregister(this); } }
Source:
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); }

Target:
public ChannelViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ChannelViewHolder((ChannelView) inflater.inflate(R.layout.channel_item_layout, parent, false)); }
Source:
public final static AttachmentSizeFormatter getInstance() { try { return new AttachmentSizeFormatter(); } catch (ClassCastException e) { return new AttachmentSizeFormatter(Locale.ENGLISH); } }

Target:
public final static AttachmentSizeFormatter getInstance() { return new AttachmentSizeFormatter(); }
Source:
private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { running = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self reponse: {}.", toString(), packet); data = atResponse.getCommandValue(); break; case REMOTE_AT_COMMAND_RESPONSE: RemoteATCommandResponsePacket remoteAtResponse = (RemoteATCommandResponsePacket)packet; if (remoteAtResponse.getFrameID() != frameID) return null; if (!remoteAtResponse.getCommand().equals(ND_COMMAND)) return null; if (remoteAtResponse.getCommandValue() == null || remoteAtResponse.getCommandValue().length == 0) { running = remoteAtResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received remote reponse: {}.", toString(), packet); data = remoteAtResponse.getCommandValue(); break; default: break; } return data; }

Target:
private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { running = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self reponse: {}.", toString(), packet); data = atResponse.getCommandValue(); break; default: break; } return data; }
Source:
private void persistGrillServiceState() throws IOException { if (isRestartEnabled()) { FileSystem fs = persistDir.getFileSystem(conf); LOG.info("Persisting server state in " + persistDir); for (GrillService service : grillServices) { LOG.info("Persisting state of service:" + service.getName()); Path serviceWritePath = new Path(persistDir, service.getName() + ".out"); ObjectOutputStream out = null; try { out = new ObjectOutputStream(fs.create(serviceWritePath)); service.writeExternal(out); } finally { if (out != null) { out.close(); } } Path servicePath = getServicePersistPath(service); fs.rename(serviceWritePath, servicePath); LOG.info("Persisted service " + service.getName() + " to " + servicePath); } } else { LOG.info("Server restart is not enabled. Not persisting the server state"); } }

Target:
private void persistGrillServiceState() throws IOException { if (conf.getBoolean(GrillConfConstants.GRILL_SERVER_RESTART_ENABLED, GrillConfConstants.DEFAULT_GRILL_SERVER_RESTART_ENABLED)) { FileSystem fs = persistDir.getFileSystem(conf); LOG.info("Persisting server state in " + persistDir); for (GrillService service : grillServices) { LOG.info("Persisting state of service:" + service.getName()); Path serviceWritePath = new Path(persistDir, service.getName() + ".out"); ObjectOutputStream out = null; try { out = new ObjectOutputStream(fs.create(serviceWritePath)); service.writeExternal(out); } finally { if (out != null) { out.close(); } } Path servicePath = getServicePersistPath(service); fs.rename(serviceWritePath, servicePath); LOG.info("Persisted service " + service.getName() + " to " + servicePath); } } else { LOG.info("Server restart is not enabled. Not persisting the server state"); } }
Source:
void defaultChromeOptions() { Capabilities chromeOptions = factory.createCapabilities(config, browser, proxy, browserDownloadsFolder); Map<String, Object> prefsMap = getBrowserLaunchPrefs(ChromeOptions.CAPABILITY, chromeOptions); assertThat(prefsMap).hasSizeGreaterThan(0); assertThat(prefsMap).containsEntry("download.default_directory", new File(DOWNLOADS_FOLDER).getAbsolutePath()); }

Target:
void defaultChromeOptions() { Capabilities chromeOptions = factory.createCapabilities(config, browser, proxy, browserDownloadsFolder); Map<String, Object> prefsMap = getBrowserLaunchPrefs(ChromeOptions.CAPABILITY, chromeOptions); assertThat(prefsMap).hasSizeGreaterThanOrEqualTo(4); assertThat(prefsMap).containsEntry("credentials_enable_service", false); assertThat(prefsMap).containsEntry("plugins.always_open_pdf_externally", true); assertThat(prefsMap).containsEntry("profile.default_content_setting_values.automatic_downloads", 1); assertThat(prefsMap).containsEntry("download.default_directory", new File(DOWNLOADS_FOLDER).getAbsolutePath()); }
Source:
public DefaultByteBufHolder(ByteBuf data) { ObjectUtil.checkNotNull(data, "data"); this.data = data; }

Target:
public DefaultByteBufHolder(ByteBuf data) { this.data = ObjectUtil.checkNotNull(data, "data"); }
Source:
public void cleanupExistingArchivableStuff() { assertTimeoutPreemptively(ofSeconds(ARCHIVE_TIMEOUT), () -> archiveService.archiveWorkflows(DateTime.now(), 10)); }

Target:
public void cleanupExistingArchivableStuff() { assertTimeoutPreemptively(ARCHIVE_TIMEOUT, () -> archiveService.archiveWorkflows(now(), 10)); }
Source:
public void testIndexSegmentation() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { qryParallelism = 2; Ignite client = startGrid(4); assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); qryParallelism = 6; assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }

Target:
public void testIndexSegmentation() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { qryParallelism = 2; Ignite client = startGrid(4); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }
Source:
public void onDisconnect() { logger.info("Disconnected from my.openHAB service"); mIsConnected = false; }

Target:
public void onDisconnect() { logger.info("Disconnected from my.openHAB service (UUID = {}, base URL = {})", this.mUUID, this.mOHBaseUrl); mIsConnected = false; }
Source:
public void enterVariableDeclaration(SwiftParser.VariableDeclarationContext ctx) { ParseTreeWalker walker = new ParseTreeWalker(); if (ctx == null || ctx.patternInitializerList() == null) { return; } for (SwiftParser.PatternInitializerContext context : ctx.patternInitializerList().patternInitializer()) { SwiftParser.PatternContext pattern = context.pattern(); listenerHelper.evaluatePattern(pattern, walker, new VariableDecListener(this.printer)); } }

Target:
public void enterVariableDeclaration(SwiftParser.VariableDeclarationContext ctx) { ParseTreeWalker walker = new ParseTreeWalker(); if (ctx.patternInitializerList() == null) { return; } for (SwiftParser.PatternInitializerContext context : ctx.patternInitializerList().patternInitializer()) { SwiftParser.PatternContext pattern = context.pattern(); listenerHelper.evaluatePattern(pattern, walker, new VariableDecListener(this.printer)); } }
Source:
public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); if (socketBindingGroup == null) { socketBindingGroup = ctx.client.options().isDomain ? "full-sockets" : "standard-sockets"; } Address socketBindingAddress = Address.of("socket-binding-group", socketBindingGroup) .and("socket-binding", socketBindingName); ops.removeIfExists(socketBindingAddress); }

Target:
public void apply(OnlineCommandContext ctx) throws Exception { Operations ops = new Operations(ctx.client); String bindingGroup = this.socketBindingGroup; if (bindingGroup == null) { bindingGroup = ctx.client.options().isDomain ? "full-sockets" : "standard-sockets"; } Address socketBindingAddress = Address.of("socket-binding-group", bindingGroup) .and("socket-binding", socketBindingName); ops.remove(socketBindingAddress); }
Source:
public void testSizeCallbackIsNotCalledPreDrawIfNoDimensSetOnPreDraw() { SizeReadyCallback cb = mock(SizeReadyCallback.class); target.getSize(cb); PreDrawShadowViewTreeObserver shadowObserver = Robolectric.shadowOf_(view.getViewTreeObserver()); shadowObserver.fireOnPreDrawListeners(); verify(cb, never()).onSizeReady(anyInt(), anyInt()); assertEquals(1, shadowObserver.getPreDrawListeners().size()); }

Target:
public void testSizeCallbackIsNotCalledPreDrawIfNoDimensSetOnPreDraw() { SizeReadyCallback cb = mock(SizeReadyCallback.class); target.getSize(cb); PreDrawShadowViewTreeObserver shadowObserver = Robolectric.shadowOf_(view.getViewTreeObserver()); shadowObserver.fireOnPreDrawListeners(); verify(cb, never()).onSizeReady(anyInt(), anyInt()); assertThat(shadowObserver.getPreDrawListeners(), hasSize(1)); }
Source:
public LogReplicationEntry receive(LogReplicationEntry message) { rxMessageCounter++; rxMessageCount.setValue(rxMessageCounter); log.debug("Sink manager received while in {}", message.getMetadata().getMessageMetadataType(), rxState); if (message.getMetadata().getTopologyConfigId() != siteConfigID) { log.trace("Sink manage with config id ignored msg id {}", siteConfigID, message.getMetadata().getTopologyConfigId()); return null; } if (message.getMetadata().getMessageMetadataType().equals(MessageType.SNAPSHOT_START)) { processSnapshotStart(message); return null; } if (!receivedValidMessage(message)) { END ACK message and END message again, but the receiver has already transited to if (message.getMetadata().getMessageMetadataType() == SNAPSHOT_END) { LogReplicationEntryMetadata metadata = snapshotSinkBufferManager.makeAckMessage(message); if (metadata.getMessageMetadataType() == SNAPSHOT_END) { log.warn("Sink Manager in state and received message {}. Resending the ACK for SNAPSHOT_END.", rxState, message.getMetadata()); return new LogReplicationEntry(metadata, new byte[0]); } } log.warn("Sink Manager in state and received message {}. Dropping Message.", rxState, message.getMetadata()); return null; } if (rxState.equals(RxState.LOG_ENTRY_SYNC)) { return logEntrySinkBufferManager.processMsgAndBuffer(message); } else { return snapshotSinkBufferManager.processMsgAndBuffer(message); } }

Target:
public LogReplicationEntry receive(LogReplicationEntry message) { rxMessageCounter++; rxMessageCount.setValue(rxMessageCounter); log.debug("Sink manager received while in {}", message.getMetadata().getMessageMetadataType(), rxState); if (message.getMetadata().getTopologyConfigId() != topologyConfigId) { log.trace("Sink manager with config id ignored msg id {}", topologyConfigId, message.getMetadata().getTopologyConfigId()); return null; } if (message.getMetadata().getMessageMetadataType().equals(MessageType.SNAPSHOT_START)) { processSnapshotStart(message); return null; } if (!receivedValidMessage(message)) { END ACK message and END message again, but the receiver has already transited to if (message.getMetadata().getMessageMetadataType() == SNAPSHOT_END) { LogReplicationEntryMetadata metadata = snapshotSinkBufferManager.makeAckMessage(message); if (metadata.getMessageMetadataType() == SNAPSHOT_END) { log.warn("Sink Manager in state and received message {}. Resending the ACK for SNAPSHOT_END.", rxState, message.getMetadata()); return new LogReplicationEntry(metadata, new byte[0]); } } log.warn("Sink Manager in state and received message {}. Dropping Message.", rxState, message.getMetadata()); return null; } if (rxState.equals(RxState.LOG_ENTRY_SYNC)) { return logEntrySinkBufferManager.processMsgAndBuffer(message); } else { return snapshotSinkBufferManager.processMsgAndBuffer(message); } }
Source:
public RewrittenAggregateProjections(boolean isValueAggregateQuery, Document document) { if (document == null) { throw new IllegalArgumentException("document cannot be null"); } if (isValueAggregateQuery) { this.payload = new Document(document.getPropertyBag()); } else { if (document.get("payload") instanceof ObjectNode) { this.payload = new Document((ObjectNode) document.get("payload")); } } }

Target:
public RewrittenAggregateProjections(boolean isValueAggregateQuery, Document document) { if (document == null) { throw new IllegalArgumentException("document cannot be null"); } if (isValueAggregateQuery) { this.payload = new Document(document.getPropertyBag()); } else { if (!document.has(PAYLOAD_PROPERTY_NAME)) { throw new IllegalStateException("Underlying object does not have an 'payload' field."); } if (document.get(PAYLOAD_PROPERTY_NAME) instanceof ObjectNode) { this.payload = new Document((ObjectNode) document.get(PAYLOAD_PROPERTY_NAME)); } } }
Source:
private List<HttpCookie> processCookieHeader(String headerKey, List<String> headerValues) { List<HttpCookie> foundCookies = new LinkedList<>(); for (String headerValue : headerValues) { foundCookies .addAll(HttpCookie.parse(headerKey + ":" + headerValue)); } return foundCookies; }

Target:
private List<HttpCookie> processCookieHeader(String headerKey, List<String> headerValues) { List<HttpCookie> foundCookies = new LinkedList<>(); for (String headerValue : headerValues) { foundCookies .addAll(HttpCookie.parse(headerKey + ':' + headerValue)); } return foundCookies; }
Source:
public Object addNonInheritableProperty(String key, Object value) { if (getInheritableProperties().containsKey(key)) { final Object oldValue = getInheritableProperties().get(key); getInheritableProperties().removeKey(key); getNonInheritableProperties().put(key, value); return oldValue; } return getNonInheritableProperties().put(key, value); }

Target:
public Object addNonInheritableProperty(String key, Object value) { if (getInheritableProperties().containsKey(key)) { final Object oldValue = getInheritableProperties().removeKey(key); getNonInheritableProperties().put(key, value); return oldValue; } return getNonInheritableProperties().put(key, value); }
Source:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { waitForTaskToComplete(); } final Future<AuthorizationStatus> job = completionService.submit(new Callable<AuthorizationStatus>() { @Override public AuthorizationStatus call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength, authzStatus); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return op.getAuthorizationStatus(); } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }

Target:
private synchronized void writeCurrentBufferToService() throws IOException { if (bufferIndex == 0) { return; } final byte[] bytes = buffer; final int bytesLength = bufferIndex; buffer = byteBufferPool.getBuffer(false, bufferSize).array(); bufferIndex = 0; final long offset = position; position += bytesLength; if (threadExecutor.getQueue().size() >= maxConcurrentRequestCount * 2) { waitForTaskToComplete(); } final Future<Void> job = completionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { AbfsPerfTracker tracker = client.getAbfsPerfTracker(); try (AbfsPerfInfo perfInfo = new AbfsPerfInfo(tracker, "writeCurrentBufferToService", "append")) { AbfsRestOperation op = client.append(path, offset, bytes, 0, bytesLength); perfInfo.registerResult(op.getResult()); byteBufferPool.putBuffer(ByteBuffer.wrap(bytes)); perfInfo.registerSuccess(true); return null; } } }); writeOperations.add(new WriteOperation(job, offset, bytesLength)); shrinkWriteOperationQueue(); }
Source:
private boolean imageWriterPathIsValid() { if ((!copyImageCheckbox.isSelected()) || !(localDisk != null)) { imageWriterErrorLabel.setVisible(false); imageWriterErrorLabel.setText(""); return true; } if (pathTextField.getText().isEmpty()) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_emptyPath()); return false; } File f = new File(pathTextField.getText()); if (((f.getParentFile() != null) && (!f.getParentFile().exists())) || (f.getParentFile() == null)) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_directoryNotExist()); return false; } if (f.isDirectory()) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_isDirectory()); return false; } if (f.exists()) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_fileExists()); return false; } imageWriterErrorLabel.setVisible(false); imageWriterErrorLabel.setText(""); return true; }

Target:
private boolean imageWriterPathIsValid() { if ((!copyImageCheckbox.isSelected()) || localDisk == null) { imageWriterErrorLabel.setVisible(false); imageWriterErrorLabel.setText(""); return true; } if (pathTextField.getText().isEmpty()) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_emptyPath()); return false; } File f = new File(pathTextField.getText()); if (((f.getParentFile() != null) && (!f.getParentFile().exists())) || (f.getParentFile() == null)) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_directoryNotExist()); return false; } if (f.isDirectory()) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_isDirectory()); return false; } if (f.exists()) { imageWriterErrorLabel.setVisible(true); imageWriterErrorLabel.setText(Bundle.LocalDiskPanel_imageWriterError_fileExists()); return false; } imageWriterErrorLabel.setVisible(false); imageWriterErrorLabel.setText(""); return true; }
Source:
public AVideo(File file) { if (file == null) throw new IllegalArgumentException("null url"); _name = file.getName(); _file = file; _isdata = DYNAMIC_STREAM; _data = null; _url = null; }

Target:
public AVideo(File file) { if (file == null) throw new IllegalArgumentException("file cannot be null"); _name = file.getName(); _file = file; _isdata = DYNAMIC_STREAM; _data = null; _url = null; }
Source:
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.context = context; this.collector = collector; firstPollOffsetStrategy = kafkaSpoutConfig.getFirstPollOffsetStrategy(); retryService = kafkaSpoutConfig.getRetryService(); tupleListener = kafkaSpoutConfig.getTupleListener(); if (isAtLeastOnceProcessing()) { commitTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getOffsetsCommitPeriodMs(), TimeUnit.MILLISECONDS); } refreshSubscriptionTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getPartitionRefreshPeriodMs(), TimeUnit.MILLISECONDS); offsetManagers = new ConcurrentHashMap<>(); emitted = new HashSet<>(); waitingToEmit = Collections.emptyListIterator(); tupleListener.open(conf, context); context.registerMetric("kafkaOffset", new IMetric() { KafkaUtils.KafkaOffsetMetric _kafkaOffsetMetric = new KafkaUtils.KafkaOffsetMetric(offsetManagers, metricsConsumer); @Override public Object getValueAndReset() { return _kafkaOffsetMetric.getValueAndReset(); } }, kafkaSpoutConfig.getMetricsTimeBucketSizeInSecs()); LOG.info("Kafka Spout opened with the following configuration: {}", kafkaSpoutConfig); }

Target:
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.context = context; this.collector = collector; firstPollOffsetStrategy = kafkaSpoutConfig.getFirstPollOffsetStrategy(); retryService = kafkaSpoutConfig.getRetryService(); tupleListener = kafkaSpoutConfig.getTupleListener(); if (isAtLeastOnceProcessing()) { commitTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getOffsetsCommitPeriodMs(), TimeUnit.MILLISECONDS); } refreshSubscriptionTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getPartitionRefreshPeriodMs(), TimeUnit.MILLISECONDS); offsetManagers = new HashMap<>(); emitted = new HashSet<>(); waitingToEmit = new HashMap<>(); setCommitMetadata(context); tupleListener.open(conf, context); if (canRegisterMetrics()) { registerMetric(); } LOG.info("Kafka Spout opened with the following configuration: {}", kafkaSpoutConfig); }
Source:
public boolean match(final ChangeData object) throws OrmException { final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { if (accounts != null && ! accounts.contains(p.getAccountId())) { continue; } allApprovers.add(p.getAccountId()); if (p.getCategoryId().equals(category.getId())) { approversThatVotedInCategory.add(p.getAccountId()); if (match(object.change(dbProvider), p.getValue(), p.getAccountId())) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (final Account.Id a : approversThatDidNotVoteInCategory) { if (match(object.change(dbProvider), 0, a)) { return true; } } return false; }

Target:
public boolean match(final ChangeData object) throws OrmException { final Change c = object.change(dbProvider); if (c == null) { return false; } final ProjectState project = projectCache.get(c.getDest().getParentKey()); if (project == null) { return false; } final LabelType labelType = type(project.getLabelTypes(), type); final Set<Account.Id> allApprovers = new HashSet<Account.Id>(); final Set<Account.Id> approversThatVotedInCategory = new HashSet<Account.Id>(); for (PatchSetApproval p : object.currentApprovals(dbProvider)) { allApprovers.add(p.getAccountId()); if (labelType.matches(p)) { approversThatVotedInCategory.add(p.getAccountId()); if (match(c, p.getValue(), p.getAccountId(), labelType)) { return true; } } } final Set<Account.Id> approversThatDidNotVoteInCategory = new HashSet<Account.Id>(allApprovers); approversThatDidNotVoteInCategory.removeAll(approversThatVotedInCategory); for (Account.Id a : approversThatDidNotVoteInCategory) { if (match(c, 0, a, labelType)) { return true; } } return false; }
Source:
public boolean stop() { List<SyncQueueItemVO> jobs = _syncQueueItemDao.getActiveQueueItems(getMsid(), false); for (SyncQueueItemVO job : jobs) { AsyncJobVO childjob = _jobDao.findById(job.getContentId()); if (childjob != null) { Long parentjobid = Long.parseLong(childjob.getRelated()); try { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancel left-over async. job- " + parentjobid); } cancelAsyncJob(parentjobid, "Management Server shutdown"); } catch (Exception e) { s_logger.error("Exception while cancelling job -" + parentjobid, e); } } _queueMgr.purgeItem(job.getId()); } shutdownAndAwaitTermination(_workerJobExecutor); shutdownAndAwaitTermination(_apiJobExecutor); _heartbeatScheduler.shutdown(); return true; }

Target:
public boolean stop() { List<SyncQueueItemVO> jobs = _syncQueueItemDao.getActiveQueueItems(getMsid(), false); for (SyncQueueItemVO job : jobs) { AsyncJobVO childjob = _jobDao.findById(job.getContentId()); if (childjob != null && StringUtils.isNotBlank(childjob.getRelated())) { Long parentjobid = Long.parseLong(childjob.getRelated()); try { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancel left-over async. job- " + parentjobid); } cancelAsyncJob(parentjobid, "Management Server shutdown"); } catch (Exception e) { s_logger.error("Exception while cancelling job -" + parentjobid, e); } } _queueMgr.purgeItem(job.getId()); } shutdownAndAwaitTermination(_workerJobExecutor); shutdownAndAwaitTermination(_apiJobExecutor); _heartbeatScheduler.shutdown(); return true; }
Source:
public String getUrlForWikiPageWithWWW(String pageName) { if ("".equals(pageName)) throw new WebDriverException("Page name is missing"); return getUrl(true) + URLsContent.WIKI_DIR + pageName; }

Target:
public String getUrlForWikiPageWithWWW(String pageName) { if ("".equals(pageName)) { throw new WebDriverException("Page name is missing"); } return getUrl(true) + URLsContent.WIKI_DIR + pageName; }
Source:
public void onImport(String fileContents) { GWT.log(this.toString() + "onImport(" + fileContents + ")"); scenarioSimulationEditorWrapper.onImport(fileContents, getImportCallBack(), getImportErrorCallback(), context.getStatus().getSimulation()); }

Target:
public void onImport(String fileContents) { scenarioSimulationEditorWrapper.onImport(fileContents, getImportCallBack(), getImportErrorCallback(), context.getStatus().getSimulation()); }
Source:
private boolean memoryNextRunSnapshotRequired() { final VM vmFromDb = getVm(); final VM vmFromParams = getParameters().getVm(); return VMStatus.Down != getVm().getStatus() && vmFromDb.getMemSizeMb() != vmFromParams.getMemSizeMb(); }

Target:
private boolean memoryNextRunSnapshotRequired() { final VM oldVm = getVm(); return VMStatus.Down != getVm().getStatus() && oldVm.getMemSizeMb() != getParameters().getVm().getMemSizeMb(); }
Source:
public void test24HourDateConversions() { ZonedDateTime date = ZonedDateTime.parse("2018-06-04T09:07:30-04:00"); QueryDate qd = new QueryDate(date.toInstant().toEpochMilli()); assertThat(qd.toString().indexOf("2018-06-04T13:07:30"), not(equalTo(-1))); }

Target:
public void test24HourDateConversions() { ZonedDateTime date = ZonedDateTime.parse("2018-06-04T09:07:30-04:00"); QueryDate qd = new QueryDate(date.toInstant().toEpochMilli()); assertThat(qd.toString().indexOf("2018-06-04T13:07:30.00Z"), not(equalTo(-1))); }
Source:
public ComponentValidationDiagnostic validate(final IBranchPath branchPath, final SnomedConceptIndexEntry component) { final SnomedTaxonomyService taxonomyService = getServiceForClass(SnomedTaxonomyService.class); final String conceptId = component.getId(); if (isConceptReferenceItself(branchPath, taxonomyService, conceptId)) { final SnomedStatementBrowser statementBrowser = getServiceForClass(SnomedStatementBrowser.class); for (final SnomedRelationshipIndexEntry relationship : statementBrowser.getOutboundStatements(branchPath, component)) { if (relationship.isActive() && relationship.getValueId().equals(conceptId)) { return new ComponentValidationDiagnosticImpl(conceptId, createErrorMessage(component, relationship, branchPath), ID, CONCEPT_NUMBER, error()); } } } return createOk(conceptId, ID, CONCEPT_NUMBER); }

Target:
public ComponentValidationDiagnostic validate(final IBranchPath branchPath, final SnomedConceptIndexEntry component) { final String conceptId = component.getId(); SnomedRelationships relationships = SnomedRequests.prepareSearchRelationship() .all() .filterByActive(true) .filterByDestination(conceptId) .filterBySource(conceptId) .setExpand("type(expand(pt()))") .setLocales(getLocales()) .build(branchPath.getPath()) .executeSync(getBus()); if (!relationships.getItems().isEmpty()) { for (ISnomedRelationship relationship : relationships) { return new ComponentValidationDiagnosticImpl(conceptId, createErrorMessage(component, relationship, branchPath), ID, CONCEPT_NUMBER, error()); } } return createOk(conceptId, ID, CONCEPT_NUMBER); }
Source:
protected void updateData(long start, long end, int nb, IProgressMonitor monitor) { double[] xAxis = getXAxis(start, end, nb); if (xAxis.length == 1) { return; } setXAxis(xAxis); try (ScopeLog log = new ScopeLog(LOGGER, Level.FINE, "CounterChartViewer#updateData")) { for (Object entry : fEntries) { if (monitor.isCanceled()) { return; } if (!(entry instanceof CounterTreeViewerEntry)) { continue; } CounterTreeViewerEntry counterEntry = (CounterTreeViewerEntry) entry; double[] steps = new double[xAxis.length]; ITmfStateSystem ss = counterEntry.getStateSystem(); Integer quark = counterEntry.getQuark(); long stateSystemStartTime = ss.getStartTime(); long stateSystemEndTime = ss.getCurrentEndTime(); long prevTime = Math.max(stateSystemStartTime, (long) (start - (xAxis[1]))); if (prevTime <= stateSystemEndTime) { Object prev = ss.querySingleState(prevTime, quark).getValue(); long prevValue = prev instanceof Long ? (long) prev : 0; for (int i = 0; i < xAxis.length; i++) { long nextTime = start + (long) xAxis[i] - 1; if (nextTime >= stateSystemStartTime && nextTime <= stateSystemEndTime) { Object next = ss.querySingleState(nextTime, quark).getValue(); long nextValue = next instanceof Long ? (long) next : 0; steps[i] = (next == null) ? 0 : nextValue - prevValue; prevValue = nextValue; } } } setSeries(counterEntry.getFullPath(), steps); } } catch (StateSystemDisposedException e) { return; } updateDisplay(); }

Target:
protected void updateData(long start, long end, int nb, IProgressMonitor monitor) { double[] xAxis = getXAxis(start, end, nb); if (xAxis.length == 1) { return; } setXAxis(xAxis); try (ScopeLog log = new ScopeLog(LOGGER, Level.FINE, "CounterChartViewer#updateData")) { for (CounterTreeViewerEntry counterEntry : Iterables.filter(fEntries, CounterTreeViewerEntry.class)) { if (monitor.isCanceled()) { return; } double[] steps = new double[xAxis.length]; ITmfStateSystem ss = counterEntry.getStateSystem(); Integer quark = counterEntry.getQuark(); long stateSystemStartTime = ss.getStartTime(); long stateSystemEndTime = ss.getCurrentEndTime(); long prevTime = Math.max(stateSystemStartTime, (long) (start - (xAxis[1]))); if (prevTime <= stateSystemEndTime) { Object prev = ss.querySingleState(prevTime, quark).getValue(); long prevValue = prev instanceof Long ? (long) prev : 0; for (int i = 0; i < xAxis.length; i++) { long nextTime = start + (long) xAxis[i] - 1; if (nextTime >= stateSystemStartTime && nextTime <= stateSystemEndTime) { Object next = ss.querySingleState(nextTime, quark).getValue(); long nextValue = next instanceof Long ? (long) next : 0; steps[i] = (next == null) ? 0 : nextValue - prevValue; prevValue = nextValue; } } } setSeries(counterEntry.getFullPath(), steps); } } catch (StateSystemDisposedException e) { return; } updateDisplay(); }
Source:
public <R> R execute(ResultProducer<R> producer) { if (bindings.isEmpty()) { throw new IllegalStateException("No batch parts to execute"); } try { return producer.produce(() -> internalBatchExecute().stmt, getContext()); } catch (SQLException e) { throw new UnableToProduceResultException("Exception producing batch result", e, getContext()); } }

Target:
public <R> R execute(ResultProducer<R> producer) { try { return producer.produce(() -> internalBatchExecute().stmt, getContext()); } catch (SQLException e) { throw new UnableToProduceResultException("Exception producing batch result", e, getContext()); } }
Source:
public static Address[] getListPostAddresses(Message message) { String[] headerValues = new String[0]; try { headerValues = message.getHeader(LIST_POST_HEADER); } catch (MessagingException e) { Log.e(K9MailLib.LOG_TAG, "Unable to parse list-post header", e); } if (headerValues.length < 1) { return new Address[0]; } List<Address> listPostAddresses = new ArrayList<>(); for (String headerValue : headerValues) { if (headerValue == null || headerValues[0].isEmpty()) { continue; } Matcher m = mailtoContainerPattern.matcher(headerValue); if (!m.find()) { continue; } String mailToUri = m.group(1); String emailAddress = MailTo.parse(mailToUri).getTo(); listPostAddresses.add(new Address(emailAddress)); } return listPostAddresses.toArray(new Address[listPostAddresses.size()]); }

Target:
public static Address[] getListPostAddresses(Message message) { String[] headerValues = new String[0]; try { headerValues = message.getHeader(LIST_POST_HEADER); } catch (MessagingException e) { Log.e(K9MailLib.LOG_TAG, "Unable to parse list-post header", e); } if (headerValues.length < 1) { return new Address[0]; } List<Address> listPostAddresses = new ArrayList<>(); for (String headerValue : headerValues) { if (headerValue == null || headerValue.isEmpty()) { continue; } Matcher m = mailtoContainerPattern.matcher(headerValue); if (!m.find()) { continue; } String mailToUri = m.group(1); String emailAddress = MailTo.parse(mailToUri).getTo(); listPostAddresses.add(new Address(emailAddress)); } return listPostAddresses.toArray(new Address[listPostAddresses.size()]); }
Source:
public void load() throws TableNotFoundException, IOException, AccumuloException, AccumuloSecurityException { TableId tableId = Tables.getTableId(context, tableName); Map<String,String> props = context.instanceOperations().getSystemConfiguration(); AccumuloConfiguration conf = new ConfigurationCopy(props); FileSystem fs = VolumeConfiguration.getVolume(dir, context.getHadoopConf(), conf).getFileSystem(); Path srcPath = checkPath(fs, dir); SortedMap<KeyExtent,Bulk.Files> mappings; TableOperationsImpl tableOps = new TableOperationsImpl(context); boolean retry = true; while (retry) { if (plan == null) { mappings = computeMappingFromFiles(fs, tableId, srcPath); } else { mappings = computeMappingFromPlan(fs, tableId, srcPath); } if (mappings.isEmpty()) throw new IllegalArgumentException("Attempted to import zero files from " + srcPath); BulkSerialize.writeLoadMapping(mappings, srcPath.toString(), fs::create); List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableId.canonical().getBytes(UTF_8)), ByteBuffer.wrap(srcPath.toString().getBytes(UTF_8)), ByteBuffer.wrap((setTime + "").getBytes(UTF_8))); try { tableOps.doBulkFateOperation(args, tableName); retry = false; } catch (AccumuloBulkMergeException ae) { if (plan != null) { checkPlanForSplits(); } log.info(ae.getMessage() + ". Retrying bulk import to " + tableName); } } }

Target:
public void load() throws TableNotFoundException, IOException, AccumuloException, AccumuloSecurityException { TableId tableId = Tables.getTableId(context, tableName); Map<String,String> props = context.instanceOperations().getSystemConfiguration(); AccumuloConfiguration conf = new ConfigurationCopy(props); FileSystem fs = VolumeConfiguration.getVolume(dir, context.getHadoopConf(), conf).getFileSystem(); Path srcPath = checkPath(fs, dir); SortedMap<KeyExtent,Bulk.Files> mappings; TableOperationsImpl tableOps = new TableOperationsImpl(context); Retry retry = Retry.builder().infiniteRetries().retryAfter(100, MILLISECONDS) .incrementBy(100, MILLISECONDS).maxWait(2, MINUTES).backOffFactor(1.5) .logInterval(3, TimeUnit.MINUTES).createRetry(); boolean shouldRetry = true; while (shouldRetry) { if (plan == null) { mappings = computeMappingFromFiles(fs, tableId, srcPath); } else { mappings = computeMappingFromPlan(fs, tableId, srcPath); } if (mappings.isEmpty()) throw new IllegalArgumentException("Attempted to import zero files from " + srcPath); BulkSerialize.writeLoadMapping(mappings, srcPath.toString(), fs::create); List<ByteBuffer> args = Arrays.asList(ByteBuffer.wrap(tableId.canonical().getBytes(UTF_8)), ByteBuffer.wrap(srcPath.toString().getBytes(UTF_8)), ByteBuffer.wrap((setTime + "").getBytes(UTF_8))); try { tableOps.doBulkFateOperation(args, tableName); shouldRetry = false; } catch (AccumuloBulkMergeException ae) { if (plan != null) { checkPlanForSplits(ae); } try { retry.waitForNextAttempt(); } catch (InterruptedException e) { throw new RuntimeException(e); } log.info(ae.getMessage() + ". Retrying bulk import to " + tableName); } } }
Source:
public final void send(Event event) { try { waitIfLockedDown(); doSend(event); waitingTime = baseWaitingTime; } catch (ConnectionException e) { for (EventSendFailureCallback eventSendFailureCallback : eventSendFailureCallbacks) { eventSendFailureCallback.onFailure(event, e); } logger.warn("An exception due to the connection occurred, a lockdown will be initiated.", e); lockDown(); } }

Target:
public final void send(Event event) { try { waitIfLockedDown(); doSend(event); waitingTime = baseWaitingTime; } catch (ConnectionException e) { logger.warn("An exception due to the connection occurred, a lockdown will be initiated.", e); lockDown(); for (EventSendFailureCallback eventSendFailureCallback : eventSendFailureCallbacks) { try { eventSendFailureCallback.onFailure(event, e); } catch (Exception exc) { logger.warn("An exception occurred while running an EventSendFailureCallback: " + eventSendFailureCallback.getClass().getName(), exc); } } } }
Source:
public void serialize(final Host host, final JsonGenerator jgen, final SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("hostId", host.getHostId()); jgen.writeStringField("ipAddress", host.getIp().toSimpleString()); jgen.writeStringField("mac", host.getMac().toString()); jgen.writeStringField("dpid", host.getPort().getParentSwitch() .getSwitchName()); jgen.writeNumberField("port", host.getPort().getPortNumber()); jgen.writeEndObject(); }

Target:
public void serialize(final Host host, final JsonGenerator jgen, final SerializerProvider sp) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeNumberField("hostId", host.getHostId()); jgen.writeStringField("ipAddress", host.getIp().toSimpleString()); jgen.writeStringField("mac", host.getMac().toString()); jgen.writeStringField("vdpid", host.getPort().getParentSwitch() .getSwitchName()); jgen.writeNumberField("vport", host.getPort().getPortNumber()); jgen.writeEndObject(); }
Source:
public String[] metaStringArrayByKey( String key, String[] def ) { Map<Integer, String> temp = m_metaStringArraysByKey.get( key ); if ( temp == null ) { return def; } else { String[] ret = new String[temp.size()]; for ( int i = 0; i < temp.size() ; i++ ) { ret[0] = "" ; } for ( Map.Entry<Integer, String> entry : temp.entrySet() ) { ret[entry.getKey() - 1] = entry.getValue() ; } return ret; } }

Target:
public String[] metaStringArrayByKey( String key, String[] def ) { Map<Integer, String> temp = m_metaStringArraysByKey.get( key ); if ( temp == null ) { return def; } else { String[] ret = new String[temp.size()]; for ( int i = 1 ; i <= temp.size() ; i++ ) { String v = temp.get( i ); if ( null == v ) { throw new RuntimeException( "temp should have 1, 2, ..., temp.size() members." ); } ret[i - 1] = v; } return ret; } }
Source:
public static ClusterComposition parse( Record record, long now ) { if ( record == null ) { return null; } final ClusterComposition result; result = new ClusterComposition( expirationTimestamp( now, record ) ); record.get( "servers" ).asList( new Function<Value,Void>() { @Override public Void apply( Value value ) { result.servers( value.get( "role" ).asString() ) .addAll( value.get( "addresses" ).asList( OF_BoltServerAddress ) ); return null; } } ); return result; }

Target:
public static ClusterComposition parse( Record record, long now ) { if ( record == null ) { return null; } final ClusterComposition result = new ClusterComposition( expirationTimestamp( now, record ) ); record.get( "servers" ).asList( new Function<Value,Void>() { @Override public Void apply( Value value ) { result.servers( value.get( "role" ).asString() ) .addAll( value.get( "addresses" ).asList( OF_BoltServerAddress ) ); return null; } } ); return result; }
Source:
protected void onDeclineButtonClicked() { if (!mSipServiceConnection.isAvailableAndHasActiveCall()) { finish(); return; } try { mSipServiceConnection.get().getCurrentCall().hangup(true); } catch (Exception e) { e.printStackTrace(); } }

Target:
protected void onDeclineButtonClicked() { if (!mSipServiceConnection.isAvailableAndHasActiveCall()) { finish(); return; } try { mSipServiceConnection.get().getCurrentCall().hangup(true); mLogger.i("The user hang up from Network Availability Activity"); } catch (Exception e) { mLogger.i("Failed to decline call "+e.getClass().getSimpleName()+e.getMessage()); finish(); } }