auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void dismissLoadingDialog() { Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG); if (frag != null) { Log_OC.d(TAG, "dismiss loading dialog"); LoadingDialog loading = (LoadingDialog) frag; <START> loading.dismiss(); <END> } }</code><technical_language>refactor this? Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG); if (frag == null) return; Log_OC.d(TAG, "dismiss loading dialog"); LoadingDialog loading = (LoadingDialog) frag; loading.dismiss();</technical_language>

Target:
public void dismissLoadingDialog() { Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_TAG); if (frag == null) { return; } Log_OC.d(TAG, "dismiss loading dialog"); LoadingDialog loading = (LoadingDialog) frag; loading.dismiss(); }
Source:
<code>protected Collection<IAction> getActions() { <START> if (historyPage.getCurrentRepo() == null) <END> return new ArrayList<>(); RefFilterHelper helper = historyPage.helper; List<IAction> actions = new ArrayList<>(); actions.add(configureFiltersAction); Set<RefFilter> filters = helper.getRefFilters(); List<RefFilter> sortedFilters = new ArrayList<>( filters); sortedFilters.sort(new Comparator<RefFilter>() { private int category(RefFilter filter) { if (filter.isPreconfigured()) return 100; return 1000; } @Override public int compare(RefFilter o1, RefFilter o2) { int cat1 = category(o1); int cat2 = category(o2); if (cat1 != cat2) { return cat1 - cat2; } String name1 = o1.getFilterString(); String name2 = o2.getFilterString(); return name1.compareTo(name2); } }); for (RefFilter filter : sortedFilters) { Action action = new ShownRefAction(filter, () -> { helper.setRefFilters(filters); historyPage.refresh(); }); actions.add(action); } return actions; }</code><technical_language>nit: missing braces</technical_language>

Target:
protected Collection<IAction> getActions() { if (historyPage.getCurrentRepo() == null) { return new ArrayList<>(); } RefFilterHelper helper = historyPage.helper; List<IAction> actions = new ArrayList<>(); actions.add(configureFiltersAction); Set<RefFilter> filters = helper.getRefFilters(); List<RefFilter> sortedFilters = new ArrayList<>( filters); sortedFilters.sort(new Comparator<RefFilter>() { private int category(RefFilter filter) { if (filter.isPreconfigured()) { return 100; } return 1000; } @Override public int compare(RefFilter o1, RefFilter o2) { int cat1 = category(o1); int cat2 = category(o2); if (cat1 != cat2) { return cat1 - cat2; } String name1 = o1.getFilterString(); String name2 = o2.getFilterString(); return name1.compareTo(name2); } }); for (RefFilter filter : sortedFilters) { Action action = new ShownRefAction(filter, () -> { helper.setRefFilters(filters); historyPage.refresh(); }); actions.add(action); } return actions; }
Source:
<code>public boolean validate() { getNetwork().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); getBond().validateSelectedItem(new IValidation[] { new NotEmptyValidation(), new LengthValidation(BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH), new BondNameValidation() }); getAddress().setIsValid(true); getSubnet().setIsValid(true); getGateway().setIsValid(true); if (getIsStaticAddress()) { getAddress().validateEntity(new IValidation[] { new NotEmptyValidation(), new IpAddressValidation() }); getSubnet().validateEntity(new IValidation[] { new NotEmptyValidation(), new SubnetMaskValidation() }); getGateway().validateEntity(new IValidation[] { new NotEmptyValidation(), new IpAddressValidation() }); } final String customEditorParameter = " Custom mode "; if (getBondingOptions().getSelectedItem().getKey().equals("custom")) { <START> getCustomEditor().validateEntity(new IValidation[] { new NotEmptyValidation(), <END> new KeyValueFormatValidation((customEditorParameter)) }); } return getBond().getIsValid() && getNetwork().getIsValid() && getAddress().getIsValid() && getSubnet().getIsValid() && getGateway().getIsValid() && getCustomEditor().getIsValid(); }</code><technical_language><LINK_0> line #9 (maybe need 'NotEmptyValidation')- important</technical_language>

Target:
public boolean validate() { getNetwork().validateSelectedItem(new IValidation[] { new NotEmptyValidation() }); getBond().validateSelectedItem(new IValidation[] { new NotEmptyValidation(), new LengthValidation(BusinessEntitiesDefinitions.HOST_NIC_NAME_LENGTH), new BondNameValidation() }); getAddress().setIsValid(true); getSubnet().setIsValid(true); getGateway().setIsValid(true); if (getIsStaticAddress()) { getAddress().validateEntity(new IValidation[] { new NotEmptyValidation(), new IpAddressValidation() }); getSubnet().validateEntity(new IValidation[] { new NotEmptyValidation(), new SubnetMaskValidation() }); getGateway().validateEntity(new IValidation[] { new NotEmptyValidation(), new IpAddressValidation() }); } if (getBondingOptions().getSelectedItem().getKey().equals(CUSTOM_BONDING_MODE)) { getCustomBondMode().validateEntity(new IValidation[] { new NotEmptyValidation(), new KeyValueFormatValidation(constantsManager) }); } return getBond().getIsValid() && getNetwork().getIsValid() && getAddress().getIsValid() && getSubnet().getIsValid() && getGateway().getIsValid() && getCustomBondMode().getIsValid(); }
Source:
<code><START> public static void main(String[] args) throws InterruptedException { <END> Microservices gateway = Microservices.builder() .discovery(serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint)) .transport(ServiceTransports::rsocketServiceTransport) .gateway(opt -> new WebsocketGateway(opt.id("ws").port(8080))) .gateway(opt -> new HttpGateway(opt.id("http").port(8181)).corsEnabled(true)) .startAwait(); Address seedAddress = Address.create(gateway.discovery().address().host(), gateway.discovery().address().port()); Microservices.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) .options(opts -> opts.seedMembers(seedAddress))) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); GreetingsService service = gateway.call().api(GreetingsService.class); service .sayHello("joe") .subscribe( consumer -> { System.out.println(consumer.message()); }); Thread.currentThread().join(); }</code><technical_language>Remove throws InterruptedException</technical_language>

