auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean tryAdvance(Consumer<? super Map<Address, CacheEntry<K, V>>> action) { while (!iterator.hasNext()) { if (nextSegment < totalSegments) { try { if (trace) <START> log.tracef("Cache %s Attempting to receive all replicas for segment %s with topology %s", cacheName, nextSegment, topology); <END> segmentRequestFuture = stateReceiver.getAllReplicasForSegment(nextSegment, topology); long remainingTime = timeService.remainingTime(endTime, TimeUnit.MILLISECONDS); List<Map<Address, CacheEntry<K, V>>> segmentEntries = segmentRequestFuture.get(remainingTime, TimeUnit.MILLISECONDS); if (trace) log.tracef("Cache %s Segment %s entries received: %s", cacheName, nextSegment, segmentEntries); nextSegment++; iterator = segmentEntries.iterator(); } catch (CancellationException e) { handleException(e); return false; } catch (InterruptedException e) { handleException(e); stateReceiver.stop(); Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { handleException(e); Throwable cause = e.getCause(); throw new CacheException(e.getMessage(), cause != null ? cause : e); } } else { streamInProgress.compareAndSet(true, false); return false; } } action.accept(iterator.next()); return true; }</code><technical_language>a fan of mid-sentence capitalization :)</technical_language>

Target:
public boolean tryAdvance(Consumer<? super Map<Address, CacheEntry<K, V>>> action) { while (!iterator.hasNext()) { if (nextSegment < totalSegments) { try { if (trace) log.tracef("Cache %s attempting to receive all replicas for segment %s with topology %s", cacheName, nextSegment, topology); segmentRequestFuture = stateReceiver.getAllReplicasForSegment(nextSegment, topology); long remainingTime = timeService.remainingTime(endTime, TimeUnit.MILLISECONDS); List<Map<Address, CacheEntry<K, V>>> segmentEntries = segmentRequestFuture.get(remainingTime, TimeUnit.MILLISECONDS); if (trace) log.tracef("Cache %s segment %s entries received: %s", cacheName, nextSegment, segmentEntries); nextSegment++; iterator = segmentEntries.iterator(); } catch (CancellationException e) { handleException(e); return false; } catch (InterruptedException e) { handleException(e); Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { handleException(e); Throwable cause = e.getCause(); throw new CacheException(e.getMessage(), cause != null ? cause : e); } } else { streamInProgress.compareAndSet(true, false); return false; } } action.accept(iterator.next()); return true; }
Source:
<code>public void userPrivateRole() { RealmResults<PermissionUser> permissionUsers = realm.where(PermissionUser.class).findAll(); assertEquals(1, permissionUsers.size()); <START> PermissionUser permissionUser = permissionUsers.get(0); <END> assertNotNull(permissionUser); Role role = permissionUser.getRole(); assertNotNull(role); assertEquals("__User:" + user.getIdentity(), role.getName()); assertTrue(role.hasMember(user.getIdentity())); }</code><technical_language>clear this user is created</technical_language>

Target:
public void userPrivateRole() { RealmResults<PermissionUser> permissionUsers = realm.where(PermissionUser.class).findAll(); assertEquals(1, permissionUsers.size()); PermissionUser permissionUser = permissionUsers.get(0); assertNotNull(permissionUser); Role role = permissionUser.getPrivateRole(); assertNotNull(role); assertEquals("__User:" + user.getIdentity(), role.getName()); assertTrue(role.hasMember(user.getIdentity())); }
Source:
<code>private IRadio getRadioProxy(Message result) { if (!mIsMobileNetworkSupported) { <START> riljLog("Not calling getService(): wifi-only"); <END> return null; } if (mRadioProxy != null) { return mRadioProxy; } try { mRadioProxy = IRadio.getService(SOCKET_NAME_RIL[mPhoneId == null ? 0 : mPhoneId]); if (mRadioProxy != null) { mRadioProxy.linkToDeath(mRadioProxyDeathRecipient, mRadioProxyCookie.incrementAndGet()); mRadioProxy.setResponseFunctions(mRadioResponse, mRadioIndication); } else { riljLoge("getRadioProxy: radioProxy == null"); } } catch (RemoteException | RuntimeException e) { mRadioProxy = null; if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(RADIO_NOT_AVAILABLE)); result.sendToTarget(); } mRilHandler.sendMessageDelayed( mRilHandler.obtainMessage(EVENT_RADIO_PROXY_DEAD, mRadioProxyCookie.get()), IRADIO_GET_SERVICE_DELAY_MILLIS); riljLoge("setResponseFunctions", e); } return mRadioProxy; }</code><technical_language>move this log printed for wifi device for call</technical_language>

Target:
private IRadio getRadioProxy(Message result) { if (!mIsMobileNetworkSupported) { if (RILJ_LOGV) riljLog("Not calling getService(): wifi-only"); return null; } if (mRadioProxy != null) { return mRadioProxy; } try { mRadioProxy = IRadio.getService(SOCKET_NAME_RIL[mPhoneId == null ? 0 : mPhoneId]); if (mRadioProxy != null) { mRadioProxy.linkToDeath(mRadioProxyDeathRecipient, mRadioProxyCookie.incrementAndGet()); mRadioProxy.setResponseFunctions(mRadioResponse, mRadioIndication); } else { riljLoge("getRadioProxy: radioProxy == null"); } } catch (RemoteException | RuntimeException e) { mRadioProxy = null; if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(RADIO_NOT_AVAILABLE)); result.sendToTarget(); } mRilHandler.sendMessageDelayed( mRilHandler.obtainMessage(EVENT_RADIO_PROXY_DEAD, mRadioProxyCookie.get()), IRADIO_GET_SERVICE_DELAY_MILLIS); riljLoge("setResponseFunctions", e); } return mRadioProxy; }
Source:
<code>Configurer(Config config) { <START> ConditionUtility.notNull(config); <END> this.config = config; }</code><technical_language>sure, @NotNull</technical_language>

