auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void cleanUpProgramState(CFG.Block block) { programState = ProgramState.cleanupDeadSymbols(programState, liveVariables.getOut(block)); programState = programState.cleanupConstraints(); }

Target:
private void cleanUpProgramState(CFG.Block block) { if (cleanup) { programState = programState.cleanupDeadSymbols(liveVariables.getOut(block)); programState = programState.cleanupConstraints(); } }
Source:
public LdapReturnValueBase execute() { try { log.debugFormat("Running LDAP command: {0}", getClass().getName()); String loginNameForKerberos = LdapBrokerUtils.modifyLoginNameForKerberos(getLoginName(), getAuthenticationDomain()); LdapCredentials ldapCredentials = new LdapCredentials(loginNameForKerberos, getPassword()); DirectorySearcher directorySearcher = new DirectorySearcher(ldapCredentials); executeQuery(directorySearcher); } catch (RuntimeException e) { log.errorFormat(String.format("Failed to run command %s. Domain is %s. User is %s.", getClass().getSimpleName(), getDomain(), getLoginName())); _ldapReturnValue.setExceptionString(VdcBllMessages.FAILED_TO_RUN_LDAP_QUERY.name()); } return _ldapReturnValue; }

Target:
public LdapReturnValueBase execute() { try { log.debugFormat("Running LDAP command: {0}", getClass().getName()); String loginNameForKerberos = LdapBrokerUtils.modifyLoginNameForKerberos(getLoginName(), getAuthenticationDomain()); LdapCredentials ldapCredentials = new LdapCredentials(loginNameForKerberos, getPassword()); DirectorySearcher directorySearcher = new DirectorySearcher(ldapCredentials); executeQuery(directorySearcher); } catch (RuntimeException e) { log.error(String.format("Failed to run command %s. Domain is %s. User is %s.", getClass().getSimpleName(), getDomain(), getLoginName())); _ldapReturnValue.setExceptionString(VdcBllMessages.FAILED_TO_RUN_LDAP_QUERY.name()); } return _ldapReturnValue; }
Source:
protected String getTitle() { return "Developer Options"; }

Target:
protected String getTitle() { return Localization.get("settings.developer.title"); }
Source:
public <T> Subscription addOnRemovedListener(final Class<T> beanClass, final BeanRemovedListener<? super T> listener) { DolphinUtils.assertIsDolphinBean(beanClass); if (beanRemovedListenerMap.containsKey(beanClass)) { beanRemovedListenerMap.get(beanClass).add(listener); } else { beanRemovedListenerMap.put(beanClass, Arrays.asList(listener)); } return () -> { if (beanRemovedListenerMap.containsKey(beanClass)) { beanRemovedListenerMap.get(beanClass).remove(listener); } }; }

Target:
public <T> Subscription addOnRemovedListener(final Class<T> beanClass, final BeanRemovedListener<? super T> listener) { DolphinUtils.assertIsDolphinBean(beanClass); beanRemovedListenerMap.computeIfAbsent(beanClass, s -> new ArrayList()).add(listener); return () -> { if (beanRemovedListenerMap.containsKey(beanClass)) { beanRemovedListenerMap.get(beanClass).remove(listener); } }; }
Source:
protected void buildImage( DockerContainerConfig containerConfig, String machineImageName, boolean doForcePullOnBuild, ProgressMonitor progressMonitor) throws InternalInfrastructureException { File workDir = null; try { BuildImageParams buildImageParams; if (containerConfig.getBuild() != null && containerConfig.getBuild().getDockerfileContent() != null) { workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append(containerConfig.getBuild().getDockerfileContent()); } buildImageParams = BuildImageParams.create(dockerfileFile); } else { buildImageParams = BuildImageParams.create(containerConfig.getBuild().getContext()) .withDockerfile(containerConfig.getBuild().getDockerfilePath()); } buildImageParams .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(doForcePullOnBuild) .withMemoryLimit(containerConfig.getMemLimit()) .withMemorySwapLimit(-1) .withBuildArgs(containerConfig.getBuild().getArgs()); dockerConnector.buildImage(buildImageParams, progressMonitor); } catch (IOException e) { throw new InternalInfrastructureException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } }

Target:
private void buildImage( DockerContainerConfig containerConfig, String machineImageName, boolean doForcePullOnBuild, ProgressMonitor progressMonitor) throws InternalInfrastructureException { File workDir = null; try { BuildImageParams buildImageParams; if (containerConfig.getBuild() != null && containerConfig.getBuild().getDockerfileContent() != null) { workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append(containerConfig.getBuild().getDockerfileContent()); } buildImageParams = BuildImageParams.create(dockerfileFile); } else { buildImageParams = BuildImageParams.create(containerConfig.getBuild().getContext()) .withDockerfile(containerConfig.getBuild().getDockerfilePath()); } buildImageParams .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(doForcePullOnBuild) .withMemoryLimit(containerConfig.getMemLimit()) .withMemorySwapLimit(-1) .withBuildArgs(containerConfig.getBuild().getArgs()); dockerConnector.buildImage(buildImageParams, progressMonitor); } catch (IOException e) { throw new InternalInfrastructureException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } }
Source:
public static AsyncLockClient create(MetricRegistry metricRegistry, List<String> hosts) { return new AsyncLockClient(TimelockUtils.createClient(metricRegistry, hosts, NamespaceAwareTimelockRpcClient.class)); }

Target:
public static AsyncLockClient create(MetricRegistry metricRegistry, List<String> hosts) { return new AsyncLockClient(TimelockUtils.createClient(metricRegistry, hosts, NamespacedTimelockRpcClient.class)); }
Source:
public static void maybeShowEditDescriptionUnlockNotification(@NonNull Context context, boolean forced) { if (!WikipediaApp.getInstance().isAnyActivityResumed() && !Prefs.isSuggestedEditsAddDescriptionsMessageShown() || forced) { Prefs.setSuggestedEditsAddDescriptionsMessageShown(true); SuggestedEditsFunnel.get(Constants.InvokeSource.NOTIFICATION).pause(); Intent intent = EditTasksActivity.newIntent(context, Constants.InvokeSource.EDIT_FEED_TITLE_DESC); NotificationCompat.Builder builder = NotificationPresenter.getDefaultBuilder(context); PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(0, context.getString(R.string.suggested_edits_unlock_notification_button), pendingIntent); NotificationPresenter.showNotification(context, builder, 0, context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_title), context.getString(R.string.suggested_edits_unlock_notification_text), context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_big_text), R.drawable.ic_mode_edit_white_24dp, R.color.accent50, intent); } }