Target:
public static void main(String[] args) { Microservices gateway = Microservices.builder() .discovery(serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint)) .transport(ServiceTransports::rsocketServiceTransport) .gateway(opt -> new WebsocketGateway(opt.id("ws").port(8080))) .gateway(opt -> new HttpGateway(opt.id("http").port(8181)).corsEnabled(true)) .startAwait(); Address seedAddress = Address.create(gateway.discovery().address().host(), gateway.discovery().address().port()); Microservices ms = Microservices.builder() .discovery( serviceEndpoint -> new ScalecubeServiceDiscovery(serviceEndpoint) .options(opts -> opts.seedMembers(seedAddress))) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); GreetingsService service = gateway.call().api(GreetingsService.class); service .sayHello("joe") .subscribe( consumer -> { System.out.println(consumer.message()); }); gateway.onShutdown().block(); ms.onShutdown().block(); }
Source:
<code>private void operationExecuted(MatchingFrame frame) { <START> if (!adapters.isEmpty()) for <END> (ILocalSearchAdapter adapter : adapters) { adapter.operationExecuted(this, frame); } }</code><technical_language>For readability reasons, please add braces</technical_language>

Target:
private void operationExecuted(MatchingFrame frame) { if (!adapters.isEmpty()){ for (ILocalSearchAdapter adapter : adapters) { adapter.operationExecuted(this, frame); } } }
Source:
<code>public void getTaskData(Set<String> taskIds, TaskRepository taskRepository, TaskDataCollector collector, IOperationMonitor monitor) throws BugzillaRestException { BugzillaRestConfiguration config; try { config = connector.getRepositoryConfiguration(taskRepository); } catch (CoreException e1) { throw new BugzillaRestException(e1); } Iterable<String> taskIdsTemp = Iterables.transform(taskIds, function); Iterable<List<String>> partitions = Iterables.partition(taskIdsTemp, MAX_RETRIEVED_PER_QUERY); for (List<String> list : partitions) { Joiner joiner = Joiner.on(",id=").skipNulls(); String urlIDList = "id=" + joiner.join(list); try { List<TaskData> taskDataArray = new BugzillaRestGetTaskData(client, connector, urlIDList, taskRepository) .run(monitor); for (TaskData taskData : taskDataArray) { new BugzillaRestGetTaskComments(getClient(), taskData).run(monitor); new BugzillaRestGetTaskAttachments(getClient(), taskData).run(monitor); config.updateProductOptions(taskData); config.addValidOperations(taskData); collector.accept(taskData); } <START> } catch (BugzillaRestException e) { <END> throw e; } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof CoreException) { throw new BugzillaRestException(cause); } throw e; } } }</code><technical_language>need this catch</technical_language>

Target:
public void getTaskData(Set<String> taskIds, TaskRepository taskRepository, TaskDataCollector collector, IOperationMonitor monitor) throws BugzillaRestException { BugzillaRestConfiguration config; try { config = connector.getRepositoryConfiguration(taskRepository); } catch (CoreException e1) { throw new BugzillaRestException(e1); } Iterable<String> taskIdsTemp = Iterables.transform(taskIds, removeLeadingZero); Iterable<List<String>> partitions = Iterables.partition(taskIdsTemp, MAX_RETRIEVED_PER_QUERY); for (List<String> list : partitions) { Joiner joiner = Joiner.on(",id=").skipNulls(); String urlIDList = "id=" + joiner.join(list); try { List<TaskData> taskDataArray = new BugzillaRestGetTaskData(client, connector, urlIDList, taskRepository) .run(monitor); for (TaskData taskData : taskDataArray) { new BugzillaRestGetTaskComments(getClient(), taskData).run(monitor); new BugzillaRestGetTaskAttachments(getClient(), taskData).run(monitor); config.updateProductOptions(taskData); config.addValidOperations(taskData); collector.accept(taskData); } } catch (RuntimeException e) { Throwable cause = e.getCause(); if (cause instanceof CoreException) { throw new BugzillaRestException(cause); } throw e; } } }
Source:
<code>private boolean isValidIpOrRange(String entry) { if (TextUtils.isEmpty(entry)) { return false; } entry = entry.trim(); <START> entry = entry.replaceAll(" ", ""); <END> String[] ipStrings = entry.split("-"); if (ipStrings.length > 2 || ipStrings.length < 1) { return false; } for (String ip : ipStrings) { if (!InetAddressUtils.isIPv4Address(ip)) { return false; } } return true; }</code><technical_language>entry.trim() do this</technical_language>

Target:
private boolean isValidIpOrRange(String entry) { if (TextUtils.isEmpty(entry)) { return false; } entry = entry.replaceAll("\\s", ""); String[] ipStrings = entry.split("-"); if (ipStrings.length > 2 || ipStrings.length < 1) { return false; } for (String ip : ipStrings) { if (!InetAddressUtils.isIPv4Address(ip)) { return false; } } return true; }
Source:
<code>public void broadcastObject(final Object object) { executorsBySession.forEach((session, executor) -> executor.submit(() -> { <START> while (true) { <END> LOGGER.debug("Sending notification to session with id: {}, open: {}", session.getId(), session.isOpen()); try { if (session.isOpen()) { session.getBasicRemote().sendObject(object); LOGGER.debug("Notification sent to session with id: {}", session.getId()); } break; } catch (IOException | EncodeException ex) { LOGGER.warn("Failed to send notification, error: {}", ex.getMessage(), ex); Thread.sleep(500); } } return null; })); }</code><technical_language>sense limit broadcast attempts? in case of some exception executor stuck here</technical_language>

Target:
public void broadcastObject(final Object object) { executorsBySession.forEach((session, executor) -> executor.submit(() -> { for (int i = 0; i < RETRIES; i++) { LOGGER.debug("Sending notification to session with id: {}, open: {}", session.getId(), session.isOpen()); try { if (session.isOpen()) { session.getBasicRemote().sendObject(object); LOGGER.debug("Notification sent to session with id: {}", session.getId()); } else { LOGGER.debug("Notification not sent, session is closed."); } break; } catch (EncodeException ex) { LOGGER.warn("Failed to send notification, due to encoding error: {}, skipping message", ex.getMessage(), ex); break; } catch (IOException ex) { LOGGER.warn("Failed to send notification, error: {}", ex.getMessage(), ex); Thread.sleep(i * 500); } } return null; })); }
Source:
<code>public boolean isFinished() { <START> return blocked.isDone() && state == State.FINISHED; <END> }</code><technical_language>nit: reverse (as originally): state == State.FINISHED && .. -- do cheaper</technical_language>

