auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isUsersWithRetirementTeacherSituations(GiafProfessionalData giafProfessionalData, Set<ContractSituation> retirementSituations, LocalDate today) { Set<PersonContractSituation> personContractSituations = new HashSet<PersonContractSituation>(); for (PersonContractSituation personContractSituation : giafProfessionalData.getPersonContractSituationsSet()) { if (personContractSituation.isValid() && personContractSituation.getAnulationDate() == null && personContractSituation.isActive(today) && (personContractSituation.getProfessionalCategory() != null && personContractSituation.getProfessionalCategory().getCategoryType().equals(CategoryType.TEACHER)) && retirementSituations.contains(personContractSituation.getContractSituation())) { return true; } } return false; }

Target:
public boolean isUsersWithRetirementTeacherSituations(GiafProfessionalData giafProfessionalData, Set<ContractSituation> retirementSituations, LocalDate today) { for (PersonContractSituation personContractSituation : giafProfessionalData.getPersonContractSituationsSet()) { if (personContractSituation.isValid() && personContractSituation.getAnulationDate() == null && personContractSituation.isActive(today) && (personContractSituation.getProfessionalCategory() != null && personContractSituation.getProfessionalCategory().getCategoryType().equals(CategoryType.TEACHER)) && retirementSituations.contains(personContractSituation.getContractSituation())) { return true; } } return false; }
Source:
private void deleteQualityGates(DbSession dbSession, OrganizationDto organization) { Collection<QualityGateDto> qualityGates = dbClient.qualityGateDao().selectAll(dbSession, organization); dbClient.qualityGateDao().deleteByUuids(dbSession, qualityGates.stream().map(QualityGateDto::getUuid).collect(MoreCollectors.toList())); }

Target:
private void deleteQualityGates(DbSession dbSession, OrganizationDto organization) { Collection<QualityGateDto> qualityGates = dbClient.qualityGateDao().selectAll(dbSession, organization); dbClient.qualityGateDao().deleteByUuids(dbSession, qualityGates.stream() .filter(q -> !q.isBuiltIn()) .map(QualityGateDto::getUuid) .collect(MoreCollectors.toList())); }
Source:
public void testItTimesOutProperly() throws Exception { String validationQuery = "select 1"; Jdbi jdbi = mock(Jdbi.class); Handle handle = mock(Handle.class); when(jdbi.open()).thenReturn(handle); when(jdbi.withHandle(Mockito.any())).thenCallRealMethod(); Mockito.doAnswer(invocation -> { try { TimeUnit.SECONDS.sleep(10); } catch (Exception ignored) { } return null; }).when(handle).execute(validationQuery); ExecutorService executorService = Executors.newSingleThreadExecutor(); JdbiHealthCheck jdbiHealthCheck = new JdbiHealthCheck(executorService, Duration.milliseconds(5), jdbi, validationQuery); HealthCheck.Result result = jdbiHealthCheck.check(); executorService.shutdown(); assertThat("is unhealthy", false, is(result.isHealthy())); }

Target:
public void testItTimesOutProperly() throws Exception { when(handle.execute(VALIDATION_QUERY)).thenAnswer((Answer<Integer>) invocation -> { TimeUnit.SECONDS.sleep(10); return null; }); HealthCheck.Result result = sut.check(); assertThat(result.isHealthy()).isFalse(); }
Source:
EnergyChannel(EnergyNetwork network, int channel) { this.network = network; this.channel = channel; }

Target:
public EnergyChannel(EnergyNetwork network, int channel) { this.network = network; this.channel = channel; }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(EXCEPT_CLAUSE, ctx -> { Expression exception = ((ExceptClause) ctx.syntaxNode()).exception(); if (exception == null) { return; } TreeUtils.flattenTuples(exception).forEach(expression -> { if (NON_COMPLIANT_TYPES.stream().anyMatch(type -> expression.type().canOnlyBe(type))) { ctx.addIssue(expression, MESSAGE); } if ((expression instanceof HasSymbol) && !inheritsFromBaseException(((HasSymbol) expression).symbol())) { ctx.addIssue(expression, MESSAGE); } }); }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(EXCEPT_CLAUSE, ctx -> { Expression exception = ((ExceptClause) ctx.syntaxNode()).exception(); if (exception == null) { return; } TreeUtils.flattenTuples(exception).forEach(expression -> { if (!canBeOrExtendBaseException(expression.type()) || ((expression instanceof HasSymbol) && !inheritsFromBaseException(((HasSymbol) expression).symbol()))) { ctx.addIssue(expression, MESSAGE); } }); }); }
Source:
private TrafficType getNetworkTrafficType(Network network) { final VpcGatewayVO gateway = _vpcGatewayDao.getVpcGatewayByNetworkId(network.getId()); if (gateway != null) { s_logger.debug("network " + network.getId() + " is a vpc private gateway, set traffic type to Public"); return TrafficType.Public; } else { return network.getTrafficType(); } }

Target:
private TrafficType getNetworkTrafficType(Network network) { final VpcGatewayVO gateway = _vpcGatewayDao.getVpcGatewayByNetworkId(network.getId()); if (gateway != null) { s_logger.debug("network " + network.getId() + " (name: " + network.getName() + " ) is a vpc private gateway, set traffic type to Public"); return TrafficType.Public; } else { return network.getTrafficType(); } }
Source:
public InheritedRefRight(){ }

Target:
protected InheritedRefRight(){ }
Source:
protected String getRemoveDiskProfileFullMsg(DiskProfile profile) { return ConstantsManager.getInstance() .getMessages() .diskProfileFromStorageDomain(profile.getName(), profile.getStorageDomainId().toString()); }

