auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void writeResponse(ActionParameters params, UserLayer ulayer) throws ActionException { try { final HttpServletResponse response = params.getResponse(); response.setContentType("text/plain;charset=utf-8"); response.setCharacterEncoding("UTF-8"); JSONObject userLayer = userlayerService.parseUserLayer2JSON(ulayer); JSONHelper.putValue(userLayer, "featuresCount", ulayer.getFeatures_count()); JSONObject permissions = OskariLayerWorker.getAllowedPermissions(); JSONHelper.putValue(userLayer, "permissions", permissions); if (ulayer.getFeatures_skipped() > 0) { JSONObject featuresSkipped = new JSONObject(); JSONHelper.putValue(featuresSkipped, "featuresSkipped", ulayer.getFeatures_skipped()); JSONHelper.putValue(userLayer, "warning", featuresSkipped); } response.getWriter().print(userLayer); } catch (IOException e) { throw new ActionException("Failed to write response", e); } }

Target:
private void writeResponse(ActionParameters params, UserLayer ulayer) throws ActionException { JSONObject userLayer = UserLayerDataService.parseUserLayer2JSON(ulayer); JSONHelper.putValue(userLayer, "featuresCount", ulayer.getFeatures_count()); JSONObject permissions = OskariLayerWorker.getAllowedPermissions(); JSONHelper.putValue(userLayer, "permissions", permissions); if (ulayer.getFeatures_skipped() > 0) { JSONObject featuresSkipped = new JSONObject(); JSONHelper.putValue(featuresSkipped, "featuresSkipped", ulayer.getFeatures_skipped()); JSONHelper.putValue(userLayer, "warning", featuresSkipped); } ResponseHelper.writeResponse(params, userLayer); }
Source:
public Set<Branch.NameKey> call() throws NoSuchProjectException, RepositoryNotFoundException, OrmException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); final Iterator<Branch.NameKey> branchIt = toRemove.iterator(); while (branchIt.hasNext()) { final Branch.NameKey k = branchIt.next(); if (!projectName.equals(k.getParentKey())) { throw new IllegalArgumentException("All keys must be from same project"); } if (!projectControl.controlForRef(k).canDelete()) { throw new IllegalStateException("Cannot delete " + k.getShortName()); } if (!db.changes().byBranchOpenAll(k).toList().isEmpty()) { branchIt.remove(); } } final Set<Branch.NameKey> deleted = new HashSet<Branch.NameKey>(); final Repository r = repoManager.openRepository(projectName); try { for (final Branch.NameKey branchKey : toRemove) { final String refname = branchKey.get(); final RefUpdate.Result result; final RefUpdate u; try { u = r.updateRef(refname); u.setForceUpdate(true); result = u.delete(); } catch (IOException e) { log.error("Cannot delete " + branchKey, e); continue; } switch (result) { case NEW: case NO_CHANGE: case FAST_FORWARD: case FORCED: deleted.add(branchKey); replication.scheduleUpdate(projectName, refname); hooks.doRefUpdatedHook(branchKey, u, identifiedUser.getAccount()); break; case REJECTED_CURRENT_BRANCH: log.warn("Cannot delete " + branchKey + ": " + result.name()); break; default: log.error("Cannot delete " + branchKey + ": " + result.name()); break; } } } finally { r.close(); } return deleted; }

Target:
public Set<Branch.NameKey> call() throws NoSuchProjectException, RepositoryNotFoundException, OrmException { final ProjectControl projectControl = projectControlFactory.controlFor(projectName); final Iterator<Branch.NameKey> branchIt = toRemove.iterator(); while (branchIt.hasNext()) { final Branch.NameKey k = branchIt.next(); if (!projectName.equals(k.getParentKey())) { throw new IllegalArgumentException("All keys must be from same project"); } if (!projectControl.controlForRef(k).canDelete()) { throw new IllegalStateException("Cannot delete " + k.getShortName()); } if (db.changes().byBranchOpenAll(k).iterator().hasNext()) { branchIt.remove(); } } final Set<Branch.NameKey> deleted = new HashSet<Branch.NameKey>(); final Repository r = repoManager.openRepository(projectName); try { for (final Branch.NameKey branchKey : toRemove) { final String refname = branchKey.get(); final RefUpdate.Result result; final RefUpdate u; try { u = r.updateRef(refname); u.setForceUpdate(true); result = u.delete(); } catch (IOException e) { log.error("Cannot delete " + branchKey, e); continue; } switch (result) { case NEW: case NO_CHANGE: case FAST_FORWARD: case FORCED: deleted.add(branchKey); replication.scheduleUpdate(projectName, refname); hooks.doRefUpdatedHook(branchKey, u, identifiedUser.getAccount()); break; case REJECTED_CURRENT_BRANCH: log.warn("Cannot delete " + branchKey + ": " + result.name()); break; default: log.error("Cannot delete " + branchKey + ": " + result.name()); break; } } } finally { r.close(); } return deleted; }
Source:
private void createServiceBindings() { createServiceBinding( TypeTranslatorInitiator.INSTANCE ); createServiceBinding( DatastoreServicesInitiator.INSTANCE ); createServiceBinding( DatastoreProviderInitiator.INSTANCE ); createServiceBinding( GridDialectFactoryInitiator.INSTANCE ); }