Target:
public boolean isFinished() { return state == State.FINISHED && blocked.isDone(); }
Source:
<code>public void systemIterateReader() { String ionText = "1 2 3 4"; IonReader ionReader = system().newSystemReader(ionText); Iterator<IonValue> iterate = system().systemIterate(ionReader); assertTrue(iterate.hasNext()); assertEquals(1, ((IonInt) iterate.next()).intValue()); assertTrue(iterate.hasNext()); assertEquals(2, ((IonInt) iterate.next()).intValue()); assertTrue(iterate.hasNext()); assertEquals(3, ((IonInt) iterate.next()).intValue()); assertTrue(iterate.hasNext()); assertEquals(4, ((IonInt) iterate.next()).intValue()); assertFalse(iterate.hasNext()); <START> } <END></code><technical_language>ionReader.close() ? (not necessary, if this is right habit, follow it)</technical_language>

Target:
public void systemIterateReader() throws IOException { String ionText = "1 2 3 4"; IonReader ionReader = system().newSystemReader(ionText); Iterator<IonValue> iterate = system().systemIterate(ionReader); assertTrue(iterate.hasNext()); assertEquals(1, ((IonInt) iterate.next()).intValue()); assertTrue(iterate.hasNext()); assertEquals(2, ((IonInt) iterate.next()).intValue()); assertTrue(iterate.hasNext()); assertEquals(3, ((IonInt) iterate.next()).intValue()); assertTrue(iterate.hasNext()); assertEquals(4, ((IonInt) iterate.next()).intValue()); assertFalse(iterate.hasNext()); ionReader.close(); }
Source:
<code>public void processTuple(String inputTuple) { try { if (out.isConnected()) { reader.open(inputTuple); JAXBElement<?> output = unmarshaller.unmarshal(new StreamSource(reader), getClazz()); LOG.debug(output.getValue().toString()); emittedObjectCount++; out.emit(output.getValue()); } else if (validator != null) { validator.validate(new StreamSource(inputTuple)); } if (parsedOutput.isConnected()) { <START> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); <END> DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new ByteArrayInputStream(inputTuple.getBytes("utf-8")))); parsedOutput.emit(doc); } catch (Exception e) { LOG.info("Failed to parse xml tuple {}, Exception = , StackTrace = {}", inputTuple, e, e.getStackTrace()); errorTupleCount++; if (err.isConnected()) { err.emit(inputTuple); } } } } catch (Exception e) { LOG.info("Failed to parse xml tuple {}, Exception = {}, StackTrace = ", inputTuple, e, e.getStackTrace()); errorTupleCount++; if (err.isConnected()) { err.emit(inputTuple); } } finally { try { if (reader.isOpen()) { reader.close(); } } catch (IOException e) { DTThrowable.wrapIfChecked(e); } } }</code><technical_language>unnecessary</technical_language>

Target:
public void processTuple(String inputTuple) { try { if (out.isConnected()) { reader.open(inputTuple); JAXBElement<?> output = unmarshaller.unmarshal(new StreamSource(reader), getClazz()); LOG.debug(output.getValue().toString()); emittedObjectCount++; out.emit(output.getValue()); } else if (validator != null) { validator.validate(new StreamSource(inputTuple)); } if (parsedOutput.isConnected()) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new ByteArrayInputStream(inputTuple.getBytes("UTF-8")))); parsedOutput.emit(doc); } catch (Exception e) { LOG.info("Failed to parse xml tuple {}, Exception = , StackTrace = {}", inputTuple, e, e.getStackTrace()); errorTupleCount++; if (err.isConnected()) { err.emit(inputTuple); } } } } catch (Exception e) { LOG.info("Failed to parse xml tuple {}, Exception = {}, StackTrace = ", inputTuple, e, e.getStackTrace()); errorTupleCount++; if (err.isConnected()) { err.emit(inputTuple); } } finally { try { if (reader.isOpen()) { reader.close(); } } catch (IOException e) { DTThrowable.wrapIfChecked(e); } } }
Source:
<code>public CatalogClasspathDo(CatalogDo catalog) { <START> this.catalog = catalog; <END> this.classpath = catalog.dto.classpath; }</code><technical_language>final checkNotNull(catalog, "catalog")</technical_language>

Target:
public CatalogClasspathDo(CatalogDo catalog) { this.catalog = Preconditions.checkNotNull(catalog, "catalog"); this.classpath = catalog.dto.classpath; this.scanMode = (classpath != null) ? classpath.scan : null; }
Source:
<code>private boolean canRestoreVmConfigFromSnapshot() { Snapshot snapshot = getSnapshot(); return snapshot.getType() == SnapshotType.PREVIEW || <START> snapshot.getType() == SnapshotType.STATELESS ? <END> getSnapshotsManager().canRestoreVmConfigurationFromSnapshot(getVm(), snapshot, new VmInterfaceManager(getMacPool())) : true; }</code><technical_language>case - system is able restore previous state of a stateless vm</technical_language>

Target:
private boolean canRestoreVmConfigFromSnapshot() { Snapshot snapshot = getSnapshot(); return snapshot.getType() == SnapshotType.PREVIEW ? getSnapshotsManager().canRestoreVmConfigurationFromSnapshot(getVm(), snapshot, new VmInterfaceManager(getMacPool())) : true; }
Source:
<code><START> public static void setup() { <END> grobidService = new GrobidService(JabRefPreferences.getInstance()); }</code><technical_language>Please tag this a FetcherTest (because relies network connection)</technical_language>