Target:
Configurer(Config config) { Objects.requireNonNull(config); this.config = config; }
Source:
<code><START> public void initTestAggregationFunction() <END> { typeRegistry = new TypeRegistry(); functionManager = new FunctionManager(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); session = testSessionBuilder().build(); }</code><technical_language>Is this a necessary change</technical_language>

Target:
public final void initTestAggregationFunction() { typeRegistry = new TypeRegistry(); functionManager = new FunctionManager(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); }
Source:
<code>private void applySessionToken(RxDocumentServiceRequest request) { Map<String, String> headers = request.getHeaders(); Objects.requireNonNull(headers, "RxDocumentServiceRequest::headers is required and cannot be null"); String requestConsistencyLevel = headers.get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); boolean sessionTokenApplicable = <START> Strings.areEqualIgnoreCase(requestConsistencyLevel, ConsistencyLevel.SESSION.toString()) || <END> (this.defaultConsistencyLevel == ConsistencyLevel.SESSION && (!request.isReadOnlyRequest() || request.getResourceType() != ResourceType.Document || !Strings.areEqualIgnoreCase(requestConsistencyLevel, ConsistencyLevel.EVENTUAL.toString()))); if (!Strings.isNullOrEmpty(request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN))) { if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } return; } if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { return; } String sessionToken = this.sessionContainer.resolveGlobalSessionToken(request); if (!Strings.isNullOrEmpty(sessionToken)) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken); } }</code><technical_language>code sets consistency level in headers, ConsistencyLeve.toString(). casing same. ignore-case equality is needed</technical_language>

Target:
private void applySessionToken(RxDocumentServiceRequest request) { Map<String, String> headers = request.getHeaders(); Objects.requireNonNull(headers, "RxDocumentServiceRequest::headers is required and cannot be null"); String requestConsistencyLevel = headers.get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); boolean sessionTokenApplicable = Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.SESSION.toString()) || (this.defaultConsistencyLevel == ConsistencyLevel.SESSION && (!request.isReadOnlyRequest() || request.getResourceType() != ResourceType.Document || !Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.EVENTUAL.toString()))); if (!Strings.isNullOrEmpty(request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN))) { if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } return; } if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { return; } String sessionToken = this.sessionContainer.resolveGlobalSessionToken(request); if (!Strings.isNullOrEmpty(sessionToken)) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken); } }
Source:
<code>public void getOrderHistoryByConcept_shouldReturnOrdersWithTheGivenConcept() throws Exception { Concept concept = Context.getConceptService().getConcept(88); Patient patient = Context.getPatientService().getPatient(2); List<Order> orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); <START> Assert.assertEquals(3, orders.size()); <END> for (Order order : orders) Assert.assertTrue(order.getOrderId() == 4 || order.getOrderId() == 5 || order.getOrderId() == 444); concept = Context.getConceptService().getConcept(792); orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); for (Order order : orders) Assert.assertTrue(order.getOrderId() == 2 || order.getOrderId() == 3 || order.getOrderId() == 222); }</code><technical_language>This is changing 2 3 of new discontinue orders, right</technical_language>

Target:
public void getOrderHistoryByConcept_shouldReturnOrdersWithTheGivenConcept() throws Exception { Concept concept = Context.getConceptService().getConcept(88); Patient patient = Context.getPatientService().getPatient(2); List<Order> orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); Assert.assertTrue(orders.get(0).getOrderId() == 5); Assert.assertTrue(orders.get(1).getOrderId() == 4); Assert.assertTrue(orders.get(2).getOrderId() == 444); concept = Context.getConceptService().getConcept(792); orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); Assert.assertTrue(orders.get(0).getOrderId() == 3); Assert.assertTrue(orders.get(1).getOrderId() == 2); Assert.assertTrue(orders.get(2).getOrderId() == 222); }
Source:
<code>public void setHeader(Widget widget) { <START> widget.addStyleName("obrand_dialogHeaderTitleElement"); END> headerTitlePanel.insert(widget, 0); }</code><technical_language>style object this: widget.addStyle(style.obrandDialogHeaderTitleElement()); add style interface above. This works right due fact obrand_ external, if changes this break. If style.xx of if style is external not</technical_language>

Target:
public void setHeader(Widget widget) { widget.addStyleName(style.obrand_dialogHeaderTitleElement()); headerTitlePanel.insert(widget, 0); }
Source:
<code>public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; <START> done = false; <END> }</code><technical_language>I need this new flag. immediately return null fetchNextReady() if child closed, test child.isOpen() child.eos(). @jingjingwang do agree</technical_language>