Target:
protected String getRemoveDiskProfileFullMsg(DiskProfile profile) { StorageDomain entity = (StorageDomain) sourceListModel.getEntity(); return ConstantsManager.getInstance() .getMessages() .diskProfileFromStorageDomain(profile.getName(), entity.getName()); }
Source:
private String computeString() { final StringBuilder buf = new StringBuilder("window("); final int i = buf.length(); if (!keys.isEmpty()) { buf.append("partition "); buf.append(keys); } if (!orderKeys.getFieldCollations().isEmpty()) { buf.append(buf.length() == i ? "order by " : " order by "); buf.append(orderKeys); } if (orderKeys.getFieldCollations().isEmpty() && lowerBound.isUnbounded() && lowerBound.isPreceding() && upperBound.isUnbounded() && upperBound.isFollowing()) { } else if (!orderKeys.getFieldCollations().isEmpty() && lowerBound.isUnbounded() && lowerBound.isPreceding() && upperBound.isCurrentRow()) { } else { buf.append(isRows ? " rows " : " range "); buf.append("between "); buf.append(lowerBound); buf.append(" and "); buf.append(upperBound); } if (!aggCalls.isEmpty()) { buf.append(buf.length() == i ? "aggs " : " aggs "); buf.append(aggCalls); } buf.append(")"); return buf.toString(); }

Target:
private String computeString() { final StringBuilder buf = new StringBuilder("window("); final int i = buf.length(); if (!keys.isEmpty()) { buf.append("partition "); buf.append(keys); } if (!orderKeys.getFieldCollations().isEmpty()) { buf.append(buf.length() == i ? "order by " : " order by "); buf.append(orderKeys); } if (orderKeys.getFieldCollations().isEmpty() && lowerBound.isUnbounded() && lowerBound.isPreceding() && upperBound.isUnbounded() && upperBound.isFollowing()) { } else if (!orderKeys.getFieldCollations().isEmpty() && lowerBound.isUnbounded() && lowerBound.isPreceding() && upperBound.isCurrentRow() && !isRows) { } else { buf.append(isRows ? " rows " : " range "); buf.append("between "); buf.append(lowerBound); buf.append(" and "); buf.append(upperBound); } if (!aggCalls.isEmpty()) { buf.append(buf.length() == i ? "aggs " : " aggs "); buf.append(aggCalls); } buf.append(")"); return buf.toString(); }
Source:
public void setHealth(int h){ Health = h; }

Target:
public void setHealth(int h){ health = h; }
Source:
private void invalidateAllIfStale(CachingContext context) { final Duration elapsed = new Duration(lastSync, DateTime.now()); if (elapsed.isLongerThan(period)) { lastSync = DateTime.now(); if (context.checkIfAnyStale()) { context.invalidateAll(true); } } }

Target:
private void invalidateAllIfStale(CachingContext context) { if (!lock.compareAndSet(false, true)) { return; } try { final Duration elapsed = new Duration(lastSync, DateTime.now()); if (!elapsed.isLongerThan(period)) { return; } lastSync = DateTime.now(); } finally { lock.set(false); } if (context.checkIfAnyStale()) { context.invalidateAll(true); } }
Source:
public CreateUserSessionParameters(String ssoToken, String profileName, String principalName, String principalId, String email, String sourceIp, List<Map> groupIds, boolean adminRequired) { setSsoToken(ssoToken); setProfileName(profileName); setPrincipalName(principalName); setPrincipalId(principalId); setEmail(email); setSourceIp("fe80::56ee:75ff:fe5c:6cc7"); setGroupIds(groupIds); setAdminRequired(adminRequired); }

Target:
public CreateUserSessionParameters(String ssoToken, String profileName, String principalName, String principalId, String email, String sourceIp, List<Map> groupIds, boolean adminRequired) { setSsoToken(ssoToken); setProfileName(profileName); setPrincipalName(principalName); setPrincipalId(principalId); setEmail(email); setSourceIp(sourceIp); setGroupIds(groupIds); setAdminRequired(adminRequired); }
Source:
private void update(String key, int value) { mWorkDatabase.beginTransaction(); try { mWorkDatabase.preferenceDao().insertPreference(new Preference(key, value)); mWorkDatabase.setTransactionSuccessful(); } finally { mWorkDatabase.endTransaction(); } }

Target:
private void update(String key, int value) { mWorkDatabase.preferenceDao().insertPreference(new Preference(key, value)); }
Source:
public void setEscapeProcessing(boolean enable) throws SQLException { throw new SQLFeatureNotSupportedException("setEscapeProcessing not supported"); }

Target:
public void setEscapeProcessing(boolean enable) throws SQLException { System.err.println("setEscapeProcessing() is not supported yet."); }
Source:
public String getStartDefaultVMArgs() { String suffix = ""; try { IJBossServerRuntime jbossRuntime = RuntimeUtils.checkedGetJBossServerRuntime(getRuntime()); IVMInstall vmInstall = jbossRuntime.getVM(); int[] versionIDs = JavaUtilities.getMajorMinor(JavaUtilities.getJavaVersionVMInstall(vmInstall)); if (versionIDs.length > 0 && versionIDs[0] >= 9) { suffix = " --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED --add-exports=jdk.unsupported/sun.reflect=ALL-UNNAMED --add-modules=java.se"; } } catch (CoreException e) { throw new RuntimeException(e); } return super.getStartDefaultVMArgs() + suffix; }