Target:
private void createServiceBindings() { for ( SessionFactoryServiceInitiator<?> inititator : OgmSessionFactoryServiceInitiators.LIST ) { createServiceBinding( inititator ); } }
Source:
private boolean runAnsiblePackOvaPlaybook(String ovf, Collection<DiskImage> disks, Map<Guid, String> diskIdToPath) { String encodedOvf = genOvfParameter(ovf); AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(String.format("{0}:{1}", getVds().getHostName(), getVds().getSshPort())) .variable("target_directory", getParameters().getDirectory()) .variable("entity_type", getParameters().getEntityType().name().toLowerCase()) .variable("ova_size", String.valueOf(calcOvaSize(disks, encodedOvf))) .variable("ova_name", getParameters().getName()) .variable("ovirt_ova_pack_ovf", encodedOvf) .variable("ovirt_ova_pack_disks", genDiskParameters(disks, diskIdToPath)) .logFileDirectory(CREATE_OVA_LOG_DIRECTORY) .logFilePrefix("ovirt-export-ova-ansible") .logFileName(getVds().getHostName()) .logFileSuffix(getCorrelationId()) .playbook(AnsibleConstants.EXPORT_OVA_PLAYBOOK); boolean succeeded = ansibleExecutor.runCommand(command).getAnsibleReturnCode() == AnsibleReturnCode.OK; if (!succeeded) { log.error("Failed to create OVA. Please check logs for more details: {}", command.logFile()); } return succeeded; }

Target:
private boolean runAnsiblePackOvaPlaybook(String ovf, Collection<DiskImage> disks, Map<Guid, String> diskIdToPath) { String encodedOvf = genOvfParameter(ovf); AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hosts(getVds()) .variable("target_directory", getParameters().getDirectory()) .variable("entity_type", getParameters().getEntityType().name().toLowerCase()) .variable("ova_size", String.valueOf(calcOvaSize(disks, encodedOvf))) .variable("ova_name", getParameters().getName()) .variable("ovirt_ova_pack_ovf", encodedOvf) .variable("ovirt_ova_pack_disks", genDiskParameters(disks, diskIdToPath)) .logFileDirectory(CREATE_OVA_LOG_DIRECTORY) .logFilePrefix("ovirt-export-ova-ansible") .logFileName(getVds().getHostName()) .logFileSuffix(getCorrelationId()) .playbook(AnsibleConstants.EXPORT_OVA_PLAYBOOK); boolean succeeded = ansibleExecutor.runCommand(command).getAnsibleReturnCode() == AnsibleReturnCode.OK; if (!succeeded) { log.error("Failed to create OVA. Please check logs for more details: {}", command.logFile()); } return succeeded; }
Source:
public <T> T readData(String path, boolean returnNullIfPathNotExists) { T data = null; try { return readData(path, null); } catch (ZkNoNodeException e) { if (!returnNullIfPathNotExists) { throw e; } } return data; }

Target:
public <T> T readData(String path, boolean returnNullIfPathNotExists) { checkIfPathContainsShardingKey(path); return _rawZkClient.readData(path, returnNullIfPathNotExists); }
Source:
public ElementNode(AbstractNode root, AbstractNode parent, DetailAST detailAst) { super(root.getTreeInfo()); this.parent = parent; this.root = root; this.detailAst = detailAst; nodeDepth = -1; text = TokenUtil.getTokenName(detailAst.getType()); indexAmongSiblings = parent.getChildren().size(); createTextAttribute(); createChildren(); }

Target:
public ElementNode(AbstractNode root, AbstractNode parent, DetailAST detailAst) { super(root.getTreeInfo()); this.parent = parent; this.root = root; this.detailAst = detailAst; text = TokenUtil.getTokenName(detailAst.getType()); indexAmongSiblings = parent.getChildren().size(); setDepth(parent.getDepth() + 1); createTextAttribute(); createChildren(); }
Source:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongIntMap sharedLocks = sharedLockCounts[resourceType.typeId()]; PrimitiveLongIntMap exclusiveLocks = exclusiveLockCounts[resourceType.typeId()]; ConcurrentMap<Long,ForsetiLockManager.Lock> resourceTypeLocks = lockMaps[resourceType.typeId()]; for ( long resourceId : resourceIds ) { if ( releaseLocalLock( resourceType, resourceId, sharedLocks ) ) { return; } if ( !exclusiveLocks.containsKey( resourceId ) ) { releaseGlobalLock( resourceTypeLocks, resourceId ); } } } finally { stateHolder.decrementActiveClients(); } }

Target:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongIntMap sharedLocks = sharedLockCounts[resourceType.typeId()]; PrimitiveLongIntMap exclusiveLocks = exclusiveLockCounts[resourceType.typeId()]; ConcurrentMap<Long,ForsetiLockManager.Lock> resourceTypeLocks = lockMaps[resourceType.typeId()]; for ( long resourceId : resourceIds ) { if ( releaseLocalLock( resourceType, resourceId, sharedLocks ) ) { continue; } if ( !exclusiveLocks.containsKey( resourceId ) ) { releaseGlobalLock( resourceTypeLocks, resourceId ); } } } finally { stateHolder.decrementActiveClients(); } }
Source:
public void onNarrowFillSendBox(Message message) { if(message.getType() == MessageType.PRIVATE_MESSAGE){ switchToPrivate(); streamActv.setText(message.getReplyTo(app)); messageEt.requestFocus(); } else { switchToStream(); streamActv.setText(message.getStream().getName()); topicActv.setText(message.getSubject()); if (message.getSubject().equals("")) topicActv.requestFocus(); else messageEt.requestFocus(); } }

Target:
public void onNarrowFillSendBox(Message message) { if(message.getType() == MessageType.PRIVATE_MESSAGE){ switchToPrivate(); topicActv.setText(message.getReplyTo(app)); messageEt.requestFocus(); } else { switchToStream(); streamActv.setText(message.getStream().getName()); topicActv.setText(message.getSubject()); if ("".equals(message.getSubject())) topicActv.requestFocus(); else messageEt.requestFocus(); } ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); }
Source:
private String getChildDocId(Element element, String key, String name, Visibility visibility) { NameSubstitutionStrategy substitutionStrategy = getConfig().getNameSubstitutionStrategy(); return element.getId() + "_" + substitutionStrategy.deflate(name) + "_" + substitutionStrategy.deflate(key); }