Target:
public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; }
Source:
<code>public void testLoginValidUserAndPasswordButNotAuthorisedToSendNonPersistent() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connectionFactory.setConfirmationWindowSize(100); connectionFactory.setBlockOnDurableSend(false); connectionFactory.setBlockOnNonDurableSend(false); Connection connection = connectionFactory.createConnection("guest", "guest"); Session session = connection.createSession(); Destination destination = session.createQueue("guest.cannot.send"); MessageProducer messageProducer = session.createProducer(destination); messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); try { AtomicReference<Exception> e = new AtomicReference<>(); CountDownLatch countDownLatch = new CountDownLatch(1); messageProducer.send(session.createTextMessage("hello"), new CompletionListener() { @Override public void onCompletion(Message message) { countDownLatch.countDown(); } @Override public void onException(Message message, Exception exception) { <START> countDownLatch.countDown(); <END> e.set(exception); } }); countDownLatch.await(10, TimeUnit.SECONDS); if (e.get() != null) { throw e.get(); } fail("JMSSecurityException expected as guest is not allowed to send"); } catch (JMSSecurityException activeMQSecurityException) { activeMQSecurityException.printStackTrace(); } connection.close(); }</code><technical_language>set occur prior countDown avoid potential race check of error state</technical_language>

Target:
public void testLoginValidUserAndPasswordButNotAuthorisedToSendNonPersistent() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connectionFactory.setConfirmationWindowSize(100); connectionFactory.setBlockOnDurableSend(false); connectionFactory.setBlockOnNonDurableSend(false); Connection connection = connectionFactory.createConnection("guest", "guest"); Session session = connection.createSession(); Destination destination = session.createQueue("guest.cannot.send"); MessageProducer messageProducer = session.createProducer(destination); messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); try { AtomicReference<Exception> e = new AtomicReference<>(); CountDownLatch countDownLatch = new CountDownLatch(1); messageProducer.send(session.createTextMessage("hello"), new CompletionListener() { @Override public void onCompletion(Message message) { countDownLatch.countDown(); } @Override public void onException(Message message, Exception exception) { e.set(exception); countDownLatch.countDown(); } }); countDownLatch.await(10, TimeUnit.SECONDS); if (e.get() != null) { throw e.get(); } fail("JMSSecurityException expected as guest is not allowed to send"); } catch (JMSSecurityException activeMQSecurityException) { activeMQSecurityException.printStackTrace(); } connection.close(); }
Source:
<code>private WeekActivityOverviewDto getWeekActivityOverview(UUID userAnonymizedId, LocalDate earliestPossibleDate, LocalDate date, Set<IntervalInactivityDto> missingInactivities) { Interval interval = Interval.createWeekInterval(date); <START> assertDateNotTooEarly(earliestPossibleDate, interval.endDate); <END> UserAnonymizedDto userAnonymized = userAnonymizedService.getUserAnonymized(userAnonymizedId); List<WeekActivityOverviewDto> weekActivityOverviews = getWeekActivityOverviews(userAnonymizedId, earliestPossibleDate, missingInactivities, userAnonymized, interval); return weekActivityOverviews.get(0); }</code><technical_language>more logical swap arguments? asserting interval.endDate here. for readability is interval.assertNotBefore(earliestPossibleDate)</technical_language>

Target:
private WeekActivityOverviewDto getWeekActivityOverview(UUID userAnonymizedId, LocalDate earliestPossibleDate, LocalDate date, Set<IntervalInactivityDto> missingInactivities) { Interval interval = Interval.createWeekInterval(date); assertDateNotTooEarly(interval.endDate, earliestPossibleDate); UserAnonymizedDto userAnonymized = userAnonymizedService.getUserAnonymized(userAnonymizedId); List<WeekActivityOverviewDto> weekActivityOverviews = getWeekActivityOverviews(userAnonymizedId, earliestPossibleDate, missingInactivities, userAnonymized, interval); return weekActivityOverviews.get(0); }
Source:
<code>private void addGlusterVolumeBricks(List<GlusterBrickEntity> bricksList, int replicaCount, int stripeCount, boolean force) { VDSReturnValue returnValue = Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.AddBricksToGlusterVolume, new GlusterVolumeBricksActionVDSParameters(upServer.getId(), getGlusterVolumeName(), bricksList, replicaCount, stripeCount, <START> force)); <END> setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { addCustomValue(GlusterConstants.NO_OF_BRICKS, String.valueOf(bricksList.size())); addGlusterVolumeBricksInDb(bricksList, replicaCount, stripeCount); logAuditMessages(bricksList); getReturnValue().setActionReturnValue(getBrickIds(bricksList)); } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_ADD_BRICK_FAILED, returnValue.getVdsError().getMessage()); return; } }</code><technical_language>pass compatibility version instead of host db for that</technical_language>

Target:
private void addGlusterVolumeBricks(List<GlusterBrickEntity> bricksList, int replicaCount, int stripeCount, boolean force) { VDSReturnValue returnValue = Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.AddBricksToGlusterVolume, new GlusterVolumeBricksActionVDSParameters(upServer.getId(), getGlusterVolumeName(), bricksList, replicaCount, stripeCount, upServer.getVdsGroupCompatibilityVersion(), force)); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { addCustomValue(GlusterConstants.NO_OF_BRICKS, String.valueOf(bricksList.size())); addGlusterVolumeBricksInDb(bricksList, replicaCount, stripeCount); logAuditMessages(bricksList); getReturnValue().setActionReturnValue(getBrickIds(bricksList)); } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_ADD_BRICK_FAILED, returnValue.getVdsError().getMessage()); return; } }
Source:
<code>AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); <START> setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); <END> }</code><technical_language>question</technical_language>