Target:
public String getStartDefaultVMArgs() { return super.getStartDefaultVMArgs() + getJava9VMArgs(); }
Source:
public void refreshOverrides() throws Exception { Environment environment = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/foo/development/", Environment.class); assertThat(environment.getPropertySources()).isEmpty(); String actuatorEndpoint = "http://localhost:" + this.port + "/actuator"; HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); HttpEntity<String> request = new HttpEntity<>( "{\"name\": \"spring.cloud.config.server.overrides.foo\", \"value\": \"bar\"}", headers); ResponseEntity<Void> response = new TestRestTemplate() .postForEntity(actuatorEndpoint + "/env", request, Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); response = new TestRestTemplate().postForEntity(actuatorEndpoint + "/refresh", null, Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); environment = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/foo/development/", Environment.class); assertThat(environment.getPropertySources()).isNotEmpty(); assertThat(environment.getPropertySources().get(0).getSource().get("foo")) .isEqualTo("bar"); }

Target:
public void refreshOverrides() { Environment environment = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/foo/development/", Environment.class); assertThat(environment.getPropertySources()).isEmpty(); String actuatorEndpoint = "http://localhost:" + this.port + "/actuator"; HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); HttpEntity<String> request = new HttpEntity<>( "{\"name\": \"spring.cloud.config.server.overrides.foo\", \"value\": \"bar\"}", headers); ResponseEntity<Void> response = new TestRestTemplate() .postForEntity(actuatorEndpoint + "/env", request, Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); response = new TestRestTemplate().postForEntity(actuatorEndpoint + "/refresh", null, Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); environment = new TestRestTemplate().getForObject( "http://localhost:" + this.port + "/foo/development/", Environment.class); assertThat(environment.getPropertySources()).isNotEmpty(); assertThat(environment.getPropertySources().get(0).getSource().get("foo")) .isEqualTo("bar"); }
Source:
public static String adaptInstrumentName(CurrencyPair pair, Object[] args) { String instrumentPostfix; try { instrumentPostfix = args[0].toString(); } catch (Throwable t) { throw new ExchangeException( "You need to provide a postfix for the instrument name in the first parameter of the array, ie: PERPETUAL, 28JUN19..."); } return pair.base.getSymbol() + "-" + instrumentPostfix; }

Target:
public static String adaptInstrumentName(CurrencyPair pair, Object[] args) { if (args == null || args.length == 0) { throw new ExchangeException( "You need to provide a postfix for the instrument name in the first parameter of the array, ie: PERPETUAL, 28JUN19..."); } String instrumentPostfix = args[0].toString(); return pair.base.getSymbol() + "-" + instrumentPostfix; }
Source:
public void writeReport(final File output) { writeReport(output, new ArrayList<>()); }

Target:
public void writeReport(final File output) { writeReport(output, Collections.EMPTY_LIST); }
Source:
public synchronized void sendMessageSync(String destAddress, String message, boolean command) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException, IllegalStateException { if (getSession() != null && getSession().isBound()) { SubmitSm submit = new SubmitSm(); byte[] textBytes; if (command) { textBytes = CharsetUtil.encode(message, commandsCharsetName); submit.setDataCoding(commandsDataCoding); } else { textBytes = CharsetUtil.encode(message, notificationsCharsetName); submit.setDataCoding(notificationsDataCoding); } submit.setShortMessage(textBytes); submit.setSourceAddress(new Address(sourceTon, sourceNpi, sourceAddress)); submit.setDestAddress(new Address(destTon, destNpi, destAddress)); SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout); if (submitResponce.getCommandStatus() == SmppConstants.STATUS_OK) { Log.debug("SMS submited, msg_id: " + submitResponce.getMessageId()); } else { throw new IllegalStateException(submitResponce.getResultMessage()); } } else { throw new SmppChannelException("Smpp session is not connected"); } }

Target:
public synchronized void sendMessageSync(String destAddress, String message, boolean command) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException, IllegalStateException { if (getSession() != null && getSession().isBound()) { SubmitSm submit = new SubmitSm(); byte[] textBytes; textBytes = CharsetUtil.encode(message, command ? commandsCharsetName : notificationsCharsetName); submit.setDataCoding(command ? commandsDataCoding : notificationsDataCoding); submit.setShortMessage(textBytes); submit.setSourceAddress(new Address(sourceTon, sourceNpi, sourceAddress)); submit.setDestAddress(new Address(destTon, destNpi, destAddress)); SubmitSmResp submitResponce = getSession().submit(submit, submitTimeout); if (submitResponce.getCommandStatus() == SmppConstants.STATUS_OK) { Log.debug("SMS submitted, message id: " + submitResponce.getMessageId()); } else { throw new IllegalStateException(submitResponce.getResultMessage()); } } else { throw new SmppChannelException("SMPP session is not connected"); } }
Source:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Invocation.Builder requestBuilder = Context.getClient().target(URL).request(); requestBuilder = requestBuilder.header(KEY_AUTHORIZATION, token); Response response = requestBuilder.post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); Log.error(output); } }

Target:
public void sendMessageSync(String destAddress, String message, boolean command) throws InterruptedException, MessageException { Response response = getRequestBuilder().post(Entity.json(preparePayload(destAddress, message))); if (!response.getStatusInfo().equals(Response.Status.OK)) { String output = response.readEntity(String.class); throw new MessageException(output); } }
Source:
public static void main(String[] args) throws InterruptedException { Microservices ms1 = Microservices.builder() .discovery( (serviceRegistry, serviceEndpoint) -> new ScalecubeServiceDiscovery(serviceRegistry, serviceEndpoint).start()) .defaultErrorMapper(new ServiceAProviderErrorMapper()) .services( ServiceInfo.fromServiceInstance(new ServiceAImpl()) .errorMapper(new ServiceAProviderErrorMapper()) .build()) .startAwait(); System.err.println("ms1 started: " + ms1.serviceAddress()); Microservices ms2 = Microservices.builder() .discovery( (serviceRegistry, serviceEndpoint) -> serviceDiscovery(serviceRegistry, serviceEndpoint, ms1)) .services( call -> { ServiceA serviceA = call.errorMapper( new ServiceAClientErrorMapper()) .create() .api(ServiceA.class); ServiceB serviceB = new ServiceBImpl(serviceA); return Collections.singleton(ServiceInfo.fromServiceInstance(serviceB).build()); }) .startAwait(); System.err.println("ms2 started: " + ms2.serviceAddress()); ms2.call() .create() .api(ServiceB.class) .doAnotherStuff(0) .subscribe( System.out::println, th -> System.err.println( "No service client mapper is defined for ServiceB, " + "so default scalecube mapper is used! -> " + th), () -> System.out.println("Completed!")); Thread.currentThread().join(); }