Target:
private String getChildDocId(Element element, String key, String name, Visibility visibility) { return element.getId() + "_" + this.nameSubstitutionStrategy.deflate(name) + "_" + this.nameSubstitutionStrategy.deflate(key); }
Source:
public void setServerContent(Map<String, String> serverContent) { Preconditions.checkNotNull(serverContent); this.serverContent = serverContent; }

Target:
public void setServerContent(Map<String, String> serverContent) { checkNotNull(serverContent); this.serverContent = serverContent; }
Source:
protected void powerOffRadioSafely() { DataConnectionTracker dcTracker = phone.mDataConnection; Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); msg.obj = CDMAPhone.REASON_RADIO_TURNED_OFF; if (networkType == ServiceState.RADIO_TECHNOLOGY_1xRTT) { msg.arg1 = 0; dcTracker.sendMessage(msg); Log.w(LOG_TAG, "Turn off the radio right away"); hangupAndPowerOff(); } else { synchronized (this) { if (!mPendingRadioPowerOffAfterDataOff) { DataConnectionTracker.State currentState = dcTracker.getState(); if (currentState != DataConnectionTracker.State.CONNECTED && currentState != DataConnectionTracker.State.DISCONNECTING && currentState != DataConnectionTracker.State.INITING) { msg.arg1 = 0; dcTracker.sendMessage(msg); if (DBG) log("Data disconnected, turn off radio right away."); hangupAndPowerOff(); } else { msg.arg1 = 1; dcTracker.sendMessage(msg); if (sendEmptyMessageDelayed(EVENT_SET_RADIO_POWER_OFF, 30000)) { if (DBG) { log("Wait upto 30s for data to disconnect, then turn off radio."); } mPendingRadioPowerOffAfterDataOff = true; } else { Log.w(LOG_TAG, "Cannot send delayed Msg, turn off radio right away."); hangupAndPowerOff(); } } } } } }