Target:
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); }
Source:
<code>public void removeContentFromIndexByStructureInode(final String structureInode) throws DotDataException { <START> final String structureName = CacheLocator.getContentTypeCache().getStructureByInode(structureInode).getVelocityVarName(); <END> final IndiciesInfo info = APILocator.getIndiciesAPI().loadIndicies(); final List<String> idxs = new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if (info.reindex_working != null) idxs.add(info.reindex_working); if (info.reindex_live != null) idxs.add(info.reindex_live); String[] idxsArr = new String[idxs.size()]; idxsArr = idxs.toArray(idxsArr); final BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(new ESClient().getClient()) .filter(QueryBuilders.matchQuery("contenttype",structureName.toLowerCase())).source(idxsArr).get(); Logger.info(this, "Records deleted: " + response.getDeleted() + " from contentType: " + structureName); }</code><technical_language>also, this is open a NPE</technical_language>

Target:
public void removeContentFromIndexByStructureInode(final String structureInode) throws DotDataException, DotSecurityException { final ContentType contentType = APILocator.getContentTypeAPI(APILocator.getUserAPI().getSystemUser()).find(structureInode); if(contentType==null){ throw new DotDataException("ContentType with Inode or VarName: " + structureInode + "not found"); } final String structureName = contentType.variable(); final IndiciesInfo info = APILocator.getIndiciesAPI().loadIndicies(); final List<String> idxs = new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if (info.reindex_working != null) idxs.add(info.reindex_working); if (info.reindex_live != null) idxs.add(info.reindex_live); String[] idxsArr = new String[idxs.size()]; idxsArr = idxs.toArray(idxsArr); final BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(new ESClient().getClient()) .filter(QueryBuilders.matchQuery("contenttype",structureName.toLowerCase())).source(idxsArr).get(); Logger.info(this, "Records deleted: " + response.getDeleted() + " from contentType: " + structureName); }
Source:
<code>public void test_equality() { String uuid = RandomStringUtils.randomAlphanumeric(35); Date date = new Date(new Random().nextLong()); <START> assertThat(new Analysis(uuid, date)).isEqualTo(new Analysis(uuid, date)); <END> assertThat(new Analysis(uuid, date).hashCode()).isEqualTo(new Analysis(uuid, date).hashCode()); assertThat(new Analysis(uuid, date)).isNotEqualTo(null); assertThat(new Analysis(uuid, date)).isNotEqualTo(new Analysis(uuid + "1", date)); assertThat(new Analysis(uuid, date).hashCode()).isNotEqualTo(new Analysis(uuid + "1", date).hashCode()); assertThat(new Analysis(uuid, date)).isNotEqualTo(new Analysis(uuid, new Date(date.getTime() + 1_000))); assertThat(new Analysis(uuid, date).hashCode()).isNotEqualTo(new Analysis(uuid, new Date(date.getTime() + 1_000)).hashCode()); assertThat(new Analysis(uuid, date).getUuid()).isEqualTo(uuid); assertThat(new Analysis(uuid, date).getDate()).isEqualTo(date); }</code><technical_language>UT simplified putting new Analysis(uuid, date) argument of assertThat underTest variable</technical_language>

Target:
public void test_equality() { String uuid = randomAlphanumeric(35); Date date = new Date(new Random().nextLong()); Analysis underTest = new Analysis(uuid, date); assertThat(underTest).isEqualTo(underTest); assertThat(underTest.getUuid()).isEqualTo(uuid); assertThat(underTest.getDate()).isEqualTo(date); assertThat(underTest).isNotEqualTo(null); assertThat(underTest).isNotEqualTo(new Analysis(uuid + "1", date)); assertThat(underTest).isNotEqualTo(new Analysis(uuid, new Date(date.getTime() + 1_000))); }
Source:
<code>public void justTheHeaderIfNoInput() { <START> Tournament tournament = new Tournament(); <END> assertEquals("Team | MP | W | D | L | P", tournament.printTable()); }</code><technical_language>This line is repeated in tests put in a [@Before block](<LINK_0> :)</technical_language>

Target:
public void justTheHeaderIfNoInput() { assertEquals("Team | MP | W | D | L | P\n", tournament.printTable()); }
Source:
<code>public void mergeLots(final Integer userId, final Integer keepLotId, final LotsSearchDto lotsSearchDto) { <START> List<ExtendedLotDto> extendedLotDtos = this.searchLots(lotsSearchDto, null).stream() <END> .filter(extendedLotDto -> extendedLotDto.getLotId().intValue() != keepLotId.intValue()) .collect(Collectors.toList()); extendedLotDtos.stream() .forEach(extendedLotDto -> { final Transaction transaction = new Transaction(TransactionType.DEPOSIT, TransactionStatus.CONFIRMED, userId, null, keepLotId, extendedLotDto.getActualBalance()); transaction.setSourceType(TransactionSourceType.MERGED_LOT.name()); transaction.setSourceId(extendedLotDto.getLotId()); daoFactory.getTransactionDAO().save(transaction); }); List<Integer> lotIds = extendedLotDtos.stream() .map(ExtendedLotDto::getLotId).collect(Collectors.toList()); this.closeLots(userId, lotIds); }</code><technical_language>final for variables, need discuss is standard</technical_language>