Target:
public static void maybeShowEditDescriptionUnlockNotification(@NonNull Context context, boolean forced) { if (!WikipediaApp.getInstance().isAnyActivityResumed() || forced) { SuggestedEditsFunnel.get(Constants.InvokeSource.NOTIFICATION).pause(); Intent intent = EditTasksActivity.newIntent(context, Constants.InvokeSource.EDIT_FEED_TITLE_DESC); NotificationCompat.Builder builder = NotificationPresenter.getDefaultBuilder(context); PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(0, context.getString(R.string.suggested_edits_unlock_notification_button), pendingIntent); NotificationPresenter.showNotification(context, builder, 0, context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_title), context.getString(R.string.suggested_edits_unlock_notification_text), context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_big_text), R.drawable.ic_mode_edit_white_24dp, R.color.accent50, intent); } }
Source:
public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") , "testResources"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(exercises.size(), 152); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }

Target:
public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") + "/testResources/"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(153, exercises.size()); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }
Source:
public int hashCode() { int result = 17; result = 31 * result + edgeId.hashCode(); if (outputTag != null) { result = 31 * result + outputTag.hashCode(); } return result; }

Target:
public int hashCode() { return Objects.hash(edgeId, outputTag); }
Source:
public GetObjectsOnTapeResult call() { try { final GetBlobsOnTapeSpectraS3Response response = getClient().getBlobsOnTapeSpectraS3(new GetBlobsOnTapeSpectraS3Request(null, this.tapeId)); return new GetObjectsOnTapeResult(this.tapeId, response.getBulkObjectListResult().getObjects().iterator()); } catch (final IOException e) { if (CommandExceptionFactory.hasStatusCode(e, 404)) { CommandExceptionFactory.getInstance().handleException(this.getClass().getSimpleName(), new CommandException("Unknown tape '" + this.tapeId +"'", e), true); } else { CommandExceptionFactory.getInstance().handleException(this.getClass().getSimpleName(), e, true); } return null; } }

Target:
public GetObjectsOnTapeResult call() throws CommandException, IOException { try { final GetBlobsOnTapeSpectraS3Response response = getClient().getBlobsOnTapeSpectraS3(new GetBlobsOnTapeSpectraS3Request(null, this.tapeId)); return new GetObjectsOnTapeResult(this.tapeId, response.getBulkObjectListResult().getObjects().iterator()); } catch (final FailedRequestException e) { if (e.getStatusCode() == 404) { throw new CommandException("Unknown tape '" + this.tapeId +"'", e); } throw e; } }
Source:
public boolean isRamValueValid() { final String validationAttribute = "aria-invalid"; return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(waitRamTextField(), validationAttribute) .equals("false"); }

Target:
public boolean isRamValueValid() { final String invalidRamFlagAttribute = "aria-invalid"; return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(waitRamTextField(), invalidRamFlagAttribute) .equals("false"); }
Source:
public TransactionController getReadOnlyTransaction(ContextManager cm, long id) throws StandardException { String transName = AccessFactoryGlobals.USER_TRANS_NAME; if (LOG.isDebugEnabled()) LOG.debug("in SpliceAccessManager - getAndNameTransaction, transName=" + transName); if (cm == null) return null; SpliceTransactionManagerContext rtc = (SpliceTransactionManagerContext) cm.getContext(AccessFactoryGlobals.RAMXACT_CONTEXT_ID); if (rtc != null) return rtc.getTransactionManager(); if (LOG.isDebugEnabled()) LOG.debug("in SpliceAccessManager - getAndNameTransaction, SpliceTransactionManagerContext is null"); Transaction rawtran = rawstore.createPastTransaction(cm, transName, id); SpliceTransactionManager rt = new SpliceTransactionManager(this, rawtran, null); rtc = new SpliceTransactionManagerContext(cm, AccessFactoryGlobals.RAMXACT_CONTEXT_ID, rt, false ); TransactionController tc = rtc.getTransactionManager(); if (xactProperties != null) { rawtran.setup(tc); } return tc; }

Target:
public TransactionController getReadOnlyTransaction(ContextManager cm, long id) throws StandardException { String transName = AccessFactoryGlobals.USER_TRANS_NAME; if (LOG.isDebugEnabled()) LOG.debug("in SpliceAccessManager - getReadOnlyTransaction, transName=" + transName); if (cm == null) throw new NullPointerException("ContextManager cannot be null"); SpliceTransactionManagerContext rtc = (SpliceTransactionManagerContext) cm.getContext(AccessFactoryGlobals.RAMXACT_CONTEXT_ID); if (rtc != null) return rtc.getTransactionManager(); if (LOG.isDebugEnabled()) LOG.debug("in SpliceAccessManager - getReadOnlyTransaction, SpliceTransactionManagerContext is null"); Transaction rawtran = rawstore.createPastTransaction(cm, transName, id); SpliceTransactionManager rt = new SpliceTransactionManager(this, rawtran, null); rtc = new SpliceTransactionManagerContext(cm, AccessFactoryGlobals.RAMXACT_CONTEXT_ID, rt, false ); TransactionController tc = rtc.getTransactionManager(); if (xactProperties != null) { rawtran.setup(tc); } return tc; }
Source:
public FormValidation doCheckTargetApiURL(@QueryParameter("targetApiURL") final String targetApiURL) { if(StringUtils.isNotBlank(targetApiURL) && !DatadogHttpClient.validateTargetURL(targetApiURL)) { return FormValidation.error("The field must be configured in the form <http|https>://<url>/"); } return FormValidation.ok("Valid URL"); }