Target:
public static void setup() { grobidService = new GrobidService("<LINK_0>"); }
Source:
<code>public static void initializeDefaults(IPreferenceStore store) { boolean[] highContrast = new boolean[] { false }; try { <START> Display.getDefault().syncExec(() -> { <END> try { highContrast[0] = Display.getDefault().getHighContrast(); } catch (SWTException e) { } }); } catch (SWTException e) { } PreferenceConverter.setDefault(store, P_DEFAULT, highContrast[0] ? DEFAULT_HIGH_CONTRAST : DEFAULT); PreferenceConverter.setDefault(store, P_PROC_INSTR, PROC_INSTR); PreferenceConverter.setDefault(store, P_STRING, STRING); PreferenceConverter.setDefault(store, P_EXTERNALIZED_STRING, EXTERNALIZED_STRING); PreferenceConverter.setDefault(store, P_TAG, TAG); PreferenceConverter.setDefault(store, P_XML_COMMENT, XML_COMMENT); PreferenceConverter.setDefault(store, P_HEADER_KEY, HEADER_KEY); PreferenceConverter.setDefault(store, P_HEADER_OSGI, HEADER_OSGI); store.setDefault(P_HEADER_OSGI + IPDEColorConstants.P_BOLD_SUFFIX, true); PreferenceConverter.setDefault(store, P_HEADER_VALUE, highContrast[0] ? HEADER_VALUE_HIGH_CONTRAST : HEADER_VALUE); PreferenceConverter.setDefault(store, P_HEADER_ATTRIBUTES, highContrast[0] ? HEADER_ASSIGNMENT_HIGH_CONTRAST : HEADER_ATTRIBUTES); store.setDefault(P_HEADER_ATTRIBUTES + IPDEColorConstants.P_ITALIC_SUFFIX, true); PreferenceConverter.setDefault(store, P_HEADER_ASSIGNMENT, HEADER_ASSIGNMENT); }</code><technical_language>Please note this introduces a deadlock ui ui thread. Especially startup this dangerous</technical_language>

Target:
public static void initializeDefaults(IPreferenceStore store) { PreferenceConverter.setDefault(store, P_DEFAULT, DEFAULT); PreferenceConverter.setDefault(store, P_PROC_INSTR, PROC_INSTR); PreferenceConverter.setDefault(store, P_STRING, STRING); PreferenceConverter.setDefault(store, P_EXTERNALIZED_STRING, EXTERNALIZED_STRING); PreferenceConverter.setDefault(store, P_TAG, TAG); PreferenceConverter.setDefault(store, P_XML_COMMENT, XML_COMMENT); PreferenceConverter.setDefault(store, P_HEADER_KEY, HEADER_KEY); PreferenceConverter.setDefault(store, P_HEADER_OSGI, HEADER_OSGI); store.setDefault(P_HEADER_OSGI + IPDEColorConstants.P_BOLD_SUFFIX, true); PreferenceConverter.setDefault(store, P_HEADER_VALUE, HEADER_VALUE); PreferenceConverter.setDefault(store, P_HEADER_ATTRIBUTES, HEADER_ATTRIBUTES); store.setDefault(P_HEADER_ATTRIBUTES + IPDEColorConstants.P_ITALIC_SUFFIX, true); PreferenceConverter.setDefault(store, P_HEADER_ASSIGNMENT, HEADER_ASSIGNMENT); try { Display display = Display.getDefault(); Runnable runnable = () -> { if (!display.isDisposed() && display.getHighContrast()) { PreferenceConverter.setDefault(store, P_DEFAULT, DEFAULT_HIGH_CONTRAST); PreferenceConverter.setDefault(store, P_HEADER_VALUE, HEADER_VALUE_HIGH_CONTRAST); PreferenceConverter.setDefault(store, P_HEADER_ATTRIBUTES, HEADER_ASSIGNMENT_HIGH_CONTRAST); } }; if (display == Display.getCurrent()) { runnable.run(); } else { display.asyncExec(runnable); } } catch (SWTException e) { } }
Source:
<code>public void testBadIntegerReconnectAttempts() { udpOperation.get(ElytronDescriptionConstants.ICMP_ERROR_RECONNECT_ATTEMPTS).set(BAD_RECONNECT_NUMBER); ModelNode response = services.executeOperation(udpOperation); <START> assertCorrectError(response, BAD_RECONNECT_NUMBER + " is an invalid value for parameter icmp-error-reconnect-attempts. A minimum value of -1 is required"); <END> assertFailed(response); }</code><technical_language>above. message ID assume a failure is enough</technical_language>

Target:
public void testBadIntegerReconnectAttempts() { udpOperation.get(ElytronDescriptionConstants.RECONNECT_ATTEMPTS).set(BAD_RECONNECT_NUMBER); ModelNode response = services.executeOperation(udpOperation); assertCorrectError(response, new String[] {"WFLYCTL0117", Integer.toString(BAD_RECONNECT_NUMBER)}); assertFailed(response); }
Source:
<code>public Response upgrade(Action action) { UpgradeHostParameters params = new UpgradeHostParameters(guid); if (action.isSetImage()) { params.setoVirtIsoFile(action.getImage()); } if <START> (action.isReboot() <END> != null) { params.setReboot(action.isReboot()); } return doAction(ActionType.UpgradeHost, params, action); }</code><technical_language>This "isSetReboot". reason is want call backend method if user explicitly provide value, backend method side effects (very in this case)</technical_language>

Target:
public Response upgrade(Action action) { UpgradeHostParameters params = new UpgradeHostParameters(guid); if (action.isSetImage()) { params.setoVirtIsoFile(action.getImage()); } if (action.isSetReboot()) { params.setReboot(action.isReboot()); } return doAction(ActionType.UpgradeHost, params, action); }
Source:
<code>public void openPreNullWithRequired() throws IOException { configFactory.copyRealmFromAssets(context, "default-before-migration.realm", Realm.DEFAULT_REALM_NAME); <START> RealmMigration migration = new RealmMigration() { <END> @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { RealmSchema schema = realm.getSchema(); if (oldVersion == 0) { schema.get(AllTypes.CLASS_NAME) .addField(AllTypes.FIELD_BYTE, byte.class) .addField(AllTypes.FIELD_SHORT, short.class) .addField(AllTypes.FIELD_INT, int.class); oldVersion++; } } }; RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .schemaVersion(1) .schema(AllTypes.class) .migration(migration) .build(); Realm realm = Realm.getInstance(realmConfig); realm.beginTransaction(); try { AllTypes allTypes = realm.createObject(AllTypes.class); allTypes.setColumnString(null); fail(); } catch (IllegalArgumentException ignored) { } realm.cancelTransaction(); realm.close(); }</code><technical_language>is a bit annoy ... I is update default-before-migration.realm instead. This side effect test case test case confused ... YEAH, update binary file is annoy</technical_language>