Target:
public void mergeLots(final Integer userId, final Integer keepLotId, final LotsSearchDto lotsSearchDto) { final List<ExtendedLotDto> extendedLotDtos = this.searchLots(lotsSearchDto, null).stream() .filter(extendedLotDto -> extendedLotDto.getLotId().intValue() != keepLotId.intValue()) .collect(Collectors.toList()); extendedLotDtos.stream() .forEach(extendedLotDto -> { final Transaction transaction = new Transaction(TransactionType.DEPOSIT, TransactionStatus.CONFIRMED, userId, null, keepLotId, extendedLotDto.getActualBalance()); transaction.setSourceType(TransactionSourceType.MERGED_LOT.name()); transaction.setSourceId(extendedLotDto.getLotId()); daoFactory.getTransactionDAO().save(transaction); }); final List<Integer> lotIds = extendedLotDtos.stream() .map(ExtendedLotDto::getLotId).collect(Collectors.toList()); this.closeLots(userId, lotIds); }
Source:
<code>private IntegrationMimeMessage(MimeMessage source) throws MessagingException { super(source); this.source = source; if (AbstractMailReceiver.this.simpleContent) { this.content = null; } else { Object complexContent; try { complexContent = source.getContent(); } catch (IOException e) { complexContent = "Unable to extract content; see logs: " + e.getMessage(); AbstractMailReceiver.this.logger.error("Failed to extract content from " + source, e); } <START> this.content = complexContent; <END> } }</code><technical_language>do this in getContent() implementation? avoid try...catch strange content replacement advice a logs</technical_language>

Target:
private IntegrationMimeMessage(MimeMessage source) throws MessagingException { super(source); this.source = source; if (AbstractMailReceiver.this.simpleContent) { this.content = null; } else { Object complexContent; try { complexContent = source.getContent(); } catch (IOException e) { throw new MessagingException("IOException while extracting content", e); } this.content = complexContent; } }
Source:
<code>private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = path!=null && (path.isEmpty() || path.equals("accurev")); <START> if(isValidCommand && isValidPath) <END> { listener.getLogger().println( String.format( "No AccuRev tool configured, using default" ) ); } }</code><technical_language>This formatting issues</technical_language>

Target:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println("No AccuRev tool configured, using default"); } }
Source:
<code>public Set<String> getUncommittedChanges() { Set<String> uncommittedChanges = new HashSet<String>(); uncommittedChanges.addAll(diff.getAdded()); uncommittedChanges.addAll(diff.getChanged()); uncommittedChanges.addAll(diff.getRemoved()); uncommittedChanges.addAll(diff.getMissing()); <START> uncommittedChanges.addAll(diff.getMissing()); <END> uncommittedChanges.addAll(diff.getConflicting()); return uncommittedChanges; }</code><technical_language>This getModified</technical_language>

Target:
public Set<String> getUncommittedChanges() { Set<String> uncommittedChanges = new HashSet<String>(); uncommittedChanges.addAll(diff.getAdded()); uncommittedChanges.addAll(diff.getChanged()); uncommittedChanges.addAll(diff.getRemoved()); uncommittedChanges.addAll(diff.getMissing()); uncommittedChanges.addAll(diff.getModified()); uncommittedChanges.addAll(diff.getConflicting()); return uncommittedChanges; }
Source:
<code>protected void done() { List<MiniTimelineResult> results = null; if (!isCancelled()) { try { results = get(); } catch (InterruptedException | ExecutionException ex) { <START> logger.log(Level.SEVERE, "Exception while trying to get list of artifacts for Domain details for mini timeline view for domain: " + domain, ex); <END> } catch (CancellationException ignored) { } } if (results == null) { results = new ArrayList<>(); } DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.MiniTimelineResultEvent(results)); }</code><technical_language>InterruptedException treated a cancellation</technical_language>

Target:
protected void done() { List<MiniTimelineResult> results = new ArrayList<>(); if (!isCancelled()) { try { results.addAll(get()); DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.MiniTimelineResultEvent(results)); } catch (InterruptedException | ExecutionException ex) { logger.log(Level.SEVERE, "Exception while trying to get list of artifacts for Domain details for mini timeline view for domain: " + domain, ex); } catch (CancellationException ignored) { } } }
Source:
<code>public boolean reserveSeatForTicket(String groupname, int seatnumber, Long ticketId) { Ticket ticket = ticketRepository.findOne(ticketId); Seat seat = seatRespository.findBySeatGroupAndSeatNumber(groupname, seatnumber); <START> if (!seat.isTaken()) { <END> seat.setTicket(ticket); seatRespository.saveAndFlush(seat); return true; } else { return false; } }</code><technical_language>this method synchronized prevent people reserving seat in a race condition</technical_language>

Target:
public boolean reserveSeatForTicket(String groupname, int seatnumber, Long ticketId) { Ticket ticket = ticketRepository.findOne(ticketId); synchronized (seatReservationLock) { Seat seat = seatRepository.findBySeatGroupAndSeatNumber(groupname, seatnumber); if (!seat.isTaken()) { seat.setTicket(ticket); seatRepository.saveAndFlush(seat); return true; } else { return false; } } }
Source:
<code>private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { final List<Action> actions = Lists.newArrayList(); actions.add(Action.RELOAD); <START> return actions; <END> }</code><technical_language>simpler as: return Arrays.asList(Action.RELOAD);</technical_language>

Target:
private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { return Arrays.asList(Action.RELOAD); }
Source:
<code>private void checkTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { ASTResultType resultType = node.getResultType(); <START> if (nameOfMethod.contains("To") && resultType.isVoid()) { <END> addViolation(data, node); } else if (hasPrefix(nameOfMethod, "to") && resultType.isVoid()) { addViolation(data, node); } }</code><technical_language>check next char "To" is uppercase</technical_language>