Target:
public static void main(String[] args) throws InterruptedException { Microservices ms1 = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .defaultErrorMapper(new ServiceAProviderErrorMapper()) .services( ServiceInfo.fromServiceInstance(new ServiceAImpl()) .errorMapper(new ServiceAProviderErrorMapper()) .build()) .startAwait(); System.err.println("ms1 started: " + ms1.serviceAddress()); Microservices ms2 = Microservices.builder() .discovery( (serviceRegistry, serviceEndpoint) -> serviceDiscovery(serviceRegistry, serviceEndpoint, ms1)) .services( call -> { ServiceA serviceA = call.errorMapper( new ServiceAClientErrorMapper()) .create() .api(ServiceA.class); ServiceB serviceB = new ServiceBImpl(serviceA); return Collections.singleton(ServiceInfo.fromServiceInstance(serviceB).build()); }) .startAwait(); System.err.println("ms2 started: " + ms2.serviceAddress()); ms2.call() .create() .api(ServiceB.class) .doAnotherStuff(0) .subscribe( System.out::println, th -> System.err.println( "No service client mapper is defined for ServiceB, " + "so default scalecube mapper is used! -> " + th), () -> System.out.println("Completed!")); Thread.currentThread().join(); }
Source:
private static void whoAmI(boolean canLogOut) { AccountInfo account = getUserAccountInfo(); final UserPopupPanel userPopup = new UserPopupPanel(account, canLogOut, true); final FlowPanel userSummaryPanel = new FlowPanel(); class PopupHandler implements KeyDownHandler, ClickHandler { private void showHidePopup() { if (userPopup.isShowing() && userPopup.isVisible()) { userPopup.hide(); } else { userPopup.showRelativeTo(userSummaryPanel); } } @Override public void onClick(ClickEvent event) { showHidePopup(); } @Override public void onKeyDown(KeyDownEvent event) { if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { showHidePopup(); event.preventDefault(); } } } final PopupHandler popupHandler = new PopupHandler(); final InlineLabel l = new InlineLabel(FormatUtil.name(account)); l.setStyleName(RESOURCES.css().menuBarUserName()); final AvatarImage avatar = new AvatarImage(account, 26, false); avatar.setStyleName(RESOURCES.css().menuBarUserNameAvatar()); userSummaryPanel.setStyleName(RESOURCES.css().menuBarUserNamePanel()); userSummaryPanel.add(l); userSummaryPanel.add(avatar); String arrow = Character.toString((char)0x25be); userSummaryPanel.add(new InlineLabel(" " + arrow)); userPopup.addAutoHidePartner(userSummaryPanel.getElement()); FocusPanel fp = new FocusPanel(userSummaryPanel); fp.setStyleName(RESOURCES.css().menuBarUserNameFocusPanel()); fp.addKeyDownHandler(popupHandler); fp.addClickHandler(popupHandler); menuRight.add(fp); }

Target:
private static void whoAmI(boolean canLogOut) { AccountInfo account = getUserAccountInfo(); final UserPopupPanel userPopup = new UserPopupPanel(account, canLogOut, true); final FlowPanel userSummaryPanel = new FlowPanel(); class PopupHandler implements KeyDownHandler, ClickHandler { private void showHidePopup() { if (userPopup.isShowing() && userPopup.isVisible()) { userPopup.hide(); } else { userPopup.showRelativeTo(userSummaryPanel); } } @Override public void onClick(ClickEvent event) { showHidePopup(); } @Override public void onKeyDown(KeyDownEvent event) { if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { showHidePopup(); event.preventDefault(); } } } final PopupHandler popupHandler = new PopupHandler(); final InlineLabel l = new InlineLabel(FormatUtil.name(account)); l.setStyleName(RESOURCES.css().menuBarUserName()); final AvatarImage avatar = new AvatarImage(account, 26, false); avatar.setStyleName(RESOURCES.css().menuBarUserNameAvatar()); userSummaryPanel.setStyleName(RESOURCES.css().menuBarUserNamePanel()); userSummaryPanel.add(l); userSummaryPanel.add(avatar); userSummaryPanel.add(new InlineLabel(" \u25be")); userPopup.addAutoHidePartner(userSummaryPanel.getElement()); FocusPanel fp = new FocusPanel(userSummaryPanel); fp.setStyleName(RESOURCES.css().menuBarUserNameFocusPanel()); fp.addKeyDownHandler(popupHandler); fp.addClickHandler(popupHandler); menuRight.add(fp); }
Source:
private UnityEntity connectAndGetValidEntityByGroup(int entityId, String groupName) throws InternalErrorException, IOException { HttpURLConnection connection = createConnection(checkUri(uriEntity) + entityId + "/groups/"); JSONArray groups = getJSONArrayFromRemote(connection); if (groups != null && compareGroupName(groups, groupName)) { JSONObject entity = getEntityFromRemote(entityId); if (entity != null) return parseValidUnityEntity(entity); } return null; }

Target:
private UnityEntity connectAndGetValidEntityByGroup(int entityId, String groupName) throws InternalErrorException, IOException { HttpURLConnection connection = createConnection(checkUri(uriEntity) + entityId + "/groups/"); JSONArray groups = getJSONArrayFromRemote(connection); if (groups != null && compareGroupName(groups, groupName)) { JSONObject entity = getEntityFromRemote(entityId); if (entity == null) throw new InternalErrorException("Entity returned for entityId " + entityId + " was null."); return parseValidUnityEntity(entity); } return null; }
Source:
public String getUrl(String baseUrl, String path) throws MalformedURLException { if (baseUrl.indexOf("://") > 0) { return new URL(new URL(baseUrl), path).toExternalForm(); } else { return baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (path.startsWith("/") ? path.substring(1) : path); } }

Target:
private static String getUrl(String baseUrl, String path) throws MalformedURLException { return new URL(new URL(baseUrl), path).toExternalForm(); }
Source:
private static OGCGeometry readGeometry(BasicSliceInput input, Slice inputSlice, GeometryType type, int length) { switch (type) { case POINT: return readPoint(input); case MULTI_POINT: case LINE_STRING: case MULTI_LINE_STRING: case POLYGON: case MULTI_POLYGON: return readSimpleGeometry(input, inputSlice, type, length); case GEOMETRY_COLLECTION: return readGeometryCollection(input, inputSlice); case ENVELOPE: return OGCGeometry.createFromEsriGeometry(readEnvelope(input), null); default: throw new IllegalArgumentException("Unexpected type: " + type); } }