Target:
public void openPreNullWithRequired() throws IOException { configFactory.copyRealmFromAssets(context, "default-before-migration.realm", Realm.DEFAULT_REALM_NAME); RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .schemaVersion(0) .schema(AllTypes.class) .build(); Realm realm = Realm.getInstance(realmConfig); realm.beginTransaction(); try { AllTypes allTypes = realm.createObject(AllTypes.class); allTypes.setColumnString(null); fail(); } catch (IllegalArgumentException ignored) { } realm.cancelTransaction(); realm.close(); }
Source:
<code>public void testXmlValidateValid() { <START> Activator plugin = Activator.getDefault(); <END> if (plugin == null) { throw new IllegalStateException(); } URL location = FileLocator.find(plugin.getBundle(), PATH_VALID, null); File file = null; try { IPath path = new Path(FileLocator.toFileURL(location).getPath()); file = path.toFile(); } catch (IOException e) { throw new IllegalStateException(); } File[] validFiles = file.listFiles(); for (File f : validFiles) { assertTrue("File " + f.getName(), XmlUtils.xmlValidate(f).isOK()); } }</code><technical_language>extract FileLocator part a common method? in another patch</technical_language>

Target:
public void testXmlValidateValid() { IPath path = getAbsolutePath(PATH_VALID); File file = path.toFile(); File[] validFiles = file.listFiles(); assertTrue(validFiles.length > 0); for (File f : validFiles) { assertTrue("File " + f.getName(), XmlUtils.xmlValidate(f).isOK()); } }
Source:
<code>public RegionBootstrap(final Context context, final MonitorNotifier monitorNotifier, List<Region> regions) { <START> if (context.getApplicationContext() == null) { <END> throw new NullPointerException("Application Context should not be null"); } beaconManager = BeaconManager.getInstanceForApplication(context.getApplicationContext()); this.context = context; this.monitorNotifier = monitorNotifier; this.monitorNotifier = new BootstrapNotifier() { public Context getApplicationContext() { return context.getApplicationContext(); } public void didEnterRegion(Region region) { monitorNotifier.didEnterRegion(region); } public void didExitRegion(Region region) { monitorNotifier.didExitRegion(region); } public void didDetermineStateForRegion(int state, Region region) { monitorNotifier.didDetermineStateForRegion(state, region); } }; this.regions = regions; beaconConsumer = new InternalBeaconConsumer(); beaconManager.bind(beaconConsumer); LogManager.d(TAG, "Waiting for BeaconService connection"); }</code><technical_language>a good idea check for context == null, is more case</technical_language>

Target:
public RegionBootstrap(final Context context, final MonitorNotifier monitorNotifier, List<Region> regions) { if (context == null) { throw new NullPointerException("Application Context should not be null"); } this.context = context.getApplicationContext(); this.monitorNotifier = monitorNotifier; this.monitorNotifier = new BootstrapNotifier() { public Context getApplicationContext() { return context.getApplicationContext(); } public void didEnterRegion(Region region) { monitorNotifier.didEnterRegion(region); } public void didExitRegion(Region region) { monitorNotifier.didExitRegion(region); } public void didDetermineStateForRegion(int state, Region region) { monitorNotifier.didDetermineStateForRegion(state, region); } }; this.regions = regions; beaconManager = BeaconManager.getInstanceForApplication(context); beaconConsumer = new InternalBeaconConsumer(); beaconManager.bind(beaconConsumer); LogManager.d(TAG, "Waiting for BeaconService connection"); }
Source:
<code>public void emptyGzip() { ObjectMapper om = Unirest.config().getObjectMapper(); ObjectMapper omWithNull = new ObjectMapper() { @Override public <T> T readValue(String value, Class<T> valueType) { return value == null || value.trim().isEmpty() ? null : om.readValue(value, valueType); } @Override public String writeValue(Object value) { return om.writeValue(value); } }; Unirest.config().setObjectMapper(omWithNull); HttpResponse<Map<?,?>> resp = Unirest.post(MockServer.EMPTY_GZIP) .header("Content-Type", "application/json") .accept( "application/json") .asObject(Map.class); Unirest.config().setObjectMapper(om); <START> assertFalse(resp.getParsingError().isPresent()); <END> }</code><technical_language>Thank for of tests! get missed. I appreciate it. I test conflates issues: 1. GZIP method bomb empty array 1. behavior of ObjectMapper presented null empty data. In reality, I expect JSON parser call if a null empty response parsed empty Map, is a issue I think. This test more clear if simply do a asString() I expect produce empty String (which is new String(new byte[0]) you). this simplified to: HttpResponse<String> result = Unirest.post(MockServer.EMPTY_GZIP) .header("Content-Type", "application/json") .accept( "application/json") .asString(); assertEquals("", result.getBody()); assertEquals(false, result.getParsingError().isPresent());</technical_language>

Target:
public void emptyGzip() { HttpResponse<String> result = Unirest.post(MockServer.EMPTY_GZIP) .asString(); assertFalse(result.getParsingError().isPresent()); assertEquals("", result.getBody()); }
Source:
<code>private void cleanupForMissingExecutor(Executor executor, List<ExecutableFlow> executions) { String finalizeReason = "Executor was unreachable, executor id: " + executor.getId(); finalizeFlows(executions, finalizeReason); try { <START> this.executorLoader.removeExecutor(executor.getHost(), executor.getPort()); <END> } catch (ExecutorManagerException ex) { logger.error(String.format("Attempt to remove executor %s failed with reason %s", executor.getId(), ex)); } }</code><technical_language>add a log line for removing executor adding reason? I looked removeExecutor log it</technical_language>

Target:
private void cleanupForMissingExecutor(Executor executor, List<ExecutableFlow> executions) { String finalizeReason = String.format("Executor was unreachable, executor-id: %s, executor-host: %s, " + "executor-port: %d", executor.getId(), executor.getHost(), executor.getPort()); finalizeFlows(executions, finalizeReason); }
Source:
<code>public void setAttributeOverrides(List<String> attributeOverrides) { Map<String, Serializable> attributeOverrideMap = new HashMap<>(); for (String s : attributeOverrides) { String[] keyValue = s.split("=", 2); if (keyValue.length < 2) { LOGGER.error("Invalid attribute override configured for monitored directory"); throw new IllegalStateException( "Invalid attribute override configured for monitored directory"); } <START> <END> attributeOverrideMap.computeIfAbsent(keyValue[0], k -> new ArrayList<String>()); ArrayList valueList = (ArrayList) attributeOverrideMap.get(keyValue[0]); valueList.add(keyValue[1]); } this.attributeOverrides = attributeOverrideMap; }</code><technical_language>attributeOverrideMap.putIfAbsent(keyValue[0], new ArrayList<String>());</technical_language>