Target:
private void checkTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { ASTResultType resultType = node.getResultType(); if (resultType.isVoid() && containsWord(nameOfMethod, "To")) { addViolationWithMessage(data, node, "Linguistics Antipattern - The transform method ''{0}'' should not return void linguistically", new Object[] { nameOfMethod }); } }
Source:
<code><START> public Map<String, Object> aliveness(String vhost) { <END> URI uri = UriComponentsBuilder.fromUriString(this.baseUri).pathSegment("aliveness-test", "{vhost}") .buildAndExpand(vhost).encode().toUri(); return this.restTemplate.getForObject(uri, Map.class); }</code><technical_language>/api/aliveness-test/vhost: > If is working correctly, return HTTP status 200 body: > status: ok So, this method return boolean getForEntity extract statusCode, void throws Exception if status 200 OK. Do return if is wrong</technical_language>

Target:
public Map<String, Object> aliveness(String vhost) throws HttpClientErrorException { URI uri = UriComponentsBuilder.fromUriString(this.baseUri).pathSegment("aliveness-test", "{vhost}") .buildAndExpand(vhost).encode().toUri(); return this.restTemplate.getForObject(uri, Map.class); }
Source:
<code>public SortedMap<Long, String> getPurgeFileVersionSettings() { <START> <END> if (purgeFileVersionSettings == null) { purgeFileVersionSettings = new TreeMap<Long, String>(); purgeFileVersionSettings.put(30L * 24L * 3600L, "DD"); purgeFileVersionSettings.put(3L * 24L * 3600L, "HH"); purgeFileVersionSettings.put(3600L, "MI"); } return purgeFileVersionSettings; }</code><technical_language>[TimeUnit](<LINK_0> instead of plain strings for interval definitions</technical_language>

Target:
public SortedMap<Long, TimeUnit> getPurgeFileVersionSettings() { return purgeFileVersionSettings; }
Source:
<code>public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (!cqTailer.moveToIndex(offset) && cqTailer.index() != offset) { toStart(); long startOffset = cqTailer.index(); if (offset < startOffset) { log.error("The last committed offset " + offset + " for tailer " + this + " points to a record that has been deleted by the retention policy." + " Records have been lost, continuing from the beginning of the partition offset: " + startOffset); } else { throw new IllegalStateException( <START> "Unable to move to the last committed offset" + offset + " for tailer " + this); <END> } } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }</code><technical_language>missing space "last committed offset"</technical_language>

Target:
public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (!cqTailer.moveToIndex(offset) && cqTailer.index() != offset) { toStart(); long startOffset = cqTailer.index(); if (offset < startOffset) { log.error("The last committed offset: " + offset + " for tailer: " + this + " points to a record that has been deleted by the retention policy." + " Records have been lost, continuing from the beginning of the partition offset: " + startOffset); } else { throw new IllegalStateException( "Unable to move to the last committed offset: " + offset + " for tailer: " + this); } } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }
Source:
<code>protected void resetDocks() { <START> abstractScenarioSimulationDocksHandler.getSettingsPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getCheatSheetPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getTestToolsPresenter().ifPresent(SubDockView.Presenter::reset); scenarioSimulationEditorWrapper.resetAdditionalDocks(); <END> }</code><technical_language>Is uniform this code approaches</technical_language>

Target:
protected void resetDocks() { abstractScenarioSimulationDocksHandler.resetDocks(); }
Source:
<code>protected void attemptTransition( final ExecutionContext executionContext ) throws RetryableTransitionException, FatalTransitionException { final File jobDirectory = executionContext.getJobDirectory(); <START> @NotNull final CleanupStrategy cleanupStrategy = executionContext.getCleanupStrategy(); <END> if (jobDirectory != null) { log.info("Cleaning up job directory (strategy: {})", cleanupStrategy); try { this.jobSetupService.cleanupJobDirectory( jobDirectory.toPath(), cleanupStrategy ); } catch (final IOException e) { throw new RetryableTransitionException("Failed to cleanup job directory", e); } } }</code><technical_language>FYI I putting method contents effect is proxy intercept evaluate them</technical_language>

Target:
protected void attemptTransition( final ExecutionContext executionContext ) throws RetryableTransitionException, FatalTransitionException { final File jobDirectory = executionContext.getJobDirectory(); final CleanupStrategy cleanupStrategy = executionContext.getCleanupStrategy(); if (jobDirectory != null) { log.info("Cleaning up job directory (strategy: {})", cleanupStrategy); try { this.jobSetupService.cleanupJobDirectory( jobDirectory.toPath(), cleanupStrategy ); } catch (final IOException e) { throw new RetryableTransitionException("Failed to cleanup job directory", e); } } }
Source:
<code>public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); long currentTotalMemory = currentUserMemory + currentSystemMemory; long deltaUserMemoryInBytes = currentUserMemory - previousUserMemory; long deltaTotalMemoryInBytes = currentTotalMemory - (previousUserMemory + previousSystemMemory); previousUserMemory = currentUserMemory; previousSystemMemory = currentSystemMemory; stateMachine.updateMemoryUsage(deltaUserMemoryInBytes, deltaTotalMemoryInBytes, currentUserMemory, currentTotalMemory); if (state == PLANNED && newStatus.getState() == RUNNING) { int runningTasks = stateMachine.getCurrentRunningTasks().incrementAndGet(); stateMachine.getPeakRunningTasks().accumulateAndGet(runningTasks, Math::max); } else if (!state.isDone() && newStatus.getState().isDone()) { <START> stateMachine.getCurrentRunningTasks().decrementAndGet(); <END> } state = newStatus.getState(); }</code><technical_language>this negative some state transitions PLANNED other RUNNING</technical_language>