Target:
private static OGCGeometry readGeometry(BasicSliceInput input, Slice inputSlice, GeometryType type, int length) { switch (type) { case POINT: return readPoint(input); case MULTI_POINT: case LINE_STRING: case MULTI_LINE_STRING: case POLYGON: case MULTI_POLYGON: return readSimpleGeometry(input, inputSlice, type, length); case GEOMETRY_COLLECTION: return readGeometryCollection(input, inputSlice); case ENVELOPE: return createFromEsriGeometry(readEnvelope(input), false); default: throw new IllegalArgumentException("Unexpected type: " + type); } }
Source:
private int scan( KijiTableReader reader, KijiDataRequest request, EntityId startRow, EntityId limitRow, Map<FamilyLayout, List<String>> mapTypeFamilies, Map<FamilyLayout, List<ColumnLayout>> groupTypeColumns) throws IOException { getPrintStream().println("Scanning kiji table: " + mURI); KijiScannerOptions scannerOptions = new KijiScannerOptions() .setStartRow(startRow) .setStopRow(limitRow); KijiRowScanner scanner = reader.getScanner(request, scannerOptions); try { int rowsOutput = 0; for (KijiRowData row : scanner) { if (mMaxRows != 0 && ++rowsOutput > mMaxRows) { break; } ToolUtils.printRow(row, mapTypeFamilies, groupTypeColumns, getPrintStream()); } } finally { ResourceUtils.closeOrLog(scanner); } return 0; }

Target:
private int scan( KijiTableReader reader, KijiDataRequest request, EntityId startRow, EntityId limitRow, Map<FamilyLayout, List<String>> mapTypeFamilies, Map<FamilyLayout, List<ColumnLayout>> groupTypeColumns) throws IOException { getPrintStream().println("Scanning kiji table: " + mURI); final KijiScannerOptions scannerOptions = new KijiScannerOptions() .setStartRow(startRow) .setStopRow(limitRow); final KijiRowScanner scanner = reader.getScanner(request, scannerOptions); try { int rowsOutput = 0; for (KijiRowData row : scanner) { if ((mMaxRows != 0) && (++rowsOutput > mMaxRows)) { break; } ToolUtils.printRow(row, mapTypeFamilies, groupTypeColumns, getPrintStream()); } } finally { ResourceUtils.closeOrLog(scanner); } return SUCCESS; }
Source:
private void refreshGeoRepSessionStatusForSessions(final VDSGroup cluster, List<GlusterGeoRepSession> geoRepSessions) { if (CollectionUtils.isEmpty(geoRepSessions)) { return; } List<Callable<GlusterGeoRepSession>> geoRepSessionCalls = new ArrayList<>(); for (final GlusterGeoRepSession geoRepSession: geoRepSessions) { geoRepSessionCalls.add(new Callable<GlusterGeoRepSession>() { @Override public GlusterGeoRepSession call() throws Exception { geoRepSession.setSessionDetails((ArrayList) getSessionDetailFromCLI(cluster, geoRepSession)); return geoRepSession; } }); } List<GlusterGeoRepSession> updatedSessions = ThreadPoolUtil.invokeAll(geoRepSessionCalls); for (GlusterGeoRepSession updatedSession : updatedSessions) { if (updatedSession.getSessionDetails() == null) { log.info("Geo-replication session details not updated for session '{}' as there was error returning data from VDS", updatedSession.getSessionKey()); continue; } try (EngineLock lock = acquireGeoRepSessionLock(updatedSession.getId())) { GlusterVolumeEntity masterVolume = getVolumeDao().getById(updatedSession.getMasterVolumeId()); updateGeoRepStatus(masterVolume, updatedSession); getGeoRepDao().updateSession(updatedSession); updateSessionDetailsInDB(updatedSession); } } }

Target:
private void refreshGeoRepSessionStatusForSessions(final VDSGroup cluster, List<GlusterGeoRepSession> geoRepSessions) { if (CollectionUtils.isEmpty(geoRepSessions)) { return; } List<Callable<GlusterGeoRepSession>> geoRepSessionCalls = new ArrayList<>(); for (final GlusterGeoRepSession geoRepSession: geoRepSessions) { geoRepSessionCalls.add(new Callable<GlusterGeoRepSession>() { @Override public GlusterGeoRepSession call() throws Exception { geoRepSession.setSessionDetails((ArrayList) getSessionDetailFromCLI(cluster, geoRepSession)); return geoRepSession; } }); } List<GlusterGeoRepSession> updatedSessions = ThreadPoolUtil.invokeAll(geoRepSessionCalls); for (GlusterGeoRepSession updatedSession : updatedSessions) { if (updatedSession.getSessionDetails() == null) { log.info("Geo-replication session details not updated for session '{}' as there was error returning data from VDS", updatedSession.getSessionKey()); continue; } try (EngineLock lock = acquireGeoRepSessionLock(updatedSession.getId())) { GlusterVolumeEntity masterVolume = getVolumeDao().getById(updatedSession.getMasterVolumeId()); updateGeoRepStatus(masterVolume, updatedSession); getGeoRepDao().updateSession(updatedSession); updateSessionDetailsInDB(updatedSession); } catch (Exception e) { log.error("Error updating session details '{}' : '{}'", updatedSession.getSessionKey(), e.getMessage()); log.debug("Exception", e); } } }
Source:
public void testProcessActivity() throws IOException, ActivitySerializerException{ File file = new File("target/test-classes/GPlusUserActivityProviderIT.stdout.txt"); InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (br.ready()) { String line = br.readLine(); if (!StringUtils.isEmpty(line)) { LOGGER.info("raw: {}", line); Activity activity = new Activity(); com.google.api.services.plus.model.Activity gPlusActivity = objectMapper.readValue(line, com.google.api.services.plus.model.Activity.class); StreamsDatum streamsDatum = new StreamsDatum(gPlusActivity); assertNotNull(streamsDatum.getDocument()); List<StreamsDatum> retList = googlePlusTypeConverter.process(streamsDatum); GooglePlusActivityUtil.updateActivity(gPlusActivity, activity); assertEquals(retList.size(), 1); assert(retList.get(0).getDocument() instanceof Activity); assertEquals(activity, retList.get(0).getDocument()); } } }