Target:
protected void powerOffRadioSafely() { DataConnectionTracker dcTracker = phone.mDataConnection; Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); msg.obj = CDMAPhone.REASON_RADIO_TURNED_OFF; synchronized (this) { if (networkType == ServiceState.RADIO_TECHNOLOGY_1xRTT) { msg.arg1 = 0; dcTracker.sendMessage(msg); Log.w(LOG_TAG, "Turn off the radio right away"); hangupAndPowerOff(); } else { if (!mPendingRadioPowerOffAfterDataOff) { DataConnectionTracker.State currentState = dcTracker.getState(); if (currentState != DataConnectionTracker.State.CONNECTED && currentState != DataConnectionTracker.State.DISCONNECTING && currentState != DataConnectionTracker.State.INITING) { msg.arg1 = 0; dcTracker.sendMessage(msg); if (DBG) log("Data disconnected, turn off radio right away."); hangupAndPowerOff(); } else { msg.arg1 = 1; dcTracker.sendMessage(msg); if (sendEmptyMessageDelayed(EVENT_SET_RADIO_POWER_OFF, 30000)) { if (DBG) { log("Wait upto 30s for data to disconnect, then turn off radio."); } mPendingRadioPowerOffAfterDataOff = true; } else { Log.w(LOG_TAG, "Cannot send delayed Msg, turn off radio right away."); hangupAndPowerOff(); } } } } } }
Source:
public static org.apache.stratos.common.beans.TenantInfoBean getTenantByDomain(String tenantDomain) throws Exception { TenantManager tenantManager = ServiceHolder.getTenantManager(); int tenantId; try { tenantId = tenantManager.getTenantId(tenantDomain); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain + "."; log.error(msg); throw new Exception(msg, e); } Tenant tenant; try { tenant = (Tenant) tenantManager.getTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant from the tenant manager."; log.error(msg); throw new Exception(msg, e); } TenantInfoBean bean; try { bean = ObjectConverter .convertCarbonTenantInfoBeanToTenantInfoBean(TenantMgtUtil.initializeTenantInfoBean(tenantId, tenant)); } catch (Exception e) { log.error(String.format("Couldn't find tenant for provided tenant domain. [Tenant Domain] %s", tenantDomain)); return null; } bean.setFirstname(ClaimsMgtUtil.getFirstNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); bean.setLastname(ClaimsMgtUtil.getLastNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); return bean; }

Target:
public static org.apache.stratos.common.beans.TenantInfoBean getTenantByDomain(String tenantDomain) throws Exception { TenantManager tenantManager = ServiceHolder.getTenantManager(); int tenantId; try { tenantId = tenantManager.getTenantId(tenantDomain); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain + "."; log.error(msg,e); throw new Exception(msg, e); } Tenant tenant; try { tenant = (Tenant) tenantManager.getTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant from the tenant manager."; log.error(msg,e); throw new Exception(msg, e); } TenantInfoBean bean; try { bean = ObjectConverter .convertCarbonTenantInfoBeanToTenantInfoBean(TenantMgtUtil.initializeTenantInfoBean(tenantId, tenant)); } catch (Exception e) { log.error(String.format("Couldn't find tenant for provided tenant domain. [Tenant Domain] %s", tenantDomain),e); return null; } bean.setFirstname(ClaimsMgtUtil.getFirstNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); bean.setLastname(ClaimsMgtUtil.getLastNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); return bean; }
Source:
public Response getFirmwares(@PathParam("thingTypeUID") @ApiParam(value = "thingTypeUID") String thingTypeUID, @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = HttpHeaders.ACCEPT_LANGUAGE) String language) { ThingTypeUID athingTypeUID = new ThingTypeUID(thingTypeUID); if (firmwareRegistry != null) { Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(athingTypeUID, LocaleUtil.getLocale(language)); List<FirmwareDTO> firmwareList = convertToFirmwareDTO(firmwares); return Response.ok().entity(firmwareList).build(); } else { return Response.status(Status.NO_CONTENT).build(); } }

Target:
public Response getFirmwares(@PathParam("thingTypeUID") @ApiParam(value = "thingTypeUID") String thingTypeUID, @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = HttpHeaders.ACCEPT_LANGUAGE) String language) { ThingTypeUID athingTypeUID = new ThingTypeUID(thingTypeUID); Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(athingTypeUID, LocaleUtil.getLocale(language)); List<FirmwareDTO> firmwareList = convertToFirmwareDTO(firmwares); if (firmwareList.isEmpty()) { return Response.status(Status.NO_CONTENT).build(); } return Response.ok().entity(firmwareList).build(); }
Source:
protected String mapRouteToService(String serviceId) { if(this.serviceRouteMapper != null) { return this.serviceRouteMapper.apply(serviceId); } return serviceId; }

Target:
protected String mapRouteToService(String serviceId) { return this.serviceRouteMapper.apply(serviceId); }
Source:
public void registerDefaultActions() { if (initialized.getAndSet(true)) { LOG.debug("Attempt to initialize default actions more than once!"); return; } register(new StoreValueChangeAction()); register(new StoreAttributeAction()); register(new CreatePresentationModelAction()); register(new DeletePresentationModelAction()); }

Target:
public void registerDefaultActions() { if (initialized.getAndSet(true)) { LOG.warn("Attempt to initialize default actions more than once!"); return; } register(new StoreValueChangeAction()); register(new StoreAttributeAction()); register(new CreatePresentationModelAction()); register(new DeletePresentationModelAction()); }
Source:
public void patchExtBadValue() throws IOException { String request = jsonParser.getJson("/ResourceIT/patchExtBadValue.req.json"); JsonNode result = jsonApiMapper.getObjectMapper().readTree(given() .contentType(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .accept(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .body(request) .patch("/") .then() .statusCode(HttpStatus.SC_LOCKED) .extract() .body() .asString()); JsonNode errors = result.get("errors"); assertNotNull(errors); assertEquals(errors.size(), 1); String error = errors.get(0).asText(); String expected = "TransactionException: Unique index or primary key violation:"; assertTrue(error.startsWith(expected), "Error does not start with '" + expected + "' but found " + error); }

Target:
public void patchExtBadValue() throws IOException { String request = jsonParser.getJson("/ResourceIT/patchExtBadValue.req.json"); JsonNode result = jsonApiMapper.getObjectMapper().readTree(given() .contentType(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .accept(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .body(request) .patch("/") .then() .statusCode(HttpStatus.SC_LOCKED) .extract() .body() .asString()); JsonNode errors = result.get("errors"); assertNotNull(errors); assertEquals(errors.size(), 1); String error = errors.get(0).asText(); String expected = "TransactionException:"; assertTrue(error.startsWith(expected), "Error does not start with '" + expected + "' but found " + error); }
Source:
private void updateMetaData(XWikiDocument doc, XWikiContext context) throws XWikiException { doc.removeXObjects(FeatureMetadatum.CLASS_REFERENCE); for (Feature feature : this.features) { @SuppressWarnings("unchecked") Map<String, FeatureMetadatum> metadataMap = (Map<String, FeatureMetadatum>) feature.getMetadata(); if (metadataMap.isEmpty() && feature.getNotes().isEmpty()) { continue; } BaseObject metaObject = doc.newXObject(FeatureMetadatum.CLASS_REFERENCE, context); metaObject.set(PhenoTipsFeature.META_PROPERTY_NAME, ((PhenoTipsFeature) feature).getPropertyName(), context); metaObject.set(PhenoTipsFeature.META_PROPERTY_VALUE, feature.getValue(), context); for (String type : metadataMap.keySet()) { PhenoTipsFeatureMetadatum metadatum = (PhenoTipsFeatureMetadatum) metadataMap.get(type); metaObject.set(type, metadatum.getId(), context); } metaObject.set("comments", feature.getNotes(), context); } }

Target:
private void updateMetaData(XWikiDocument doc, XWikiContext context) throws XWikiException { doc.removeXObjects(FeatureMetadatum.CLASS_REFERENCE); for (Feature feature : this.features) { @SuppressWarnings("unchecked") Map<String, FeatureMetadatum> metadataMap = (Map<String, FeatureMetadatum>) feature.getMetadata(); if (metadataMap.isEmpty() && feature.getNotes().isEmpty()) { continue; } BaseObject metaObject = doc.newXObject(FeatureMetadatum.CLASS_REFERENCE, context); metaObject.set(PhenoTipsFeature.META_PROPERTY_NAME, feature.getPropertyName(), context); metaObject.set(PhenoTipsFeature.META_PROPERTY_VALUE, feature.getValue(), context); for (String type : metadataMap.keySet()) { PhenoTipsFeatureMetadatum metadatum = (PhenoTipsFeatureMetadatum) metadataMap.get(type); metaObject.set(type, metadatum.getId(), context); } metaObject.set("comments", feature.getNotes(), context); } }
Source:
public synchronized void doPrepare(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { JSONObject submittedForm = req.getSubmittedForm(); String inputReason = submittedForm.getString("shutdownReason"); String shutdownReason = inputReason.isEmpty() ? null : inputReason; LOGGER.log(Level.FINE, "Shutdown requested"); Jenkins.get().doQuietDown(false, 0, shutdownReason).generateResponse(req, rsp, null); }

Target:
public synchronized void doPrepare(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { Jenkins.get().checkPermission(Jenkins.MANAGE); JSONObject submittedForm = req.getSubmittedForm(); String inputReason = submittedForm.getString("shutdownReason"); String shutdownReason = inputReason.isEmpty() ? null : inputReason; LOGGER.log(Level.FINE, "Shutdown requested"); Jenkins.get().doQuietDown(false, 0, shutdownReason).generateResponse(req, rsp, null); }
Source:
public void setUp() throws Exception { super.setUp(); impl = new HttpBreakpointManagementDaemonImpl(null); }

Target:
public void setUp() throws Exception { super.setUp(); impl = new HttpBreakpointManagementDaemonImpl(); }
Source:
private @Nullable JobStatus mapStateToStatus(final States state) { final JobStatus jobStatus; if (States.SETUP_JOB.equals(state) && previousJobStatus == null) { jobStatus = JobStatus.INIT; } else if (States.MONITOR_JOB.equals(state) && JobStatus.INIT.equals(previousJobStatus)) { jobStatus = JobStatus.RUNNING; } else if ( States.HANDLE_ERROR.equals(state) && (JobStatus.INIT.equals(previousJobStatus) || JobStatus.RUNNING.equals(previousJobStatus))) { jobStatus = JobStatus.FAILED; } else if (States.CLEANUP_JOB.equals(state)) { jobStatus = executionContext.getFinalJobStatus(); } else { jobStatus = null; } return jobStatus; }

Target:
private @Nullable JobStatus mapStateToStatus(final States state) { final JobStatus jobStatus; if (States.SETUP_JOB == state && previousJobStatus == null) { jobStatus = JobStatus.INIT; } else if (States.MONITOR_JOB == state && JobStatus.INIT == previousJobStatus) { jobStatus = JobStatus.RUNNING; } else if ( States.HANDLE_ERROR == state && (JobStatus.INIT == previousJobStatus || JobStatus.RUNNING == previousJobStatus)) { jobStatus = JobStatus.FAILED; } else if (States.CLEANUP_JOB.equals(state)) { jobStatus = executionContext.getFinalJobStatus(); } else { jobStatus = null; } return jobStatus; }
Source:
public Object eGet(EObject eObject, final String featureName) { if (eObject == null || featureName == null) { throw new NullPointerException(); } Optional<EStructuralFeature> feature = Iterables.tryFind( eObject.eClass().getEAllStructuralFeatures(), new Predicate<EStructuralFeature>() { @Override public boolean apply(EStructuralFeature input) { return input != null && featureName.equals(input.getName()); } }); Object result = null; if (feature.isPresent()) { result = eObject.eGet(feature.get()); } if (result instanceof Set<?>) { result = Sets.newLinkedHashSet((Set<?>)result); } else if (result instanceof Collection<?>) { result = Lists.newArrayList((Set<?>)result); } return result; }

Target:
public Object eGet(EObject eObject, final String featureName) { if (eObject == null || featureName == null) { throw new NullPointerException(); } Optional<EStructuralFeature> feature = Iterables.tryFind( eObject.eClass().getEAllStructuralFeatures(), new Predicate<EStructuralFeature>() { @Override public boolean apply(EStructuralFeature input) { return input != null && featureName.equals(input.getName()); } }); Object result = null; if (feature.isPresent()) { result = eObject.eGet(feature.get()); } if (result instanceof Set<?>) { result = Sets.newLinkedHashSet((Set<?>)result); } else if (result instanceof EMap<?, ?>) { result = new BasicEMap<Object, Object>(((EMap<?, ?>)result).map()); } else if (result instanceof Collection<?>) { result = Lists.newArrayList((Collection<?>)result); } return result; }
Source:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg rcvMsg = codec.decode(aggregationMessage.getData().array()); final String workerId = aggregationMessage.getSourceId().toString(); switch (rcvMsg.getType()) { case RequestInitClock: final int workerClock = initializeWorkerClock(workerId); final byte[] data = codec.encode(getReplyInitialClockMessage(globalMinimumClock, workerClock)); try { aggregationMaster.send(AGGREGATION_CLIENT_NAME, workerId, data); } catch (final NetworkException e) { LOG.log(Level.INFO, "Target worker failed to receive the initial worker clock message.", e); } break; case Tick: tickClock(workerId); break; default: } }

Target:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg rcvMsg = codec.decode(aggregationMessage.getData().array()); final String workerId = aggregationMessage.getSourceId().toString(); switch (rcvMsg.getType()) { case RequestInitClockMsg: final int workerClock = initializeWorkerClock(workerId); final byte[] data = codec.encode(getReplyInitialClockMessage(globalMinimumClock, workerClock)); int retryCount = 0; while (true) { if (retryCount++ > MAXIMUM_RETRY_COUNTS) { throw new RuntimeException(String.format("Sending initialization message to %s has failed %d times", workerId, MAXIMUM_RETRY_COUNTS + 1)); } try { aggregationMaster.send(AGGREGATION_CLIENT_NAME, workerId, data); break; } catch (final NetworkException e) { LOG.log(Level.INFO, String.format("ClockManager failed to send initialization message to %s", workerId), e); } } break; case TickMsg: tickClock(workerId); break; default: throw new RuntimeException("Unexpected message type: " + rcvMsg.getType().toString()); } }
Source:
@Override public long getSize(){ return managedCache.size(); }

Target:
@Override public long getSize(){ long size = 0; for(ManagedCache<K, V> mc : managedCache){ size += mc.getSize(); } return size; }
Source:
ListenableFuture<List<String>> getNames(final LabelId id, final LabelType type) { BoundStatement getNameBoundStatement = getNameStatement.bind(toLong(id), type.toValue()); final ListenableFuture<List<Row>> namesFuture = transform( session.executeAsync(getNameBoundStatement), new ResultSetToRowListFunction("Found duplicate IDs for ({}, {})", id, type)); return transform(namesFuture, new Function<List<Row>, List<String>>() { @Override public List<String> apply(final List<Row> rows) { final ImmutableList.Builder<String> names = ImmutableList.builder(); for (final Row row : rows) { final String name = row.getString("name"); names.add(name); } return names.build(); } }); }

Target:
ListenableFuture<List<String>> getNames(final LabelId id, final LabelType type) { BoundStatement getNameBoundStatement = getNameStatement.bind(toLong(id), type.toValue()); final ListenableFuture<List<Row>> namesFuture = transform( session.executeAsync(getNameBoundStatement), new MultipleRowLoggingFunction("Found duplicate IDs for ({}, {})", id, type)); return transform(namesFuture, new Function<List<Row>, List<String>>() { @Override public List<String> apply(final List<Row> rows) { final ImmutableList.Builder<String> names = ImmutableList.builder(); for (final Row row : rows) { final String name = row.getString("name"); names.add(name); } return names.build(); } }); }
Source:
public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this.scope = ChooserScope.TABLE; this.context = context; this.tableId = Objects.requireNonNull(tableId); tabletId = null; }

Target:
public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this(tableId, null, context); }
Source:
public void testAuthorized() throws Exception { ContextMapper classUnderTest = new ContextMapper(CONTEXT); HttpServletRequest originalRequest = createMockRequest("/a/plugins/", PLUGIN_NAME + "/" + RESOURCE); HttpServletRequest result = classUnderTest.create(originalRequest, PLUGIN_NAME); assertEquals(CONTEXT + "/a/plugins/" + PLUGIN_NAME, result.getContextPath()); assertEquals("", result.getServletPath()); assertEquals("/" + RESOURCE, result.getPathInfo()); assertEquals(CONTEXT + "/a/plugins/" + (PLUGIN_NAME + "/" + RESOURCE), result.getRequestURI()); }

Target:
public void testAuthorized() throws Exception { ContextMapper classUnderTest = new ContextMapper(CONTEXT); HttpServletRequest originalRequest = createMockRequest("/a/plugins/", PLUGIN_NAME + "/" + RESOURCE); HttpServletRequest result = classUnderTest.create(originalRequest, PLUGIN_NAME); assertEquals(CONTEXT + "/a/plugins/" + PLUGIN_NAME, result.getContextPath()); assertEquals("", result.getServletPath()); assertEquals("/" + RESOURCE, result.getPathInfo()); assertEquals(CONTEXT + "/a/plugins/" + PLUGIN_NAME + "/" + RESOURCE, result.getRequestURI()); }
Source:
private static String retrieveNodeExecutableFromConfig(@Nullable Configuration configuration) throws NodeCommandException { if (configuration != null && (configuration.hasKey(NODE_EXECUTABLE_PROPERTY) || configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS))) { String nodeExecutable = ""; String usedProperty = ""; if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS)) { LOG.warn("The use of " + NODE_EXECUTABLE_PROPERTY_TS + " is deprecated, use " + NODE_EXECUTABLE_PROPERTY + " instead."); usedProperty = NODE_EXECUTABLE_PROPERTY_TS; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY_TS).get(); } if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY)) { usedProperty = NODE_EXECUTABLE_PROPERTY; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY).get(); } File file = new File(nodeExecutable); if (file.exists()) { LOG.info("Using Node.js executable from property {}.", file.getAbsoluteFile(), usedProperty); return nodeExecutable; } else { LOG.error("Provided Node.js executable file does not exist. Property '{}' was to '{}'", NODE_EXECUTABLE_PROPERTY, nodeExecutable); throw new NodeCommandException("Provided Node.js executable file does not exist."); } } LOG.debug("Using default Node.js executable: '{}'.", NODE_EXECUTABLE_DEFAULT); return NODE_EXECUTABLE_DEFAULT; }