Target:
public FormValidation doCheckTargetApiURL(@QueryParameter("targetApiURL") final String targetApiURL) { if(!validateURL(targetApiURL)) { return FormValidation.error("The field must be configured in the form <http|https>://<url>/"); } return FormValidation.ok("Valid URL"); }
Source:
private void rename(MetaDataUpdate md) throws IOException, ConfigInvalidException { boolean success = false; for (int attempts = 0; !success && attempts < MAX_TRIES; attempts++) { ProjectConfig config = ProjectConfig.read(md); GroupReference ref = config.getGroup(uuid); if (ref == null || newName.equals(ref.getName())) { projectCache.evict(config.getProject()); return; } ref.setName(newName); md.getCommitBuilder().setAuthor(author); md.setMessage("Rename group " + oldName + " to " + newName + "\n"); try { config.commit(md); projectCache.evict(config.getProject()); success = true; } catch (IOException e) { try { Thread.sleep(25 ); } catch (InterruptedException wakeUp) { continue; } } } if (!success) { if (tryingAgain) { log.warn("Could not rename group " + oldName + " to " + newName + " in " + md.getProjectName().get()); } else { retryOn.add(md.getProjectName()); } } }

Target:
private void rename(MetaDataUpdate md) throws IOException, ConfigInvalidException { boolean success = false; for (int attempts = 0; !success && attempts < MAX_TRIES; attempts++) { ProjectConfig config = ProjectConfig.read(md); GroupReference ref = config.getGroup(uuid); if (ref == null || newName.equals(ref.getName())) { projectCache.evict(config.getProject()); return; } ref.setName(newName); md.getCommitBuilder().setAuthor(author); md.setMessage("Rename group " + oldName + " to " + newName + "\n"); try { config.commit(md); projectCache.evict(config.getProject()); success = true; } catch (IOException e) { log.error("Could not commit rename of group " + oldName + " to " + newName + " in " + md.getProjectName().get(), e); try { Thread.sleep(25 ); } catch (InterruptedException wakeUp) { continue; } } } if (!success) { if (tryingAgain) { log.warn("Could not rename group " + oldName + " to " + newName + " in " + md.getProjectName().get()); } else { retryOn.add(md.getProjectName()); } } }
Source:
public void testValidateLabels(){ Nic nicWithUnmanagedNetwork = new Nic(); nicWithUnmanagedNetwork.setName("eth_unmanaged"); NicLabel label = new NicLabel(null, "eth1", "label1"); NicLabel labelWithUnmanagedNetwork = new NicLabel(null, "eth_unmanaged", "labelOnUnmanaged"); Set<NicLabel> labels = new HashSet<>(Arrays.asList(label, labelWithUnmanagedNetwork)); ValidationResult result = validator.validateLabels(nicWithUnmanagedNetwork, labels); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_LABEL_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(LABEL, "labelOnUnmanaged"), ReplacementUtils.createSetVariableString(NIC, "eth_unmanaged"))); NicLabel labelWithoutUnmanaged = new NicLabel(null, "eth_other", "label1"); Set<NicLabel> labelsNotOnUnmanagedNetwork = new HashSet<>(Arrays.asList(labelWithoutUnmanaged)); result = validator.validateLabels(nicWithUnmanagedNetwork, labelsNotOnUnmanagedNetwork); assertTrue(result.isValid()); }

Target:
public void testValidateLabels(){ String nicWithUnmanagedNetwork = "eth_unmanaged"; NicLabel label = new NicLabel(null, "eth1", "label1"); NicLabel labelWithUnmanagedNetwork = new NicLabel(null, nicWithUnmanagedNetwork, "labelOnUnmanaged"); Collection<NicLabel> labels = Arrays.asList(label, labelWithUnmanagedNetwork); ValidationResult result = validator.validateLabels(nicWithUnmanagedNetwork, labels); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_LABEL_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(LABEL, "labelOnUnmanaged"), ReplacementUtils.createSetVariableString(NIC, "eth_unmanaged"))); NicLabel labelWithoutUnmanaged = new NicLabel(null, "eth_other", "label1"); Collection<NicLabel> labelsNotOnUnmanagedNetwork = Arrays.asList(labelWithoutUnmanaged); result = validator.validateLabels(nicWithUnmanagedNetwork, labelsNotOnUnmanagedNetwork); assertTrue(result.isValid()); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); mRasterFunctionButton = findViewById(R.id.rasterButton); mRasterFunctionButton.setEnabled(false); map = new ArcGISMap(Basemap.createDarkGrayCanvasVector()); final ImageServiceRaster imageServiceRaster = new ImageServiceRaster(getString(R.string.image_service_raster_url)); final RasterLayer imageRasterLayer = new RasterLayer(imageServiceRaster); map.getOperationalLayers().add(imageRasterLayer); imageRasterLayer.addDoneLoadingListener(() -> { if (imageRasterLayer.getLoadStatus() == LoadStatus.LOADED) { Point centerPnt = imageServiceRaster.getServiceInfo().getFullExtent().getCenter(); mMapView.setViewpointCenterAsync(centerPnt, 55000000); mRasterFunctionButton.setEnabled(true); } }); mRasterFunctionButton.setOnClickListener(v -> applyRasterFunction(imageServiceRaster)); mMapView.setMap(map); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMapView = findViewById(R.id.mapView); mRasterFunctionButton = findViewById(R.id.rasterButton); mRasterFunctionButton.setEnabled(false); ArcGISMap map = new ArcGISMap(Basemap.createDarkGrayCanvasVector()); final ImageServiceRaster imageServiceRaster = new ImageServiceRaster(getString(R.string.image_service_raster_url)); final RasterLayer imageRasterLayer = new RasterLayer(imageServiceRaster); map.getOperationalLayers().add(imageRasterLayer); imageRasterLayer.addDoneLoadingListener(() -> { if (imageRasterLayer.getLoadStatus() == LoadStatus.LOADED) { Point centerPnt = imageServiceRaster.getServiceInfo().getFullExtent().getCenter(); mMapView.setViewpointCenterAsync(centerPnt, 55000000); mRasterFunctionButton.setEnabled(true); } else { String error = "Error loading image raster layer: " + imageRasterLayer.getLoadError(); Log.e(TAG, error); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); } }); mRasterFunctionButton.setOnClickListener(v -> applyRasterFunction(imageServiceRaster)); mMapView.setMap(map); }
Source:
public AbstractSiteMap parseSiteMap(String contentType, byte[] content, URL url) throws UnknownFormatException, IOException { MediaType mediaType = MediaType.parse(contentType); while (mediaType != null && !mediaType.equals(MediaType.OCTET_STREAM)) { if (XML_MEDIA_TYPES.contains(mediaType)) { return processXml(url, content); } else if (TEXT_MEDIA_TYPES.contains(mediaType)) { return processText(url, content); } else if (GZ_MEDIA_TYPES.contains(mediaType)) { InputStream decompressed; MediaType embeddedType; try { decompressed = new GZIPInputStream(new ByteArrayInputStream(content)); embeddedType = MediaType.parse(TIKA.detect(decompressed)); } catch (Exception e) { UnknownFormatException err = new UnknownFormatException("Failed to detect embedded MediaType of gzipped sitemap: " + url + ", caused by " + e); err.initCause(e); throw err; } if (XML_MEDIA_TYPES.contains(embeddedType)) { return processGzip(url, content); } else if (TEXT_MEDIA_TYPES.contains(embeddedType)) { decompressed = new GZIPInputStream(new ByteArrayInputStream(content)); return processText(url, decompressed); } else if (GZ_MEDIA_TYPES.contains(embeddedType)) { throw new UnknownFormatException("Can't parse gzip recursively: " + url); } throw new UnknownFormatException("Can't parse a gzipped sitemap with the embedded MediaType of: " + embeddedType + " (at: " + url + ")"); } mediaType = MEDIA_TYPE_REGISTRY.getSupertype(mediaType); } throw new UnknownFormatException("Can't parse a sitemap with the MediaType of: " + contentType + " (at: " + url + ")"); }