Target:
public void testProcessActivity() throws IOException, ActivitySerializerException{ File file = new File("target/test-classes/GPlusUserActivityProviderIT.stdout.txt"); InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (br.ready()) { String line = br.readLine(); if (!StringUtils.isEmpty(line)) { LOGGER.info("raw: {}", line); Activity activity = new Activity(); com.google.api.services.plus.model.Activity gPlusActivity = objectMapper.readValue(line, com.google.api.services.plus.model.Activity.class); StreamsDatum streamsDatum = new StreamsDatum(gPlusActivity); assertNotNull(streamsDatum.getDocument()); List<StreamsDatum> retList = googlePlusTypeConverter.process(streamsDatum); GooglePlusActivityUtil.updateActivity(gPlusActivity, activity); assertEquals(retList.size(), 1); assertTrue(retList.get(0).getDocument() instanceof Activity); assertEquals(activity, retList.get(0).getDocument()); } } }
Source:
public void shouldRetryBecomingLeader() throws Exception { when(leaderElectionService.blockOnBecomingLeader()) .thenThrow(new RuntimeException()) .thenReturn(leadershipToken); Runnable proxy = AwaitingLeadershipProxy.newProxyInstance( Runnable.class, delegateSupplier, leaderElectionService); Thread.sleep(1000); proxy.run(); verify(leaderElectionService, times(2)).blockOnBecomingLeader(); }

Target:
public void shouldRetryBecomingLeader() throws Exception { when(leaderElectionService.blockOnBecomingLeader()) .thenThrow(new RuntimeException()) .thenReturn(leadershipToken); Runnable proxy = AwaitingLeadershipProxy.newProxyInstance( Runnable.class, delegateSupplier, leaderElectionService); Thread.sleep(1000); proxy.run(); verify(leaderElectionService, atLeast(2)).blockOnBecomingLeader(); }
Source:
public Future<BigInteger> submit(Topology app, Map<String, Object> config) throws Exception { Boolean forceRemote = (Boolean)config.get(ContextProperties.FORCE_REMOTE); if(forceRemote != null && forceRemote.equals(true)){ return new RemoteBuildAndSubmitter().submit(app, config); } preBundle(config); File bundle = bundler.submit(app, config).get(); preInvoke(); BigInteger jobId = submitJobToService(bundle, config); return new CompletedFuture<BigInteger>(jobId); }

Target:
public Future<BigInteger> submit(Topology app, Map<String, Object> config) throws Exception { Boolean forceRemote = (Boolean)config.get(ContextProperties.FORCE_REMOTE_BUILD); if(forceRemote != null && forceRemote){ return new RemoteBuildAndSubmitter().submit(app, config); } preBundle(config); File bundle = bundler.submit(app, config).get(); preInvoke(); BigInteger jobId = submitJobToService(bundle, config); return new CompletedFuture<BigInteger>(jobId); }
Source:
private void retryingTask(Callable<SweepIterationResult> task) { try { SweepIterationResult sweepResult = task.call(); if (!scalingEnabled.getAsBoolean()) { scheduleAfterDelay(delay.getInitialPause()); } else { long pause = delay.getNextPause(sweepResult); SweepIterationResults.caseOf(sweepResult) .success(numThreads -> determineAction(numThreads, pause)) .unableToAcquireShard(wrap(() -> decreaseNumberOfTasksOrRescheduleIfLast(pause))) .insufficientConsistency(wrap(() -> scheduleAfterDelay(pause))) .otherError(wrap(() -> scheduleAfterDelay(pause))) .disabled(wrap(() -> decreaseNumberOfTasksOrRescheduleIfLast(pause))); } } catch (Exception e) { scheduleAfterDelay(delay.getMaxPause()); } }

Target:
private void retryingTask(Callable<SweepIterationResult> task) { try { SweepIterationResult sweepResult = task.call(); if (!scalingEnabled.getAsBoolean()) { scheduleAfterDelay(delay.getInitialPause()); } else { long pause = delay.getNextPause(sweepResult); SweepIterationResults.caseOf(sweepResult) .success(entriesSwept -> determineAction(entriesSwept, pause)) .unableToAcquireShard(wrap(() -> decreaseNumberOfTasksOrRescheduleIfLast(pause))) .insufficientConsistency(wrap(() -> scheduleAfterDelay(pause))) .otherError(wrap(() -> scheduleAfterDelay(pause))) .disabled(wrap(() -> decreaseNumberOfTasksOrRescheduleIfLast(pause))); } } catch (Exception e) { scheduleAfterDelay(delay.getMaxPause()); } }
Source:
private void expandWorkspaceResource(IResource container) { IWorkbenchPage workbenchPage = getActiveWorkbenchPage(); if (workbenchPage != null) { refreshWorkspaceResource(container); IViewPart projectExplorer = workbenchPage.findView("org.eclipse.ui.navigator.ProjectExplorer"); if (projectExplorer != null && projectExplorer instanceof CommonNavigator) { expandInProjectExplorer((CommonNavigator)projectExplorer, container); } IViewPart packageExplorer = workbenchPage.findView(JavaUI.ID_PACKAGES); if (packageExplorer != null) { expandInPackageExplorer(packageExplorer, container); } } }

Target:
private void expandWorkspaceResource(IResource container) { IWorkbenchPage workbenchPage = getActiveWorkbenchPage(); if (workbenchPage != null) { refreshWorkspaceResource(container); IViewPart projectExplorer = workbenchPage.findView(IPageLayout.ID_PROJECT_EXPLORER); if (projectExplorer != null && projectExplorer instanceof CommonNavigator) { expandInProjectExplorer((CommonNavigator)projectExplorer, container); } IViewPart packageExplorer = workbenchPage.findView(JavaUI.ID_PACKAGES); if (packageExplorer != null) { expandInPackageExplorer(packageExplorer, container); } } }
Source:
public String healthCheck() { return new String("{\"status\":\"running\"}").trim(); }

Target:
public String healthCheck() { return "{\"status\":\"running\"}"; }
Source:
public String toString() { return "OneByOneLoadBalancer" + "\n {" + "\n }"; }