Target:
private static String retrieveNodeExecutableFromConfig(@Nullable Configuration configuration) throws NodeCommandException { if (configuration != null && (configuration.hasKey(NODE_EXECUTABLE_PROPERTY) || configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS))) { String nodeExecutable = ""; String usedProperty = ""; if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY_TS)) { LOG.warn("The use of " + NODE_EXECUTABLE_PROPERTY_TS + " is deprecated, use " + NODE_EXECUTABLE_PROPERTY + " instead."); usedProperty = NODE_EXECUTABLE_PROPERTY_TS; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY_TS).get(); } if (configuration.hasKey(NODE_EXECUTABLE_PROPERTY)) { usedProperty = NODE_EXECUTABLE_PROPERTY; nodeExecutable = configuration.get(NODE_EXECUTABLE_PROPERTY).get(); } File file = new File(nodeExecutable); if (file.exists()) { LOG.info("Using Node.js executable from property {}.", file.getAbsoluteFile(), usedProperty); return nodeExecutable; } else { LOG.error("Provided Node.js executable file does not exist. Property '{}' was to '{}'", usedProperty, nodeExecutable); throw new NodeCommandException("Provided Node.js executable file does not exist."); } } LOG.debug("Using default Node.js executable: '{}'.", NODE_EXECUTABLE_DEFAULT); return NODE_EXECUTABLE_DEFAULT; }
Source:
private void autoIgnoreDerivedResources(IProject project, IProgressMonitor monitor) throws CoreException { if (!Activator.autoIgnoreDerived()) { return; } List<IPath> paths = findDerivedResources(project); if (paths.size() > 0) { IgnoreOperation ignoreOp = new IgnoreOperation(paths); IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1); ignoreOp.execute(subMonitor); } }