Target:
public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); long currentTotalMemory = currentUserMemory + currentSystemMemory; long deltaUserMemoryInBytes = currentUserMemory - previousUserMemory; long deltaTotalMemoryInBytes = currentTotalMemory - (previousUserMemory + previousSystemMemory); previousUserMemory = currentUserMemory; previousSystemMemory = currentSystemMemory; stateMachine.updateMemoryUsage(deltaUserMemoryInBytes, deltaTotalMemoryInBytes, currentUserMemory, currentTotalMemory); if (state == PLANNED && newStatus.getState() == RUNNING) { stateMachine.incrementCurrentRunningTaskCount(); } else if (state == RUNNING && newStatus.getState().isDone()) { stateMachine.decrementCurrentRunningTaskCount(); } state = newStatus.getState(); }
Source:
<code>private Map<String, List<String>> getTableToBrokersMap() { int controllerIdx = RANDOM.nextInt(controllerUrls.length); for (int i = 0; i < controllerFetchRetries; i++) { try { String brokerTableQueryResp = IOUtils.toString( new URL(String.format(CONTROLLER_ONLINE_TABLE_BROKERS_MAP_URL_TEMPLATE, controllerUrls[controllerIdx]))); Map<String, List<String>> tablesToBrokersMap = OBJECT_MAPPER.readValue(brokerTableQueryResp, Map.class); for (String table : tablesToBrokersMap.keySet()) { List<String> brokerHostPorts = new ArrayList<>(); for (String broker : tablesToBrokersMap.get(table)) { <START> brokerHostPorts.add(broker.replace("Broker_", "").replace("_", ":")); <END> } tablesToBrokersMap.put(table, brokerHostPorts); } return tablesToBrokersMap; } catch (Exception e) { LOGGER.warn(String.format("Unable to fetch controller broker information from '%s', retry in %d millseconds", controllerUrls[controllerIdx], this.controllerFetchRetriesIntervalMills), e); controllerIdx = (controllerIdx + 1) % controllerUrls.length; try { Thread.sleep(controllerFetchRetriesIntervalMills); } catch (InterruptedException interruptedException) { } } } LOGGER.warn( String.format("Failed to fetch controller broker information with %d retries", this.controllerFetchRetries)); return null; }</code><technical_language>wrap this string manipulation a utility function standardized/reusable code base? if controller side api is new (ie incompatibility issue), api return a response in format require this string massaging</technical_language>

Target:
private Map<String, List<String>> getTableToBrokersMap() { int controllerIdx = RANDOM.nextInt(_controllerUrls.length); for (int i = 0; i < _controllerFetchRetries; i++) { try { String brokerTableQueryResp = IOUtils.toString( new URL(String.format(CONTROLLER_ONLINE_TABLE_BROKERS_MAP_URL_TEMPLATE, _controllerUrls[controllerIdx]))); Map<String, List<String>> tablesToBrokersMap = OBJECT_MAPPER.readValue(brokerTableQueryResp, Map.class); for (String table : tablesToBrokersMap.keySet()) { List<String> brokerHostPorts = new ArrayList<>(); for (String broker : tablesToBrokersMap.get(table)) { brokerHostPorts.add(Utils.generateBrokerHostPort(broker)); } tablesToBrokersMap.put(table, brokerHostPorts); } return tablesToBrokersMap; } catch (Exception e) { LOGGER.warn("Unable to fetch controller broker information from '{}', retry in millseconds", _controllerUrls[controllerIdx], _controllerFetchRetriesIntervalMills, e); controllerIdx = (controllerIdx + 1) % _controllerUrls.length; try { Thread.sleep(_controllerFetchRetriesIntervalMills); } catch (InterruptedException interruptedException) { } } } LOGGER.warn("Failed to fetch controller broker information with retries", _controllerFetchRetries); return null; }
Source:
<code>public void doUserCancel_chargeStatusDuringAuthorisation_needsCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); WorldpayCancelResponse worldpayResponse = mock(WorldpayCancelResponse.class); when(worldpayResponse.cancelStatus()).thenReturn(BaseCancelResponse.CancelStatus.CANCELLED); GatewayResponse.GatewayResponseBuilder<WorldpayCancelResponse> gatewayResponseBuilder = responseBuilder(); GatewayResponse cancelResponse = gatewayResponseBuilder.withResponse(worldpayResponse).build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(true); when(mockChargeDao.findByExternalId(externalChargeId)).thenReturn(Optional.of(chargeEntity)); when(mockPaymentProviders.byName(chargeEntity.getPaymentGatewayName())).thenReturn(mockPaymentProvider); when(mockPaymentProvider.cancel(argThat(aCancelGatewayRequestMatching(chargeEntity)))).thenReturn(cancelResponse); chargeCancelService.doUserCancel(externalChargeId); verify(mockPaymentProvider).cancel(argThat(aCancelGatewayRequestMatching(chargeEntity))); verify(chargeService).transitionChargeState(externalChargeId, USER_CANCELLED); <START> verifyNoMoreInteractions(ignoreStubs(mockChargeDao)); <END> }</code><technical_language>purpose for verifying interactions mockChargeDao</technical_language>