Target:
public String toString() { return "OneByOneLoadBalancer"; }
Source:
protected HttpConnection httpOpen(String method, URL u, AcceptEncoding acceptEncoding) throws IOException { if (method == null || u == null || acceptEncoding == null) { throw new NullPointerException(); } final Proxy proxy = HttpSupport.proxyFor(proxySelector, u); HttpConnection conn = connectionFactory.create(u, proxy); if (!sslVerify && "https".equals(u.getProtocol())) { HttpSupport.disableSslVerify(conn); } conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setUseCaches(false); if (acceptEncoding == AcceptEncoding.GZIP) { conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP); } conn.setRequestProperty(HDR_PRAGMA, "no-cache"); if (UserAgent.get() != null) { conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get()); } int timeOut = getTimeout(); if (timeOut != -1) { int effTimeOut = timeOut * 1000; conn.setConnectTimeout(effTimeOut); conn.setReadTimeout(effTimeOut); } StringBuilder cookieHeaderValue = new StringBuilder(); for (HttpCookie cookie : relevantCookies) { if (!cookie.hasExpired()) { if (cookieHeaderValue.length() > 0) { cookieHeaderValue.append(';'); } cookieHeaderValue.append(cookie.toString()); } } if (cookieHeaderValue.length() >= 0) { conn.setRequestProperty(HDR_COOKIE, cookieHeaderValue.toString()); } if (this.headers != null && !this.headers.isEmpty()) { for (Map.Entry<String, String> entry : this.headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); } authMethod.configureRequest(conn); return conn; }

Target:
protected HttpConnection httpOpen(String method, URL u, AcceptEncoding acceptEncoding) throws IOException { if (method == null || u == null || acceptEncoding == null) { throw new NullPointerException(); } final Proxy proxy = HttpSupport.proxyFor(proxySelector, u); HttpConnection conn = connectionFactory.create(u, proxy); if (!sslVerify && "https".equals(u.getProtocol())) { HttpSupport.disableSslVerify(conn); } conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setUseCaches(false); if (acceptEncoding == AcceptEncoding.GZIP) { conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP); } conn.setRequestProperty(HDR_PRAGMA, "no-cache"); if (UserAgent.get() != null) { conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get()); } int timeOut = getTimeout(); if (timeOut != -1) { int effTimeOut = timeOut * 1000; conn.setConnectTimeout(effTimeOut); conn.setReadTimeout(effTimeOut); } if (relevantCookies.size() > 0) { setCookieHeader(conn); } if (this.headers != null && !this.headers.isEmpty()) { for (Map.Entry<String, String> entry : this.headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); } authMethod.configureRequest(conn); return conn; }
Source:
protected Map<String,Object> prepareEnv(Map<String, String> pTargetConfig) { if (pTargetConfig == null || pTargetConfig.size() == 0) { return null; } Map<String,Object> ret = new HashMap<String, Object>(pTargetConfig); String user = (String) ret.remove("user"); String password = (String) ret.remove("password"); if (user != null && password != null) { ret.put(Context.SECURITY_PRINCIPAL, user); ret.put(Context.SECURITY_CREDENTIALS, password); ret.put("jmx.remote.credentials",new String[] { user, password }); } if (!System.getProperty("javax.net.ssl.trustStore", "NULL").equals("NULL")) { ret.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory()); } return ret; }

Target:
protected Map<String,Object> prepareEnv(Map<String, String> pTargetConfig) { if (pTargetConfig == null || pTargetConfig.size() == 0) { return null; } Map<String,Object> ret = new HashMap<String, Object>(pTargetConfig); String user = (String) ret.remove("user"); String password = (String) ret.remove("password"); if (user != null && password != null) { ret.put(Context.SECURITY_PRINCIPAL, user); ret.put(Context.SECURITY_CREDENTIALS, password); ret.put("jmx.remote.credentials",new String[] { user, password }); } if (System.getProperties().containsKey("javax.net.ssl.trustStore")) { ret.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory()); } return ret; }
Source:
public void getObjectVerifyFullPayload() throws IOException, SignatureException { final String jobIdString = "a4a586a1-cb80-4441-84e2-48974e982d51"; final Map<String, String> queryParams = new HashMap<>(); queryParams.put("job", jobIdString); queryParams.put("offset", Long.toString(0)); final Map<String, String> responseHeaders = new HashMap<>(); responseHeaders.put("Content-Length", "4"); final ByteArraySeekableByteChannel resultChannel = new ByteArraySeekableByteChannel(); final String stringResponse = "Response"; try { MockNetwork .expecting(HttpVerb.GET, "/bucketName/object", queryParams, null) .returning(200, stringResponse, responseHeaders) .asClient() .getObject(new GetObjectRequest("bucketName", "object", 0, UUID.fromString(jobIdString), resultChannel)); } catch (final ContentLengthNotMatchException ex) { assertThat(ex.getMessage(), is("The Content length for object (4) not match the number of byte read (8)")); } }

Target:
public void getObjectVerifyFullPayload() throws IOException, SignatureException { final String jobIdString = "a4a586a1-cb80-4441-84e2-48974e982d51"; final Map<String, String> queryParams = new HashMap<>(); queryParams.put("job", jobIdString); queryParams.put("offset", Long.toString(0)); final Map<String, String> responseHeaders = new HashMap<>(); responseHeaders.put("Content-Length", "4"); final ByteArraySeekableByteChannel resultChannel = new ByteArraySeekableByteChannel(); final String stringResponse = "Response"; MockNetwork .expecting(HttpVerb.GET, "/bucketName/object", queryParams, null) .returning(200, stringResponse, responseHeaders) .asClient() .getObject(new GetObjectRequest("bucketName", "object", 0, UUID.fromString(jobIdString), resultChannel)); }
Source:
private void encodeUtf8Component(CharSequence s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c < 0x80) { if (dontNeedEncoding(c)) { uriBuilder.append(c); } else { appendEncoded(c); } } else if (c < 0x800) { appendEncoded(0xc0 | (c >> 6)); appendEncoded(0x80 | (c & 0x3f)); } else if (StringUtil.isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { appendEncoded(WRITE_UTF_UNKNOWN); continue; } if (++i == s.length()) { appendEncoded(WRITE_UTF_UNKNOWN); break; } writeUtf8Surrogate(c, s.charAt(i)); } else { appendEncoded(0xe0 | (c >> 12)); appendEncoded(0x80 | ((c >> 6) & 0x3f)); appendEncoded(0x80 | (c & 0x3f)); } } }