Target:
public AbstractSiteMap parseSiteMap(String contentType, byte[] content, URL url) throws UnknownFormatException, IOException { MediaType mediaType = MediaType.parse(contentType); while (mediaType != null && !mediaType.equals(MediaType.OCTET_STREAM)) { if (XML_MEDIA_TYPES.contains(mediaType)) { return processXml(url, content); } else if (TEXT_MEDIA_TYPES.contains(mediaType)) { return processText(url, content); } else if (GZ_MEDIA_TYPES.contains(mediaType)) { InputStream decompressed; MediaType embeddedType; try { decompressed = new GZIPInputStream(new ByteArrayInputStream(content)); embeddedType = MediaType.parse(TIKA.detect(decompressed)); } catch (Exception e) { UnknownFormatException err = new UnknownFormatException("Failed to detect embedded MediaType of gzipped sitemap: " + url + ", caused by " + e); err.initCause(e); throw err; } if (XML_MEDIA_TYPES.contains(embeddedType)) { return processGzippedXML(url, content); } else if (TEXT_MEDIA_TYPES.contains(embeddedType)) { decompressed = new GZIPInputStream(new ByteArrayInputStream(content)); return processText(url, decompressed); } else if (GZ_MEDIA_TYPES.contains(embeddedType)) { throw new UnknownFormatException("Can't parse gzip recursively: " + url); } throw new UnknownFormatException("Can't parse a gzipped sitemap with the embedded MediaType of: " + embeddedType + " (at: " + url + ")"); } mediaType = MEDIA_TYPE_REGISTRY.getSupertype(mediaType); } throw new UnknownFormatException("Can't parse a sitemap with the MediaType of: " + contentType + " (at: " + url + ")"); }
Source:
private boolean openSerialPort(final String serialPortName, int baudRate) { logger.debug("Connecting to serial port '{}'", serialPortName); try { SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(serialPortName); if (portIdentifier == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Port does not exist"); return false; } serialPort = portIdentifier.open("org.openhab.binding.zigbee", 2000); serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.enableReceiveTimeout(2000); serialPort.notifyOnDataAvailable(true); logger.info("Connected to serial port '{}'.", serialPortName); } catch (PortInUseException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "Serial Error: Port in use"); return false; } catch (UnsupportedCommOperationException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Serial Error: Unsupported operation"); return false; } try { inputStream = new BufferedInputStream(serialPort.getInputStream()); outputStream = serialPort.getOutputStream(); } catch (IOException e) { logger.error("Error getting serial streams", e); return false; } return true; }