Target:
private void autoIgnoreDerivedResources(IProject project, IProgressMonitor monitor) throws CoreException { if (!Activator.autoIgnoreDerived()) { return; } List<IPath> paths = findDerivedResources(project); if (paths.size() > 0) { IgnoreOperation ignoreOp = new IgnoreOperation(paths); ignoreOp.execute(monitor); } }
Source:
private void showOrHideButtons() { if (playQueue == null) return; if (playQueue.getIndex() == 0) playPreviousButton.setVisibility(View.INVISIBLE); else playPreviousButton.setVisibility(View.VISIBLE); if (playQueue.getIndex() + 1 == playQueue.getStreams().size()) playNextButton.setVisibility(View.INVISIBLE); else playNextButton.setVisibility(View.VISIBLE); if (playQueue.getStreams().size() <= 1 || popupPlayerSelected()) queueButton.setVisibility(View.GONE); else queueButton.setVisibility(View.VISIBLE); }

Target:
private void showOrHideButtons() { if (playQueue == null) { return; } playPreviousButton.setVisibility(playQueue.getIndex() == 0 ? View.INVISIBLE : View.VISIBLE); playNextButton.setVisibility(playQueue.getIndex() + 1 == playQueue.getStreams().size() ? View.INVISIBLE : View.VISIBLE); queueButton.setVisibility(playQueue.getStreams().size() <= 1 || popupPlayerSelected() ? View.GONE : View.VISIBLE); }
Source:
private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug("JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); SimpleDateFormat jdbcDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.format(filter.getBeginDate()) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.format(filter.getEndDate().getTime()) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC "; if (filter.getPageSize() != 0x7fffffff) { filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(value," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }

Target:
private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug( "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.print(new DateTime(filter.getBeginDate().getTime())) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.print(new DateTime(filter.getEndDate().getTime())) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC "; if (filter.getPageSize() != 0x7fffffff) { filterString += " LIMIT " + filter.getPageNumber() * filter.getPageSize() + "," + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(value," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }
Source:
public <V> V getService(Class<V> serviceClass, String filter) { ServiceReference<V> serviceRef = getServiceReference(serviceClass, filter); if (serviceRef == null) { return null; } else { if (fServices.containsKey(serviceRef)) { @SuppressWarnings("unchecked") V service = (V)fServices.get(serviceRef); return service; } else { V service = fBundleContext.getService(serviceRef); fServices.put(serviceRef, service); return service; } } }

Target:
public <V> V getService(Class<V> serviceClass, String filter) { ServiceReference<V> serviceRef = getServiceReference(serviceClass, filter); if (serviceRef == null) { return null; } @SuppressWarnings("unchecked") V service = (V)fServices.get(serviceRef); if (service == null) { if (fServices.containsKey(serviceRef) == false) { service = fBundleContext.getService(serviceRef); fServices.put(serviceRef, service); } } return service; }
Source:
public void onBindViewHolder(RandoViewHolder holder, Cursor cursor) { recycle(holder); holder.rando = RandoDAO.cursorToRando(cursor); holder.position = cursor.getPosition(); holder.timestamp.setText(dateFormat.format(holder.rando.date).toUpperCase()); setRatingIcon(holder, false); loadImages(holder.randoItemLayout.getContext(), holder, holder.rando); if (holder.rando.isUnwanted()) { holder.unwantedRandoView = new UnwantedRandoView(holder.randoItemLayout.getContext()); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.unwantedRandoView, layoutParams); } else { if (holder.rando.isToUpload()) { holder.uploadingProgress = new RoundProgress(holder.randoItemLayout.getContext(), (float) (imageSize / 2.0) - 8); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.uploadingProgress, layoutParams); } else { setAnimations(holder); } } }

Target:
public void onBindViewHolder(RandoViewHolder holder, Cursor cursor) { recycle(holder); holder.rando = RandoDAO.cursorToRando(cursor); holder.position = cursor.getPosition(); String timestamp = holder.rando.date.after(nyDate) ? dateFormat.format(holder.rando.date) : dateYearFormat.format(holder.rando.date); holder.timestamp.setText(timestamp.toUpperCase()); setRatingIcon(holder, false); loadImages(holder.randoItemLayout.getContext(), holder, holder.rando); if (holder.rando.isUnwanted()) { holder.unwantedRandoView = new UnwantedRandoView(holder.randoItemLayout.getContext()); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.unwantedRandoView, layoutParams); } else { if (holder.rando.isToUpload()) { holder.uploadingProgress = new RoundProgress(holder.randoItemLayout.getContext(), (float) (imageSize / 2.0) - 8); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageSize, imageSize); holder.randoItemLayout.addView(holder.uploadingProgress, layoutParams); } else { setAnimations(holder); } } }
Source:
protected void setWorkflowImplServiceListener(WorkflowImplServiceListener workflowListener) { if(workflowListener !=null) { WorkflowImplServiceDataHolder.getInstance().getWorkflowListenerList() .add(workflowListener); } }

Target:
protected void setWorkflowImplServiceListener(WorkflowImplServiceListener workflowListener) { WorkflowImplServiceDataHolder.getInstance().getWorkflowListenerList().add(workflowListener); }
Source:
public boolean performNextOperation(int completedChildCount) { switch (getParameters().getCreateSnapshotStage()) { case CREATE_VOLUME_FINISHED: getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_STARTED); Snapshot createdSnapshot = snapshotDao.get(getParameters().getCreatedSnapshotId()); getParameters().setTaskGroupSuccess(createdSnapshot != null && getParameters().getTaskGroupSuccess()); if (getParameters().getTaskGroupSuccess()) { getParameters().setLiveSnapshotRequired(shouldPerformLiveSnapshot(createdSnapshot)); if (getParameters().isLiveSnapshotRequired()) { getParameters().setLiveSnapshotSucceeded(performLiveSnapshot(createdSnapshot)); } else if (snapshotWithMemory(createdSnapshot)) { logMemorySavingFailed(); snapshotDao.removeMemoryFromSnapshot(createdSnapshot.getId()); removeMemoryVolumesOfSnapshot(createdSnapshot); } } getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_COMPLETED); break; default: return false; } persistCommandIfNeeded(); return true; }

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getCreateSnapshotStage() == CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_VOLUME_FINISHED) { getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_STARTED); Snapshot createdSnapshot = snapshotDao.get(getParameters().getCreatedSnapshotId()); getParameters().setTaskGroupSuccess(createdSnapshot != null && getParameters().getTaskGroupSuccess()); if (getParameters().getTaskGroupSuccess()) { getParameters().setLiveSnapshotRequired(shouldPerformLiveSnapshot(createdSnapshot)); if (getParameters().isLiveSnapshotRequired()) { getParameters().setLiveSnapshotSucceeded(performLiveSnapshot(createdSnapshot)); } else if (snapshotWithMemory(createdSnapshot)) { logMemorySavingFailed(); snapshotDao.removeMemoryFromSnapshot(createdSnapshot.getId()); removeMemoryVolumesOfSnapshot(createdSnapshot); } } getParameters().setCreateSnapshotStage(CreateSnapshotForVmParameters.CreateSnapshotStage.CREATE_SNAPSHOT_COMPLETED); persistCommandIfNeeded(); return true; } return false; }
Source:
void connect() throws Exception { webSocketConnection.connect(); verify(webSocketClient) .connectBlocking( WebSocketConnection.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); }