Target:
public void setAttributeOverrides(List<String> attributeOverrides) { Map<String, Serializable> attributeOverrideMap = new HashMap<>(); for (String s : attributeOverrides) { String[] keyValue = s.split("=", 2); if (keyValue.length < 2) { LOGGER.error("Invalid attribute override configured for monitored directory"); throw new IllegalStateException( "Invalid attribute override configured for monitored directory"); } attributeOverrideMap.computeIfAbsent(keyValue[0], k -> new ArrayList<String>()); List valueList = (List) attributeOverrideMap.get(keyValue[0]); valueList.add(keyValue[1]); } this.attributeOverrides = attributeOverrideMap; }
Source:
<code>private static SerializableError createSerializableError(Exception exception) { <START> return SerializableError.of( <END> exception.getMessage(), exception.getClass()); }</code><technical_language>this drop stacktrace? I imagine want ship well</technical_language>

Target:
private static SerializableError createSerializableError(Exception exception) { return SerializableError.of( exception.getMessage(), exception.getClass(), getStackTraceElementsAsList(exception)); }
Source:
<code>private String getJarBackupFilename(String filename) { <START> Pattern jarFilenamePattern = Pattern.compile("^(.*)\\.(jar|JAR)$"); <END> Matcher jarFilenameMatcher = jarFilenamePattern.matcher(filename); if (!jarFilenameMatcher.find()) { return filename + BACKUP_FILENAME_SUFFIX; } return jarFilenameMatcher.group(1) + backupSuffix + ".jar"; }</code><technical_language>case insensitivity handled Pattern.compile("regex", Pattern.CASE_INSENSITIVE)</technical_language>

Target:
private String getJarBackupFilename(String filename) { Pattern jarFilenamePattern = Pattern.compile("^(.*)\\.jar$", Pattern.CASE_INSENSITIVE); Matcher jarFilenameMatcher = jarFilenamePattern.matcher(filename); if (!jarFilenameMatcher.find()) { return filename + BACKUP_FILENAME_SUFFIX; } return jarFilenameMatcher.group(1) + backupSuffix + ".jar"; }
Source:
<code>public boolean isEnabled() { <START> return baragonConfiguration.getWorkerConfiguration().isEnabled(); <END> }</code><technical_language>above, split out a config for this</technical_language>

Target:
public boolean isEnabled() { return config.isEnabled(); }
Source:
<code>private TableScanNode tableScan(String id, List<VariableReferenceExpression> variables) { ImmutableMap.Builder<VariableReferenceExpression, ColumnHandle> assignments = ImmutableMap.builder(); for (VariableReferenceExpression variable : variables) { assignments.put(variable, new TpchColumnHandle("orderkey", BIGINT)); } TpchTableHandle tableHandle = new TpchTableHandle("orders", 1.0); return new TableScanNode( new PlanNodeId(id), new TableHandle( new ConnectorId("tpch"), tableHandle, TpchTransactionHandle.INSTANCE, Optional.of(new TpchTableLayoutHandle(tableHandle, TupleDomain.all()))), variables, assignments.build(), false, <START> TupleDomain.all(), TupleDomain.all()); <END> }</code><technical_language>wrap</technical_language>

Target:
private TableScanNode tableScan(String id, List<VariableReferenceExpression> variables) { ImmutableMap.Builder<VariableReferenceExpression, ColumnHandle> assignments = ImmutableMap.builder(); for (VariableReferenceExpression variable : variables) { assignments.put(variable, new TpchColumnHandle("orderkey", BIGINT)); } TpchTableHandle tableHandle = new TpchTableHandle("orders", 1.0); return new TableScanNode( new PlanNodeId(id), new TableHandle( new ConnectorId("tpch"), tableHandle, TpchTransactionHandle.INSTANCE, Optional.of(new TpchTableLayoutHandle(tableHandle, TupleDomain.all()))), variables, assignments.build(), TupleDomain.all(), TupleDomain.all()); }
Source:
<code>public TimestampService createTimestampService(KeyValueService rawKvs, Optional<TableReference> timestampTable) { AtlasDbVersion.ensureVersionReported(); Preconditions.checkArgument(rawKvs instanceof CassandraKeyValueService, "TimestampService must be created from an instance of" + " CassandraKeyValueService, found %s", rawKvs.getClass()); return PersistentTimestampService.create( CassandraTimestampBoundStore.create((CassandraKeyValueService) rawKvs, timestampTable.orElse(AtlasDbConstants.TIMESTAMP_TABLE))); <START> } <END></code><technical_language>Discussed offline: I a concern Invalidator custom table. However, expect require automatic cross migrations a custom table db-persisted timestamp a paxos-persisted timestamp timelock (at in short run), this is fine for now</technical_language>