Target:
private boolean openSerialPort(final String serialPortName, int baudRate) { logger.debug("Connecting to serial port '{}'", serialPortName); try { SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(serialPortName); if (portIdentifier == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Port does not exist"); return false; } SerialPort sp = portIdentifier.open("org.openhab.binding.bluetooth.bluegiga", 2000); sp.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); sp.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT); sp.enableReceiveThreshold(1); sp.enableReceiveTimeout(2000); sp.notifyOnDataAvailable(true); logger.info("Connected to serial port '{}'.", serialPortName); try { inputStream = new BufferedInputStream(sp.getInputStream()); outputStream = sp.getOutputStream(); } catch (IOException e) { logger.error("Error getting serial streams", e); return false; } this.serialPort = sp; return true; } catch (PortInUseException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "Serial Error: Port in use"); return false; } catch (UnsupportedCommOperationException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, "Serial Error: Unsupported operation"); return false; } }
Source:
private String buildAuthorizationRequestUri() { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, percentEncode(this.responseType.getValue())); parameters.set(OAuth2ParameterNames.CLIENT_ID, percentEncode(this.clientId)); if (!CollectionUtils.isEmpty(this.scopes)) { parameters.set(OAuth2ParameterNames.SCOPE, percentEncode(StringUtils.collectionToDelimitedString(this.scopes, " "))); } if (this.state != null) { parameters.set(OAuth2ParameterNames.STATE, percentEncode(this.state)); } if (this.redirectUri != null) { parameters.set(OAuth2ParameterNames.REDIRECT_URI, percentEncode(this.redirectUri)); } if (!CollectionUtils.isEmpty(this.additionalParameters)) { this.additionalParameters.forEach((k, v) -> parameters.set(percentEncode(k), percentEncode(v.toString()))); } return UriComponentsBuilder.fromHttpUrl(this.authorizationUri) .queryParams(parameters) .build() .toUriString(); }

Target:
private String buildAuthorizationRequestUri() { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, encodeQueryParam(this.responseType.getValue())); parameters.set(OAuth2ParameterNames.CLIENT_ID, encodeQueryParam(this.clientId)); if (!CollectionUtils.isEmpty(this.scopes)) { parameters.set(OAuth2ParameterNames.SCOPE, encodeQueryParam(StringUtils.collectionToDelimitedString(this.scopes, " "))); } if (this.state != null) { parameters.set(OAuth2ParameterNames.STATE, encodeQueryParam(this.state)); } if (this.redirectUri != null) { parameters.set(OAuth2ParameterNames.REDIRECT_URI, encodeQueryParam(this.redirectUri)); } if (!CollectionUtils.isEmpty(this.additionalParameters)) { this.additionalParameters.forEach((k, v) -> parameters.set(encodeQueryParam(k), encodeQueryParam(v.toString()))); } return UriComponentsBuilder.fromHttpUrl(this.authorizationUri) .queryParams(parameters) .build() .toUriString(); }
Source:
public static ByteRange fromOffsetRange(long startOffset, long endOffset) { if (startOffset < 0 || endOffset < startOffset) { throw new IllegalArgumentException( "Invalid range offsets provided for ByteRange; startOffset=" + startOffset + ", endOffset=" + endOffset); } return new OffsetRange(startOffset, endOffset); }

Target:
public static ByteRange fromOffsetRange(long startOffset, long endOffset) { return ByteRanges.fromOffsetRange(startOffset, endOffset); }
Source:
public void checkValid(String value) throws InvalidConditionParameterException{ if(!allowAdditions){ if(!options.containsKey(value)) throw new InvalidConditionParameterException("Parameter '%s' is not allowed. Additions are not allowed on the dropdown",value); } }

Target:
public void checkValid(String value) throws InvalidConditionParameterException, RuleEngineException{ if(allowAdditions) try{ this.getDataType().checkValid(value); }catch(Exception e){ Logger.error(this.getClass(), e.getMessage(), e); throw new RuleEngineException(e.getMessage()); } else if(!options.containsKey(value)) throw new InvalidConditionParameterException("Parameter '%s' is not allowed. Additions are not allowed on the dropdown",value); }
Source:
SubscriptionImpl subscribe(String subject, String queue, MessageHandler cb, BlockingQueue<Message> ch) { final SubscriptionImpl sub; mu.lock(); try { if (closed()) { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } if (cb == null && ch == null) { throw new IllegalArgumentException(ERR_BAD_SUBSCRIPTION); } if (cb != null) { MsgDeliveryPool msgDlvPool = null; final boolean useDlvPool = (this.opts.useGlobalMsgDelivery && ((msgDlvPool = Nats.getMsgDeliveryThreadPool()) != null)); sub = new AsyncSubscriptionImpl(this, subject, queue, cb, useDlvPool); if (useDlvPool) { msgDlvPool.assignDeliveryWorker((AsyncSubscriptionImpl) sub); } else { subexec.submit(new Runnable() { public void run() { try { waitForMsgs((AsyncSubscriptionImpl) sub); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); } } else { sub = new SyncSubscriptionImpl(this, subject, queue); sub.setChannel(ch); } addSubscription(sub); if (!reconnecting()) { sendSubscriptionMessage(sub); } kickFlusher(); return sub; } finally { mu.unlock(); } }

Target:
SubscriptionImpl subscribe(String subject, String queue, MessageHandler cb, BlockingQueue<Message> ch) { final SubscriptionImpl sub; mu.lock(); try { if (closed()) { throw new IllegalStateException(ERR_CONNECTION_CLOSED); } if (cb == null && ch == null) { throw new IllegalArgumentException(ERR_BAD_SUBSCRIPTION); } if (cb != null) { MsgDeliveryPool msgDlvPool = null; final boolean useDlvPool = (this.opts.useGlobalMsgDelivery && ((msgDlvPool = Nats.getMsgDeliveryThreadPool()) != null)); sub = new AsyncSubscriptionImpl(this, subject, queue, cb, useDlvPool); if (useDlvPool) { msgDlvPool.assignDeliveryWorker((AsyncSubscriptionImpl) sub); } else { subexec.submit(new Runnable() { public void run() { waitForMsgs((AsyncSubscriptionImpl) sub); } }); } } else { sub = new SyncSubscriptionImpl(this, subject, queue); sub.setChannel(ch); } addSubscription(sub); if (!reconnecting()) { sendSubscriptionMessage(sub); } kickFlusher(); return sub; } finally { mu.unlock(); } }
Source:
private void enforceTaskLimits() { int totalRunningTaskCount = 0; int highestRunningTaskCount = 0; Optional<T> highestRunningTaskQuery = Optional.empty(); for (T query : queries.values()) { if (query.isDone()) { continue; } int runningTaskCount = query.getRunningTask(); totalRunningTaskCount += runningTaskCount; if (runningTaskCount > highestRunningTaskCount) { highestRunningTaskCount = runningTaskCount; highestRunningTaskQuery = Optional.of(query); } } runningTaskCount.set(totalRunningTaskCount); if (totalRunningTaskCount > maxTotalRunningTaskCount && highestRunningTaskCount > maxQueryRunningTaskCount && highestRunningTaskQuery.isPresent()) { highestRunningTaskQuery.get().fail(new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Cluster is overloaded with too many tasks (%s), query with highest running tasks is killed (%s). " + TOO_MANY_STAGES_MESSAGE, totalRunningTaskCount, highestRunningTaskCount))); queriesKilledDueToTooManyTask.incrementAndGet(); } }

Target:
private void enforceTaskLimits() { int totalRunningTaskCount = 0; int highestRunningTaskCount = 0; Optional<T> highestRunningTaskQuery = Optional.empty(); for (T query : queries.values()) { if (query.isDone()) { continue; } int runningTaskCount = query.getRunningTaskCount(); totalRunningTaskCount += runningTaskCount; if (runningTaskCount > highestRunningTaskCount) { highestRunningTaskCount = runningTaskCount; highestRunningTaskQuery = Optional.of(query); } } runningTaskCount.set(totalRunningTaskCount); if (totalRunningTaskCount > maxTotalRunningTaskCount && highestRunningTaskCount > maxQueryRunningTaskCount && highestRunningTaskQuery.isPresent()) { highestRunningTaskQuery.get().fail(new PrestoException(QUERY_HAS_TOO_MANY_STAGES, format( "Query killed because the cluster is overloaded with too many tasks (%s) and this query was running with the highest number of tasks (%s). %s Otherwise, please try again later.", totalRunningTaskCount, highestRunningTaskCount, TOO_MANY_STAGES_MESSAGE))); queriesKilledDueToTooManyTask.incrementAndGet(); } }
Source:
public Optional<String> getCountryCode(String wktLocation, int radius) throws GeoEntryQueryException, ParseException { String countryCode = null; try (final Directory directory = openDirectoryAndCheckForIndex()) { Shape shape = getShape(wktLocation); countryCode = doGetCountryCode(shape, radius, directory); } catch (IOException e) { LOGGER.warn("Could not get directory"); } catch (ParseException e) { LOGGER.warn("Could not get shape from {}", wktLocation); } return Optional.ofNullable(countryCode); }

Target:
public Optional<String> getCountryCode(String wktLocation, int radius) throws GeoEntryQueryException { String countryCode = null; try (final Directory directory = openDirectoryAndCheckForIndex()) { Shape shape = getShape(wktLocation); countryCode = doGetCountryCode(shape, radius, directory); } catch (IOException e) { LOGGER.warn("Could not get directory"); } catch (ParseException e) { LOGGER.warn("Could not get shape from {}", wktLocation); } return Optional.ofNullable(countryCode); }
Source:
public void CompletePcapPacketTest() throws IOException, BadPcapFileException, BadPacketException { PcapTestTrace trace = PcapTestTrace.MOSTLY_UDP; assumeTrue(trace.exists()); PcapFile file = trace.getTrace(); file.seekPacket(36); PcapPacket packet = file.parseNextPacket(); if (packet == null) { fail("CompletePcapPacketTest has failed!"); return; } assertEquals(PcapProtocol.PCAP, packet.getProtocol()); assertTrue(packet.hasProtocol(PcapProtocol.PCAP)); assertTrue(packet.hasProtocol(PcapProtocol.UNKNOWN)); assertFalse(packet.hasProtocol(PcapProtocol.TCP)); assertTrue(packet.validate()); assertEquals(86567859, packet.hashCode()); assertFalse(packet.equals(null)); assertFalse(packet.equals(file.parseNextPacket())); assertEquals(EXPECTED_FIELDS, packet.getFields()); assertEquals(EXPECTED_TOSTRING, packet.toString()); assertEquals("Frame 36: 75 bytes on wire, 75 bytes captured", packet.getLocalSummaryString()); assertEquals("Source Port: 2719, Destination Port: 53", packet.getGlobalSummaryString()); assertEquals(new PcapEndpoint(packet, true), packet.getSourceEndpoint()); assertEquals(new PcapEndpoint(packet, false), packet.getDestinationEndpoint()); ByteBuffer payload = packet.getPayload(); if (payload == null) { fail("CompletePcapPacketTest has failed!"); return; } assertEquals(fPayload, payload.flip()); assertEquals(36, packet.getIndex()); assertEquals(75, packet.getOriginalLength()); assertEquals(75, packet.getIncludedLength()); assertEquals(1120469632829277L, packet.getTimestamp()); assertFalse(packet.isTruncated()); }

Target:
public void CompletePcapPacketTest() throws IOException, BadPcapFileException, BadPacketException { PcapTestTrace trace = PcapTestTrace.MOSTLY_UDP; assumeTrue(trace.exists()); try (PcapFile file = trace.getTrace();) { file.seekPacket(36); PcapPacket packet = file.parseNextPacket(); if (packet == null) { fail("CompletePcapPacketTest has failed!"); return; } assertEquals(PcapProtocol.PCAP, packet.getProtocol()); assertTrue(packet.hasProtocol(PcapProtocol.PCAP)); assertTrue(packet.hasProtocol(PcapProtocol.UNKNOWN)); assertFalse(packet.hasProtocol(PcapProtocol.TCP)); assertTrue(packet.validate()); assertEquals(86567859, packet.hashCode()); assertFalse(packet.equals(null)); assertFalse(packet.equals(file.parseNextPacket())); assertEquals(EXPECTED_FIELDS, packet.getFields()); assertEquals(EXPECTED_TOSTRING, packet.toString()); assertEquals("Frame 36: 75 bytes on wire, 75 bytes captured", packet.getLocalSummaryString()); assertEquals("Source Port: 2719, Destination Port: 53", packet.getGlobalSummaryString()); assertEquals(new PcapEndpoint(packet, true), packet.getSourceEndpoint()); assertEquals(new PcapEndpoint(packet, false), packet.getDestinationEndpoint()); ByteBuffer payload = packet.getPayload(); if (payload == null) { fail("CompletePcapPacketTest has failed!"); return; } assertEquals(fPayload, payload.flip()); assertEquals(36, packet.getIndex()); assertEquals(75, packet.getOriginalLength()); assertEquals(75, packet.getIncludedLength()); assertEquals(1120469632829277L, packet.getTimestamp()); assertFalse(packet.isTruncated()); } }
Source:
public void dispose() { super.dispose(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fListener); }

Target:
public void dispose() { super.dispose(); ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fPartListener); }
Source:
public List<VmNumaNode> getAllPinnedVmNumaNodeByVdsNumaNodeId(Guid vdsNumaNodeId) { List<VmNumaNode> vmNumaNodes = multipleResults(entityManager.createNativeQuery("select * from GetVmNumaNodeByVdsNumaNodeIdWithPinnedInfo(CAST( CAST (? AS text) AS uuid),?)", VmNumaNode.class) .setParameter(1, vdsNumaNodeId.toString()) .setParameter(2, true)); return vmNumaNodes; }

Target:
public List<VmNumaNode> getAllPinnedVmNumaNodeByVdsNumaNodeId(Guid vdsNumaNodeId) { List<VmNumaNode> vmNumaNodes = multipleResults(entityManager.createNativeQuery("select * " + "from GetVmNumaNodeByVdsNumaNodeIdWithPinnedInfo(CAST( CAST (? AS text) AS uuid),?)", VmNumaNode.class) .setParameter(1, vdsNumaNodeId.toString()) .setParameter(2, true)); return vmNumaNodes; }
Source:
private void showDeletePageOnboarding() { FeedbackUtil.makeSnackbar(getView(), getString(R.string.reading_lists_onboarding_page_delete), Snackbar.LENGTH_INDEFINITE) .setAction(R.string.reading_lists_onboarding_got_it, new View.OnClickListener() { @Override public void onClick(View v) { } }).show(); Prefs.setReadingListPageDeleteTutorialEnabled(false); }

Target:
private void showDeletePageOnboarding() { FeedbackUtil.makeSnackbar(getView(), getString(R.string.reading_lists_onboarding_page_delete), Snackbar.LENGTH_INDEFINITE) .setAction(R.string.reading_lists_onboarding_got_it, new View.OnClickListener() { @Override public void onClick(View v) { Prefs.setReadingListPageDeleteTutorialEnabled(false); } }).show(); }
Source:
public RemoteFilesList getRemoteFilesList(String capabilityListUri, String authString) throws IOException, CantRetrieveFileException { List<UrlItem> capabilityList = getRsFile(capabilityListUri, authString).getItemList(); List<RemoteFile> changes = new ArrayList<>(); List<RemoteFile> resources = new ArrayList<>(); for (UrlItem capabilityListItem : capabilityList) { if (capabilityListItem.getMetadata().getCapability().equals(Capability.CHANGELIST.getXmlValue())) { UrlSet rsFile = getRsFile(capabilityListItem.getLoc(), authString); String changeListExtension = ".*.nqud"; for (UrlItem changeListItem : rsFile.getItemList()) { if (changeListItem.getMetadata().getMimeType().equals(MIME_TYPE_FOR_EXTENSION.get(changeListExtension)) || changeListItem.getLoc().matches(changeListExtension)) { RemoteFile remoteFile = getRemoteFile(new Tuple<>(changeListItem.getLoc(), changeListItem.getMetadata()), authString); changes.add(remoteFile); } } } else if (capabilityListItem.getMetadata().getCapability().equals(Capability.RESOURCELIST.getXmlValue())) { UrlSet rsFile = getRsFile(capabilityListItem.getLoc(), authString); for (UrlItem resourceListItem : rsFile.getItemList()) { if (MIME_TYPE_FOR_EXTENSION.values().contains(resourceListItem.getMetadata().getMimeType()) || RdfExtensions.createFromFile(resourceListItem.getLoc()) != null) { resources.add(getRemoteFile(new Tuple<>(resourceListItem.getLoc(), resourceListItem.getMetadata()), authString)); } } } } return new RemoteFilesList(changes, resources); }

Target:
public RemoteFilesList getRemoteFilesList(String capabilityListUri, String authString) throws IOException, CantRetrieveFileException { List<UrlItem> capabilityList = getRsFile(capabilityListUri, authString).getItemList(); List<RemoteFile> changes = new ArrayList<>(); List<RemoteFile> resources = new ArrayList<>(); for (UrlItem capabilityListItem : capabilityList) { if (capabilityListItem.getMetadata().getCapability().equals(Capability.CHANGELIST.getXmlValue())) { UrlSet rsFile = getRsFile(capabilityListItem.getLoc(), authString); String changeListExtension = ".*.nqud"; for (UrlItem changeListItem : rsFile.getItemList()) { if (changeListItem.getMetadata().getMimeType().equals(MIME_TYPE_FOR_EXTENSION.get("nqud")) || changeListItem.getLoc().matches(changeListExtension)) { RemoteFile remoteFile = getRemoteFile(new Tuple<>(changeListItem.getLoc(), changeListItem.getMetadata()), authString); changes.add(remoteFile); } } } else if (capabilityListItem.getMetadata().getCapability().equals(Capability.RESOURCELIST.getXmlValue())) { UrlSet rsFile = getRsFile(capabilityListItem.getLoc(), authString); for (UrlItem resourceListItem : rsFile.getItemList()) { if (MIME_TYPE_FOR_EXTENSION.values().contains(resourceListItem.getMetadata().getMimeType()) || RdfExtensions.createFromFile(resourceListItem.getLoc()) != null) { resources.add(getRemoteFile(new Tuple<>(resourceListItem.getLoc(), resourceListItem.getMetadata()), authString)); } } } } return new RemoteFilesList(changes, resources); }
Source:
public static void addCast(IItemStack output, IIngredient[][] ingredients, int fluidInput, @Optional IItemStack plan) { FluidStack fluid = FluidRegistry.getFluidStack("glass", fluidInput); if (fluid == null){ LogHelper.logWarning("Liquid Class is null for the Thermionic Fabricator"); return; } ShapedRecipeCustom patternRecipe = new ShapedRecipeCustom(toStack(output), MTInputHelper.toShapedObjects(ingredients)); NonNullList<NonNullList<ItemStack>> ingredientsList = patternRecipe.getRawIngredients(); IFabricatorRecipe recipe = new FabricatorRecipe(toStack(plan), fluid, toStack(output), ingredientsList, patternRecipe.getOreDicts(), patternRecipe.getWidth(), patternRecipe.getHeight()); ModTweaker.LATE_ADDITIONS.add(new AddCast(recipe)); }

Target:
public static void addCast(IItemStack output, IIngredient[][] ingredients, int fluidInput, @Optional IItemStack plan) { FluidStack fluid = FluidRegistry.getFluidStack("glass", fluidInput); if (fluid == null){ LogHelper.logWarning("Liquid Glass is null for the Thermionic Fabricator"); return; } ShapedRecipeCustom patternRecipe = new ShapedRecipeCustom(toStack(output), toShapedObjects(ingredients)); NonNullList<NonNullList<ItemStack>> ingredientsList = patternRecipe.getRawIngredients(); IFabricatorRecipe recipe = new FabricatorRecipe(toStack(plan), fluid, toStack(output), ingredientsList, patternRecipe.getOreDicts(), patternRecipe.getWidth(), patternRecipe.getHeight()); ModTweaker.LATE_ADDITIONS.add(new AddCast(recipe)); }
Source:
public MethodNode deepResolveMethod(@NotNull MethodInfo mth) { ClassNode cls = resolveClass(mth.getDeclClass()); if (cls == null) { return null; } MethodNode resolved; DexNode declDex = cls.dex(); resolved = declDex.deepResolveMethod(cls, mth); if (resolved != null){ return resolved; } for (DexNode dexNode : dexNodes) { if(dexNodes == declDex) { continue; } resolved = dexNode.deepResolveMethod(cls, mth); if (resolved != null){ return resolved; } } return null; }

Target:
public MethodNode deepResolveMethod(@NotNull MethodInfo mth) { ClassNode cls = resolveClass(mth.getDeclClass()); if (cls == null) { return null; } return cls.dex().deepResolveMethod(cls, mth.makeSignature(false)); }
Source:
public ThrottleJobProperty(Integer maxConcurrentPerNode, Integer maxConcurrentTotal, List<String> categories, boolean throttleEnabled, String throttleOption, boolean limitOneJobWithMatchingParams, String paramsToUseForLimit, @CheckForNull ThrottleMatrixProjectOptions matrixOptions ) { this.maxConcurrentPerNode = maxConcurrentPerNode == null ? 0 : maxConcurrentPerNode; this.maxConcurrentTotal = maxConcurrentTotal == null ? 0 : maxConcurrentTotal; this.categories = categories == null ? new CopyOnWriteArrayList<String>() : new CopyOnWriteArrayList<String>(categories); this.throttleEnabled = throttleEnabled; this.throttleOption = throttleOption; this.limitOneJobWithMatchingParams = limitOneJobWithMatchingParams; this.matrixOptions = matrixOptions; this.paramsToUseForLimit = paramsToUseForLimit; if ((this.paramsToUseForLimit != null)) { if ((this.paramsToUseForLimit.length() > 0)) { this.paramsToCompare = Arrays.asList(this.paramsToUseForLimit.split(",")); } else { this.paramsToCompare = new ArrayList<String>(); } } else { this.paramsToCompare = new ArrayList<String>(); } }

Target:
public ThrottleJobProperty(Integer maxConcurrentPerNode, Integer maxConcurrentTotal, List<String> categories, boolean throttleEnabled, String throttleOption, boolean limitOneJobWithMatchingParams, String paramsToUseForLimit, @CheckForNull ThrottleMatrixProjectOptions matrixOptions ) { this.maxConcurrentPerNode = maxConcurrentPerNode == null ? 0 : maxConcurrentPerNode; this.maxConcurrentTotal = maxConcurrentTotal == null ? 0 : maxConcurrentTotal; this.categories = categories == null ? new CopyOnWriteArrayList<String>() : new CopyOnWriteArrayList<String>(categories); this.throttleEnabled = throttleEnabled; this.throttleOption = throttleOption; this.limitOneJobWithMatchingParams = limitOneJobWithMatchingParams; this.matrixOptions = matrixOptions; this.paramsToUseForLimit = paramsToUseForLimit; if ((this.paramsToUseForLimit != null)) { if ((this.paramsToUseForLimit.length() > 0)) { this.paramsToCompare = Arrays.asList(ArrayUtils.nullToEmpty(StringUtils.split(this.paramsToUseForLimit))); } else { this.paramsToCompare = new ArrayList<String>(); } } else { this.paramsToCompare = new ArrayList<String>(); } }
Source:
public List<DMNRuntimeEventListener> getListeners() { List<DMNRuntimeEventListener> results = new ArrayList<>(); if (knowledgeBase != null && knowledgeBase instanceof KnowledgeBaseImpl) { KnowledgeBaseImpl knowledgeBaseImpl = (KnowledgeBaseImpl) knowledgeBase; KieContainerImpl kieContainer = (KieContainerImpl) knowledgeBaseImpl.getKieContainer(); if (kieContainer != null) { KieBaseModelImpl kieBaseModel = (KieBaseModelImpl) kieContainer.getKieProject().getKieBaseModel(knowledgeBase.getId()); for (Entry<String, String> kv : kieBaseModel.getKModule().getConfigurationProperties().entrySet()) { String k = kv.getKey(); if (k != null && k.startsWith(DMNAssemblerService.DMN_RUNTIME_LISTENER_PREFIX)) { if (ClassLoaderUtil.CAN_PLATFORM_CLASSLOAD) { try { DMNRuntimeEventListener runtimeListenerInstance = (DMNRuntimeEventListener) knowledgeBase.getRootClassLoader().loadClass(kv.getValue()).newInstance(); results.add(runtimeListenerInstance); } catch (Exception e) { logger.error("Cannot perform classloading of runtime listener: {}", kv, e); } } else { logger.error("This platform does not support classloading of runtime listener: {}", kv); } } } } } else { logger.warn("No DMNRuntime Listener can be provided, as created without a reference to KnowledgeBase"); } return results; }

Target:
public List<DMNRuntimeEventListener> getListeners() { if (knowledgeBase != null && knowledgeBase instanceof KnowledgeBaseImpl && ((KnowledgeBaseImpl) knowledgeBase).getKieContainer() instanceof KieContainerImpl) { KieBaseModelImpl kieBaseModel = (KieBaseModelImpl) ((KieContainerImpl) ((KnowledgeBaseImpl) knowledgeBase).getKieContainer()).getKieProject().getKieBaseModel(knowledgeBase.getId()); return kieBaseModel.getKModule().getConfigurationProperties().entrySet().stream() .filter(kv -> kv.getKey() != null && kv.getKey().startsWith(DMNAssemblerService.DMN_RUNTIME_LISTENER_PREFIX)) .map(Entry::getValue) .map(this::loadEventListener) .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) .collect(Collectors.toList()); } else { logger.warn("No DMNRuntime Listener can be provided, as created without a reference to KnowledgeBase"); } return Collections.emptyList(); }