Target:
void connect() throws Exception { when(webSocketClient.connectBlocking(anyLong(), any())).thenReturn(true); webSocketConnection.connect(); verify(webSocketClient).connectBlocking(anyLong(), any()); }
Source:
void close() { if (running) { synchronized (this) { if (running) { try { LOG.info("Starting to close FeatureStateConsumer."); kafkaConsumer.wakeup(); shutdownLatch.await(); running = false; LOG.info("Successfully closed FeatureStateConsumer."); } catch (InterruptedException e) { LOG.error("An error occurred while closing FeatureStateConsumer.", e); } } else { LOG.info("FeatureStateConsumer has already been closed."); } } } else { LOG.info("FeatureStateConsumer has already been closed."); } }

Target:
private synchronized void close() { if (running) { try { LOG.debug("Starting to close FeatureStateConsumer."); kafkaConsumer.wakeup(); shutdownLatch.await(); LOG.debug("Successfully closed FeatureStateConsumer."); } catch (InterruptedException e) { LOG.warn("Closing of FeatureStateConsumer was interrupted.", e); currentThread().interrupt(); } } else { LOG.info("FeatureStateConsumer has already been closed."); } }
Source:
default SaslServer createSaslServer(String mechanism, List<Principal> principals, String protocol, String serverName, Map<String, String> props) throws SaslException { AuthorizingCallbackHandler callbackHandler = getCallbackHandler(mechanism, props); if ("EXTERNAL".equals(mechanism)) { for(Principal principal : principals) { if (principal instanceof X500Principal) { ExternalSaslServerFactory factory = new ExternalSaslServerFactory((X500Principal) principal); SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); return new SubjectSaslServer(saslServer, principals, callbackHandler); } } throw new IllegalStateException("EXTERNAL mech requires X500Principal"); } else { for (SaslServerFactory factory : SaslUtils.getSaslServerFactories()) { if (factory != null) { SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); if (saslServer != null) { return new SubjectSaslServer(saslServer, principals, callbackHandler); } } } } return null; }