Target:
public TimestampService createTimestampService(KeyValueService rawKvs, Optional<TableReference> timestampTable) { Preconditions.checkArgument(!timestampTable.isPresent() || timestampTable.get().equals(AtlasDbConstants.TIMESTAMP_TABLE), "***ERROR:This can cause severe data corruption.***\nUnexpected timestamp table found: " + timestampTable.map(TableReference::getQualifiedName).orElse("unknown table") + "\nThis can happen if you configure the timelock server to use Cassandra KVS for timestamp" + " persistence, which is unsupported.\nWe recommend using the default paxos timestamp" + " persistence. However, if you are need to persist the timestamp service state in the" + " database, please specify a valid DbKvs config in the timestampBoundPersister block." + "\nNote that if the service has already been running, you will have to migrate the timestamp" + " table to Postgres/Oracle and rename it to %s.", AtlasDbConstants.TIMELOCK_TIMESTAMP_TABLE); AtlasDbVersion.ensureVersionReported(); Preconditions.checkArgument(rawKvs instanceof CassandraKeyValueService, "TimestampService must be created from an instance of" + " CassandraKeyValueService, found %s", rawKvs.getClass()); return PersistentTimestampService.create( CassandraTimestampBoundStore.create((CassandraKeyValueService) rawKvs)); }
Source:
<code><START> public void setOutputName(IModule module, String name) throws IllegalStateException { <END> verifyWorkingCopy(); DeploymentPreferences prefs = DeploymentPreferencesLoader.loadPreferencesFromServer(getServerOrWC()); DeploymentModulePrefs modPrefs = prefs.getOrCreatePreferences().getOrCreateModulePrefs(module); modPrefs.setProperty(IJBossToolingConstants.LOCAL_DEPLOYMENT_OUTPUT_NAME, name); DeploymentPreferencesLoader.savePreferencesToServerWorkingCopy(getWorkingCopy(), prefs); }</code><technical_language>setPreferenceValue(module, IJBossToolingConstants.LOCAL_DEPLOYMENT_OUTPUT_NAME, name); protected void setPreferenceValue(IModule module, String propertyName, String value) throws IllegalStateException { verifyWorkingCopy(); DeploymentPreferences prefs = DeploymentPreferencesLoader.loadPreferencesFromServer(getServerOrWC()); DeploymentModulePrefs modPrefs = prefs.getOrCreatePreferences().getOrCreateModulePrefs(module); modPrefs.setProperty(propertyName, value); DeploymentPreferencesLoader.savePreferencesToServerWorkingCopy(getWorkingCopy(), prefs); }</technical_language>

Target:
public void setOutputName(IModule module, String name) throws IllegalStateException { setModuleDeploymentPreference(module, IJBossToolingConstants.LOCAL_DEPLOYMENT_OUTPUT_NAME, name); }
Source:
<code>public ImmutableSetMultimap<String, String> getRefs(Collection<String> entityIds) { UpdateBuilder b = new UpdateBuilder(getRefs); b.bindUris("entityList", entityIds); b.bind("uris.statement", uris.statement()); b.bindUri("prov:wasDerivedFrom", Provenance.WAS_DERIVED_FROM); return <START> rdfClient.resultToMap(rdfClient.query(b.toString()), <END> "entity", "s"); }</code><technical_language>this selectToMap</technical_language>

Target:
public ImmutableSetMultimap<String, String> getRefs(Collection<String> entityIds) { UpdateBuilder b = new UpdateBuilder(getRefs); b.bindUris("entityList", entityIds); b.bind("uris.statement", uris.statement()); b.bindUri("prov:wasDerivedFrom", Provenance.WAS_DERIVED_FROM); return rdfClient.selectToMap(b.toString(), "entity", "s"); }
Source:
<code>public boolean match(Name name, Name group) { if (patterns.stream().anyMatch(pattern -> group.getUrn().startsWith(pattern))) { return true; <START> } <END> if (match(name)) { return true; } return false; }</code><technical_language>needed</technical_language>

Target:
public boolean match(Name name, Name group) { if (patterns.stream().anyMatch(pattern -> group.getUrn().startsWith(pattern))) { return true; } return match(name); }
Source:
<code>private InputStream filterClean(InputStream in, OperationType opType) throws IOException { in = handleAutoCRLF(in, opType); String filterCommand = getCleanFilterCommand(); if (filterCommand != null) { if (Repository.isRegistered(filterCommand)) { LocalFile buffer = new TemporaryBuffer.LocalFile(null); FilterCommand command = Repository.getCommand(filterCommand, repository, in, buffer); <START> while (command.run() != -1) { <END> } return buffer.openInputStream(); } FS fs = repository.getFS(); ProcessBuilder filterProcessBuilder = fs.runInShell(filterCommand, new String[0]); filterProcessBuilder.directory(repository.getWorkTree()); filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY, repository.getDirectory().getAbsolutePath()); ExecutionResult result; try { result = fs.execute(filterProcessBuilder, in); } catch (IOException | InterruptedException e) { throw new IOException(new FilterFailedException(e, filterCommand, getEntryPathString())); } int rc = result.getRc(); if (rc != 0) { throw new IOException(new FilterFailedException(rc, filterCommand, getEntryPathString(), result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE), RawParseUtils.decode(result.getStderr() .toByteArray(MAX_EXCEPTION_TEXT_SIZE)))); } return result.getStdout().openInputStream(); } return in; }</code><technical_language>do need this loop</technical_language>

Target:
private InputStream filterClean(InputStream in, OperationType opType) throws IOException { in = handleAutoCRLF(in, opType); String filterCommand = getCleanFilterCommand(); if (filterCommand != null) { if (Repository.isRegistered(filterCommand)) { LocalFile buffer = new TemporaryBuffer.LocalFile(null); FilterCommand command = Repository.getFilterCommand(filterCommand, repository, in, buffer); while (command.run() != -1) { } return buffer.openInputStream(); } FS fs = repository.getFS(); ProcessBuilder filterProcessBuilder = fs.runInShell(filterCommand, new String[0]); filterProcessBuilder.directory(repository.getWorkTree()); filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY, repository.getDirectory().getAbsolutePath()); ExecutionResult result; try { result = fs.execute(filterProcessBuilder, in); } catch (IOException | InterruptedException e) { throw new IOException(new FilterFailedException(e, filterCommand, getEntryPathString())); } int rc = result.getRc(); if (rc != 0) { throw new IOException(new FilterFailedException(rc, filterCommand, getEntryPathString(), result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE), RawParseUtils.decode(result.getStderr() .toByteArray(MAX_EXCEPTION_TEXT_SIZE)))); } return result.getStdout().openInputStream(); } return in; }
Source:
<code>public String generateSpecfile() { StringBuilder buffer = new StringBuilder(); generateSiteLibSiteArch(buffer); String packageName = model.getPackageName(); buffer.append("Name: " + packageName.toLowerCase() + "\n"); buffer.append("Version: " + model.getVersion() + "\n"); buffer.append("Release: 1%{?dist}" + "\n"); buffer.append("Summary: " + model.getSummary() + "\n\n"); buffer.append("Group: Development/Libraries\n"); buffer.append("License: " + model.getLicense() + "\n"); buffer.append("URL: " + model.getURL() + "\n"); buffer.append("Source0: #FIXME\n\n"); <START> buffer.append("BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root-%(%{__id_u} -n)" + "\n\n"); <END> buffer.append("BuildArch: noarch\n"); generateRequires(buffer); buffer.append("\n%description\n" + model.getDescription() + "\n\n"); generatePython3SubPackage(buffer); generatePrepSection(buffer); generateBuildSection(buffer); generateInstallSection(buffer); generateCleanSection(buffer); generateFilesSections(buffer); generateChangelog(buffer); return buffer.toString(); }</code><technical_language>Please generate BuildRoot. needed for long time. Python template is a bit outdated</technical_language>