Target:
public void doUserCancel_chargeStatusDuringAuthorisation_needsCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); WorldpayCancelResponse worldpayResponse = new WorldpayCancelResponse(); GatewayResponse.GatewayResponseBuilder<WorldpayCancelResponse> gatewayResponseBuilder = responseBuilder(); GatewayResponse cancelResponse = gatewayResponseBuilder.withResponse(worldpayResponse).build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(true); when(mockChargeDao.findByExternalId(externalChargeId)).thenReturn(Optional.of(chargeEntity)); when(mockPaymentProviders.byName(chargeEntity.getPaymentGatewayName())).thenReturn(mockPaymentProvider); when(mockPaymentProvider.cancel(argThat(aCancelGatewayRequestMatching(chargeEntity)))).thenReturn(cancelResponse); chargeCancelService.doUserCancel(externalChargeId); verify(mockPaymentProvider).cancel(argThat(aCancelGatewayRequestMatching(chargeEntity))); verify(chargeService).transitionChargeState(externalChargeId, USER_CANCELLED); }
Source:
<code>public Response generateDescriptor() { String consoleString = HexUtils.hex2string(consoleId); GraphicsConsole console = new GraphicsConsole(); console.setProtocol(consoleString); validateEnums(GraphicsConsole.class, console); GraphicsType type = GraphicsType.valueOf(consoleString); org.ovirt.engine.core.common.businessentities.GraphicsType graphicsType = getMappingLocator().getMapper(GraphicsType.class, org.ovirt.engine.core.common.businessentities.GraphicsType.class).map(type, null); ConsoleOptions consoleOptions = new ConsoleOptions(graphicsType); consoleOptions.setVmId(vmGuid); ConfigureConsoleOptionsParams queryParams = new ConfigureConsoleOptionsParams(consoleOptions, true); try { URI baseUri = getUriInfo().getBaseUri(); URL engineBaseUrl = new URL(baseUri.getScheme(), baseUri.getHost(), baseUri.getPort(), ""); queryParams.setEngineBaseUrl(engineBaseUrl.toString()); } catch (MalformedURLException e) { } <START> queryParams.setConsoleClientResourcesUrl(BrandingManager.getInstance().getMessage("obrand.common.console_client_resources_url")); <END> ConsoleOptions configuredOptions = runQuery(VdcQueryType.ConfigureConsoleOptions, queryParams).getReturnValue(); String descriptor = runQuery(VdcQueryType.GetConsoleDescriptorFile, new ConsoleOptionsParams(configuredOptions)) .getReturnValue(); Response.ResponseBuilder builder = Response.ok(descriptor.getBytes(Charset.forName("UTF-8")), ApiMediaType.APPLICATION_X_VIRT_VIEWER); return builder.build(); }</code><technical_language>correct assume RESTAPI URL calculate URL of other resources. This logic part of backend, ENGINE_FQDN, ENGINE_URI ENGINE_PROXY_HTTPS_PORT properties</technical_language>

Target:
public Response generateDescriptor() { String consoleString = HexUtils.hex2string(consoleId); GraphicsConsole console = new GraphicsConsole(); console.setProtocol(consoleString); validateEnums(GraphicsConsole.class, console); GraphicsType type = GraphicsType.valueOf(consoleString); org.ovirt.engine.core.common.businessentities.GraphicsType graphicsType = getMappingLocator().getMapper(GraphicsType.class, org.ovirt.engine.core.common.businessentities.GraphicsType.class).map(type, null); ConsoleOptions consoleOptions = new ConsoleOptions(graphicsType); consoleOptions.setVmId(vmGuid); ConfigureConsoleOptionsParams queryParams = new ConfigureConsoleOptionsParams(consoleOptions, true); queryParams.setConsoleClientResourcesUrl(BrandingManager.getInstance().getMessage("obrand.common.console_client_resources_url")); ConsoleOptions configuredOptions = runQuery(VdcQueryType.ConfigureConsoleOptions, queryParams).getReturnValue(); String descriptor = runQuery(VdcQueryType.GetConsoleDescriptorFile, new ConsoleOptionsParams(configuredOptions)) .getReturnValue(); Response.ResponseBuilder builder = Response.ok(descriptor.getBytes(Charset.forName("UTF-8")), ApiMediaType.APPLICATION_X_VIRT_VIEWER); return builder.build(); }
Source:
<code>public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", error.getUrl()); obj.put("code", 0); obj.put("sslerror", error.getPrimaryError()); String message; switch (error.getPrimaryError()) { case SslError.SSL_DATE_INVALID: message = "The date of the certificate is invalid"; break; case SslError.SSL_EXPIRED: message = "The certificate has expired"; break; case SslError.SSL_IDMISMATCH: message = "Hostname mismatch"; break; default: case SslError.SSL_INVALID: message = "A generic error occurred"; break; <START> case SslError.SSL_MAX_ERROR: <END> message = "<SSL_MAX_ERROR>"; break; case SslError.SSL_NOTYETVALID: message = "The certificate is not yet valid"; break; case SslError.SSL_UNTRUSTED: message = "The certificate authority is not trusted"; break; } obj.put("message", message); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } handler.cancel(); }</code><technical_language>I if remove one: <LINK_0></technical_language>

Target:
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); try { JSONObject obj = new JSONObject(); obj.put("type", LOAD_ERROR_EVENT); obj.put("url", error.getUrl()); obj.put("code", 0); obj.put("sslerror", error.getPrimaryError()); String message; switch (error.getPrimaryError()) { case SslError.SSL_DATE_INVALID: message = "The date of the certificate is invalid"; break; case SslError.SSL_EXPIRED: message = "The certificate has expired"; break; case SslError.SSL_IDMISMATCH: message = "Hostname mismatch"; break; default: case SslError.SSL_INVALID: message = "A generic error occurred"; break; case SslError.SSL_NOTYETVALID: message = "The certificate is not yet valid"; break; case SslError.SSL_UNTRUSTED: message = "The certificate authority is not trusted"; break; } obj.put("message", message); sendUpdate(obj, true, PluginResult.Status.ERROR); } catch (JSONException ex) { LOG.d(LOG_TAG, "Should never happen"); } handler.cancel(); }