Target:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (c < 0x80) { if (dontNeedEncoding(c)) { uriBuilder.append(c); } else { appendEncoded(c); } } else if (c < 0x800) { appendEncoded(0xc0 | (c >> 6)); appendEncoded(0x80 | (c & 0x3f)); } else if (StringUtil.isSurrogate(c)) { if (!Character.isHighSurrogate(c)) { appendEncoded(WRITE_UTF_UNKNOWN); continue; } if (++i == s.length()) { appendEncoded(WRITE_UTF_UNKNOWN); break; } writeUtf8Surrogate(c, s.charAt(i)); } else { appendEncoded(0xe0 | (c >> 12)); appendEncoded(0x80 | ((c >> 6) & 0x3f)); appendEncoded(0x80 | (c & 0x3f)); } } }
Source:
public void shouldNotBeAbleToReadLargeAmountsIfSoftLimitSleepWillBeMoreThanConfiguredBackoffTime() { assertThatThrownBy(() -> readOneBatchOfSize(200)) .isInstanceOf(RateLimitExceededException.class) .hasMessage("Rate limited. Available capacity has been exhausted."); }

Target:
public void shouldNotBeAbleToReadLargeAmountsIfSoftLimitSleepWillBeMoreThanConfiguredBackoffTime() { assertThatThrownBy(() -> readOneBatchOfSize(200)) .isInstanceOf(RateLimitExceededException.class) .hasMessage("Rate limited. Available capacity has been exhausted."); assertThatThrownBy(() -> readOneBatchOfSize(1)) .isInstanceOf(RateLimitExceededException.class) .hasMessage("Rate limited. Available capacity has been exhausted."); }
Source:
private boolean isDuplicate(IndexEntry copyCandidate, FileSpan duplicateSearchSpan, Offset indexSegmentStartOffset, boolean checkAlreadyCopied) { try { boolean isDuplicate = false; IndexValue copyCandidateValue = copyCandidate.getValue(); if (duplicateSearchSpan != null && validEntryFilter.alreadyExists(srcIndex, duplicateSearchSpan, copyCandidate.getKey(), copyCandidateValue)) { logger.trace("{} in segment with start offset in is a duplicate because it already exists in store", copyCandidate, indexSegmentStartOffset, storeId); isDuplicate = true; } else if (checkAlreadyCopied && validEntryFilter.alreadyExists(tgtIndex, null, copyCandidate.getKey(), copyCandidateValue)) { logger.trace("{} in segment with start offset in is a duplicate because it has already been copied", copyCandidate, indexSegmentStartOffset, storeId); isDuplicate = true; if (!(recoveryStartToken != null && recoveryStartToken.getOffset().equals(indexSegmentStartOffset))) { tgtMetrics.compactionTargetIndexDuplicateOnNonRecoveryCount.inc(); } } else { logger.trace("{} in index segment with start offset in is not a duplicate", copyCandidate, indexSegmentStartOffset, storeId); } return isDuplicate; } catch (StoreException e) { throw new IllegalStateException(e); } }

Target:
private boolean isDuplicate(IndexEntry copyCandidate, FileSpan duplicateSearchSpan, Offset indexSegmentStartOffset, boolean checkAlreadyCopied) { try { boolean isDuplicate = false; IndexValue copyCandidateValue = copyCandidate.getValue(); if (duplicateSearchSpan != null && validEntryFilter.alreadyExists(srcIndex, duplicateSearchSpan, copyCandidate.getKey(), copyCandidateValue)) { logger.trace("{} in segment with start offset in is a duplicate because it already exists in store", copyCandidate, indexSegmentStartOffset, storeId); isDuplicate = true; } else if (checkAlreadyCopied && validEntryFilter.alreadyExists(tgtIndex, null, copyCandidate.getKey(), copyCandidateValue)) { logger.trace("{} in segment with start offset in is a duplicate because it has already been copied", copyCandidate, indexSegmentStartOffset, storeId); isDuplicate = true; if (!isIndexSegmentUnderCopy(indexSegmentStartOffset)) { tgtMetrics.compactionTargetIndexDuplicateOnNonRecoveryCount.inc(); } } else { logger.trace("{} in index segment with start offset in is not a duplicate", copyCandidate, indexSegmentStartOffset, storeId); } return isDuplicate; } catch (StoreException e) { throw new IllegalStateException(e); } }
Source:
private void initTrayIconExitHandler(Runnable exitCommand) { final TrayIcon trayIcon = createTrayIcon(exitCommand); try { trayIcon.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { restoreFromTray(new ActionEvent(e.getSource(), e.getID(), e.paramString())); } } public void mouseEntered(MouseEvent e) public void mouseExited(MouseEvent e) public void mousePressed(MouseEvent e) public void mouseReleased(MouseEvent e) }); SystemTray.getSystemTray().add(trayIcon); mainWindow.setOnCloseRequest((e) -> { if (Platform.isImplicitExit()) { exitCommand.run(); } else { mainWindow.close(); this.showTrayNotification(trayIcon); } }); } catch (SecurityException | AWTException ex) { mainWindow.setOnCloseRequest((ev) -> { exitCommand.run(); }); } }

Target:
private void initTrayIconExitHandler(Runnable exitCommand) { final TrayIcon trayIcon = createTrayIcon(exitCommand); try { trayIcon.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { restoreFromTray(new ActionEvent(e.getSource(), e.getID(), e.paramString())); } } }); SystemTray.getSystemTray().add(trayIcon); mainWindow.setOnCloseRequest((e) -> { if (Platform.isImplicitExit()) { exitCommand.run(); } else { mainWindow.close(); this.showTrayNotification(trayIcon); } }); } catch (SecurityException | AWTException ex) { mainWindow.setOnCloseRequest((ev) -> { exitCommand.run(); }); } }
Source:
public void missingAccessDecisionManagerIsDetected() { assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.setAccessDecisionManager(null)) .withMessage("accessDecisionManager cannot be null"); }

Target:
public void missingAccessDecisionManagerIsDetected() throws Exception { this.interceptor.setAccessDecisionManager(null); assertThatIllegalArgumentException().isThrownBy(() -> this.interceptor.afterPropertiesSet()); }