Target:
public String generateSpecfile() { StringBuilder buffer = new StringBuilder(); generateSiteLibSiteArch(buffer); String packageName = model.getPackageName(); buffer.append("Name: " + packageName.toLowerCase() + "\n"); buffer.append("Version: " + model.getVersion() + "\n"); buffer.append("Release: 1%{?dist}" + "\n"); buffer.append("Summary: " + model.getSummary() + "\n\n"); buffer.append("Group: Development/Libraries\n"); buffer.append("License: " + model.getLicense() + "\n"); buffer.append("URL: " + model.getURL() + "\n"); buffer.append("Source0: #FIXME\n\n"); buffer.append("BuildArch: noarch\n"); generateRequires(buffer); buffer.append("\n%description\n" + model.getDescription() + "\n\n"); generatePython3SubPackage(buffer); generatePrepSection(buffer); generateBuildSection(buffer); generateInstallSection(buffer); generateFilesSections(buffer); generateChangelog(buffer); return buffer.toString(); }
Source:
<code>public Iterable<TmfAbstractAnalysisRequirement> getAnalysisRequirements() { return <START> REQUIREMENTS; <END> }</code><technical_language>return Collections.emptySet() directly, need a constant</technical_language>

Target:
public Iterable<TmfAbstractAnalysisRequirement> getAnalysisRequirements() { return Collections.emptySet(); }
Source:
<code>public void forceHealthChecks() { for (HealthCheck healthCheck : _badEndPoints.values()) { <START> healthCheck.run(); <END> } }</code><technical_language>Due nature of run(), this potentially duplicate health check runs scheduled</technical_language>

Target:
void forceHealthChecks() { for (HealthCheck healthCheck : _badEndPoints.values()) { healthCheck.run(); } }
Source:
<code>public Set<APIKey> getKeyMappingsFromApplicationId(int applicationId) throws APIManagementException{ <START> final String query = "SELECT UUID,CONSUMER_KEY,KEY_MANAGER,KEY_TYPE,STATE,APP_INFO FROM AM_APPLICATION_KEY_MAPPING " + <END> "WHERE APPLICATION_ID=?"; Set<APIKey> apiKeyList = new HashSet<>(); try(Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(query)){ preparedStatement.setInt(1,applicationId); try(ResultSet resultSet = preparedStatement.executeQuery()){ while (resultSet.next()){ APIKey apiKey = new APIKey() ; apiKey.setMappingId(resultSet.getString("UUID")); apiKey.setConsumerKey(resultSet.getString("CONSUMER_KEY")); apiKey.setKeyManager(resultSet.getString("KEY_MANAGER")); apiKey.setType(resultSet.getString("KEY_TYPE")); apiKey.setState(resultSet.getString("STATE")); try (InputStream appInfo = resultSet.getBinaryStream("APP_INFO")) { if (appInfo != null){ apiKey.setAppMetadata(IOUtils.toString(appInfo)); } } catch (IOException e) { log.error("Error while retrieving metadata", e); } apiKeyList.add(apiKey); } } } catch (SQLException e) { throw new APIManagementException("Error while Retrieving Key Mappings ",e); } return apiKeyList; }</code><technical_language>final here? move query SQLConstants</technical_language>

Target:
public Set<APIKey> getKeyMappingsFromApplicationId(int applicationId) throws APIManagementException { Set<APIKey> apiKeyList = new HashSet<>(); try (Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement preparedStatement = connection .prepareStatement(SQLConstants.GET_KEY_MAPPING_INFO_FROM_APP_ID)) { preparedStatement.setInt(1, applicationId); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { APIKey apiKey = new APIKey(); apiKey.setMappingId(resultSet.getString("UUID")); apiKey.setConsumerKey(resultSet.getString("CONSUMER_KEY")); apiKey.setKeyManager(resultSet.getString("KEY_MANAGER")); apiKey.setType(resultSet.getString("KEY_TYPE")); apiKey.setState(resultSet.getString("STATE")); try (InputStream appInfo = resultSet.getBinaryStream("APP_INFO")) { if (appInfo != null) { apiKey.setAppMetaData(IOUtils.toString(appInfo)); } } catch (IOException e) { log.error("Error while retrieving metadata", e); } apiKeyList.add(apiKey); } } } catch (SQLException e) { throw new APIManagementException("Error while Retrieving Key Mappings ", e); } return apiKeyList; }
Source:
<code>public static Launcher create(LauncherConfig config) throws PreconditionViolationException { List<TestEngine> engines = new ArrayList<>(); if (config.isTestEngineAutoRegistrationEnabled()) { new ServiceLoaderTestEngineRegistry().loadTestEngines().forEach(engines::add); <START> } <END> engines.addAll(config.getAdditionalTestEngines()); Launcher launcher = new DefaultLauncher(engines); if (config.isTestExecutionListenerAutoRegistrationEnabled()) { new ServiceLoaderTestExecutionListenerRegistry().loadListeners().forEach( launcher::registerTestExecutionListeners); } config.getAdditionalTestExecutionListeners().forEach(launcher::registerTestExecutionListeners); return launcher; }</code><technical_language>Missing a precondition "non-null" check for supplied config</technical_language>

Target:
public static Launcher create(LauncherConfig config) throws PreconditionViolationException { Preconditions.notNull(config, "configuration must not be null"); List<TestEngine> engines = new ArrayList<>(); if (config.isTestEngineAutoRegistrationEnabled()) { new ServiceLoaderTestEngineRegistry().loadTestEngines().forEach(engines::add); } engines.addAll(config.getAdditionalTestEngines()); Launcher launcher = new DefaultLauncher(engines); if (config.isTestExecutionListenerAutoRegistrationEnabled()) { new ServiceLoaderTestExecutionListenerRegistry().loadListeners().forEach( launcher::registerTestExecutionListeners); } config.getAdditionalTestExecutionListeners().forEach(launcher::registerTestExecutionListeners); return launcher; }