Target:
default SaslServer createSaslServer(String mechanism, List<Principal> principals, String protocol, String serverName, Map<String, String> props) throws SaslException { AuthorizingCallbackHandler callbackHandler = getCallbackHandler(mechanism, props); if ("EXTERNAL".equals(mechanism)) { for(Principal principal : principals) { if (principal instanceof X500Principal) { ExternalSaslServerFactory factory = new ExternalSaslServerFactory((X500Principal) principal); SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); return new SubjectSaslServer(saslServer, principals, callbackHandler); } } throw new IllegalStateException("EXTERNAL mech requires X500Principal"); } else { for (SaslServerFactory factory : SaslUtils.getSaslServerFactories(this.getClass().getClassLoader(), true)) { if (factory != null) { SaslServer saslServer = factory.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { if (callbackHandler != null) { callbackHandler.handle(callbacks); } }); if (saslServer != null) { return new SubjectSaslServer(saslServer, principals, callbackHandler); } } } } return null; }
Source:
private boolean isLocationEnabled() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gpsEnabled = false; boolean networkEnabled = false; try { gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception e) { Toast.makeText(getApplicationContext(), R.string.gps_network_not_available, Toast.LENGTH_SHORT).show(); } if (gpsEnabled && networkEnabled) { return true; } else { return false; } }

Target:
private boolean isLocationEnabled() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gpsEnabled = false; boolean networkEnabled = false; if (lm != null) { try { gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), R.string.gps_network_not_available, Toast.LENGTH_SHORT) .show(); } } else { Toast.makeText(getApplicationContext(), R.string.location_services_unavailable, Toast.LENGTH_SHORT) .show(); } return gpsEnabled && networkEnabled; }