auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Function<Double, Double> getTrigonometricFunction(OperatorOption o) { switch (o) { case COS: return parameter -> Math.cos(parameter.doubleValue()); case TAN: return parameter -> Math.tan(parameter.doubleValue()); case ASIN: return parameter -> Math.asin(parameter.doubleValue()); case ACOS: return parameter -> Math.acos(parameter.doubleValue()); case ATAN: return parameter -> Math.atan(parameter.doubleValue()); <START> default: <END> case SIN: return parameter -> Math.sin(parameter.doubleValue()); } }</code><technical_language>Please reorder cases default is</technical_language>

Target:
private Function<Double, Double> getTrigonometricFunction(OperatorOption o) { switch (o) { case COS: return parameter -> Math.cos(parameter.doubleValue()); case TAN: return parameter -> Math.tan(parameter.doubleValue()); case ASIN: return parameter -> Math.asin(parameter.doubleValue()); case ACOS: return parameter -> Math.acos(parameter.doubleValue()); case ATAN: return parameter -> Math.atan(parameter.doubleValue()); case SIN: default: return parameter -> Math.sin(parameter.doubleValue()); } }
Source:
<code>public void removeString() { BibtexStringViewModel toBeRemoved = selectedItemProperty.getValue(); allStrings.remove(toBeRemoved); <START> bibDatabase.removeStringByName(fromBibtexStringViewModel(toBeRemoved)); <END> }</code><technical_language>If user removes a string presses cancel string removed, right</technical_language>

Target:
public void removeString() { BibtexStringViewModel toBeRemoved = selectedItemProperty.getValue(); allStrings.remove(toBeRemoved); }
Source:
<code>public boolean isMenuQnNumberVisible(int qnNumber) { WebElement discardChangesButton = browser.driver.findElement( <START> By.id(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER + "-" + qnNumber)); <END> return discardChangesButton.isDisplayed(); }</code><technical_language>I line 831 832 combined. If combine line 830,831 832 2 lines</technical_language>

Target:
public boolean isMenuQnNumberVisible(int qnNumber) { if (qnNumber != NEW_QUESTION_NUM) { WebElement selectQuestionNumberDropdown = browser.driver.findElement(By.id(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER + "-" + qnNumber)); return selectQuestionNumberDropdown.isDisplayed(); } WebElement retrievedQnTable = browser.driver.findElement(By.id("questionTable-" + qnNumber)); return retrievedQnTable.findElement(By.id(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER)).isDisplayed(); }
Source:
<code>public Set<String> getUnmarkedBlobs() { try { Set<String> unmarked = new HashSet<>(); Page<Blob> blobs = binaryManager.getBucket().list(BlobListOption.fields(BlobField.ID, BlobField.SIZE)); do { for (Blob blob : blobs.iterateAll()) { <START> if (marked.contains(getDigest(blob))) { <END> status.numBinaries++; status.sizeBinaries += blob.getSize(); } else { status.numBinariesGC++; status.sizeBinariesGC += blob.getSize(); unmarked.add(getDigest(blob)); marked.remove(getDigest(blob)); } } blobs = blobs.getNextPage(); } while (blobs != null); return unmarked; } catch (StorageException e) { throw new NuxeoException(e); } }</code><technical_language>Please add a safety check for S3 a MD5 digest, avoid deleting unwanted files</technical_language>

Target:
public Set<String> getUnmarkedBlobs() { Set<String> unmarked = new HashSet<>(); Page<Blob> blobs = binaryManager.getBucket() .list(BlobListOption.fields(BlobField.ID, BlobField.SIZE), BlobListOption.prefix(binaryManager.bucketPrefix)); do { int prefixLength = binaryManager.bucketPrefix.length(); for (Blob blob : blobs.iterateAll()) { String digest = blob.getName().substring(prefixLength); if (!isMD5(digest)) { continue; } if (marked.contains(digest)) { status.numBinaries++; status.sizeBinaries += blob.getSize(); } else { status.numBinariesGC++; status.sizeBinariesGC += blob.getSize(); unmarked.add(digest); marked.remove(digest); } } blobs = blobs.getNextPage(); } while (blobs != null); return unmarked; }
Source:
<code>public void autoSetText(CharSequence text, int cursorPosition){ autoEdit = true; setText(text); <START> this.setSelection(cursorPosition); <END> autoEdit = false; }</code><technical_language>need "this.". Check other places</technical_language>

Target:
public void autoSetText(CharSequence text, int cursorPosition){ mAutoEdit = true; setText(text); setSelection(cursorPosition); mAutoEdit = false; }
Source:
<code>public void onMessage(ReadRowsResponse message) { resetStatusBasedBackoff(); <START> if (rowObserver instanceof ResponseQueueReader) { <END> ((ResponseQueueReader) rowObserver).addRequestResultMarker(); } else { call.request(1); } lastResponseMs = clock.currentTimeMillis(); timeoutRetryCount = 0; ByteString previouslyProcessedKey = rowMerger.getLastCompletedRowKey(); rowMerger.onNext(message); ByteString lastProcessedKey = rowMerger.getLastCompletedRowKey(); if (previouslyProcessedKey != lastProcessedKey) { updateLastFoundKey(lastProcessedKey); } else { updateLastFoundKey(message.getLastScannedRowKey()); } }</code><technical_language>This is a bit hacky, I if is a handle this</technical_language>

Target:
public void onMessage(ReadRowsResponse message) { resetStatusBasedBackoff(); lastResponseMs = clock.currentTimeMillis(); timeoutRetryCount = 0; ByteString previouslyProcessedKey = rowMerger.getLastCompletedRowKey(); rowMerger.onNext(message); ByteString lastProcessedKey = rowMerger.getLastCompletedRowKey(); if (previouslyProcessedKey != lastProcessedKey) { updateLastFoundKey(lastProcessedKey); } else { updateLastFoundKey(message.getLastScannedRowKey()); } if (adapter.autoFlowControlEnabled) { adapter.request(1); } if (resultObserver != null) { resultObserver.onNext(message); } }
Source:
<code>double routeLeg(Person person, Leg leg, Link fromLink, Link toLink, double depTime) { double travTime = 0; Node startNode = fromLink.getToNode(); Node endNode = toLink.getFromNode(); if (toLink != fromLink) { <START> <END> Id<Vehicle> vehicleId = VehicleUtils.getVehicleId(person, leg.getMode(), this.scenario.getConfig()); Vehicle vehicle = scenario.getVehicles().getVehicles().get(vehicleId); Path path = this.routeAlgo.calcLeastCostPath(startNode, endNode, depTime, person, vehicle); if (path == null) throw new RuntimeException("No route found from node " + startNode.getId() + " to node " + endNode.getId() + "."); NetworkRoute route = this.populationFactory.getRouteFactories().createRoute(NetworkRoute.class, fromLink.getId(), toLink.getId()); route.setLinkIds(fromLink.getId(), NetworkUtils.getLinkIds(path.links), toLink.getId()); route.setTravelTime((int) path.travelTime); route.setTravelCost(path.travelCost); route.setDistance(RouteUtils.calcDistance(route, 1.0,1.0,this.filteredNetwork ) ); leg.setRoute(route); travTime = (int) path.travelTime; } else { NetworkRoute route = this.populationFactory.getRouteFactories().createRoute(NetworkRoute.class, fromLink.getId(), toLink.getId()); route.setTravelTime(0); route.setDistance(0.0); leg.setRoute(route); travTime = 0; } leg.setDepartureTime(depTime); leg.setTravelTime(travTime); return travTime; }</code><technical_language>please test I try myself/see problem? Thanks ..</technical_language>

Target:
double routeLeg(Person person, Leg leg, Link fromLink, Link toLink, double depTime) { double travTime; Node startNode = fromLink.getToNode(); Node endNode = toLink.getFromNode(); if (toLink != fromLink) { Id<Vehicle> vehicleId = VehicleUtils.getVehicleId(person, leg.getMode()); Vehicle vehicle = scenario.getVehicles().getVehicles().get(vehicleId); Path path = this.routeAlgo.calcLeastCostPath(startNode, endNode, depTime, person, vehicle); if (path == null) throw new RuntimeException("No route found from node " + startNode.getId() + " to node " + endNode.getId() + "."); NetworkRoute route = this.populationFactory.getRouteFactories().createRoute(NetworkRoute.class, fromLink.getId(), toLink.getId()); route.setLinkIds(fromLink.getId(), NetworkUtils.getLinkIds(path.links), toLink.getId()); route.setTravelTime((int) path.travelTime); route.setTravelCost(path.travelCost); route.setDistance(RouteUtils.calcDistance(route, 1.0,1.0,this.filteredNetwork ) ); leg.setRoute(route); travTime = (int) path.travelTime; } else { NetworkRoute route = this.populationFactory.getRouteFactories().createRoute(NetworkRoute.class, fromLink.getId(), toLink.getId()); route.setTravelTime(0); route.setDistance(0.0); leg.setRoute(route); travTime = 0; } leg.setDepartureTime(depTime); leg.setTravelTime(travTime); return travTime; }
Source:
<code>public TableViewer createTableViewerSection(Composite aParent) { Composite viewerForm = UIUtils.createsGeneralComposite(aParent, SWT.BORDER | SWT.SHADOW_ETCHED_IN); GridData gribDataViewer = new GridData(GridData.FILL_BOTH); viewerForm.setLayoutData(gribDataViewer); GridLayout layout = new GridLayout(); layout.numColumns = ReviewTableDefinition.values().length; layout.makeColumnsEqualWidth = false; layout.marginWidth = 0; layout.marginHeight = 0; viewerForm.setLayout(layout); fViewer = new TableViewer(viewerForm, TABLE_STYLE); fViewer = buildAndLayoutTable(fViewer); fViewer.setContentProvider(new ReviewTableContentProvider()); ReviewTableLabelProvider tableProvider = new ReviewTableLabelProvider(); fViewer.setLabelProvider(tableProvider); ReviewTableSorter.bind(fViewer); <START> fViewer.setComparator(new ReviewTableSorter(7)); END> fViewer.getTable().addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { GerritUi.Ftracer.traceInfo("Table selection: " + e.toString()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); fViewer.getTable().addListener(SWT.MouseDown, mouseButtonListener); return fViewer; }</code><technical_language>Another nit, a Hungarian notation snuck censors. ;) reviewViewer something</technical_language>

Target:
public TableViewer createTableViewerSection(Composite aParent) { Composite viewerForm = UIUtils.createsGeneralComposite(aParent, SWT.BORDER | SWT.SHADOW_ETCHED_IN); GridData gribDataViewer = new GridData(GridData.FILL_BOTH); viewerForm.setLayoutData(gribDataViewer); GridLayout layout = new GridLayout(); layout.numColumns = ReviewTableDefinition.values().length; layout.makeColumnsEqualWidth = false; layout.marginWidth = 0; layout.marginHeight = 0; viewerForm.setLayout(layout); fViewer = new TableViewer(viewerForm, TABLE_STYLE); fViewer = buildAndLayoutTable(fViewer); fViewer.setContentProvider(new ReviewTableContentProvider()); ReviewTableLabelProvider tableProvider = new ReviewTableLabelProvider(); fViewer.setLabelProvider(tableProvider); ReviewTableSorter.bind(fViewer); fViewer.setComparator(new ReviewTableSorter(6)); fViewer.getTable().addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { GerritUi.Ftracer.traceInfo("Table selection: " + e.toString()); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }); fViewer.getTable().addListener(SWT.MouseDown, mouseButtonListener); return fViewer; }
Source:
<code><START> public String toString() { <END> return toStringHelper().toString(); }</code><technical_language>This stay final</technical_language>

Target:
public final String toString() { return toStringHelper().toString(); }
Source:
<code>public void setUserActivationKey_shouldCreateUserActivationKey() throws MessageException { User u = new User(); u.setPerson(new Person()); u.addName(new PersonName("Benjamin", "A", "Wolfe")); u.setUsername("bwolfe"); u.getPerson().setGender("M"); <START> Context.getAdministrationService().setGlobalProperty("mail.smtp_auth", "false"); <END> Context.getAdministrationService().setGlobalProperty(OpenmrsConstants.GP_MAIL_SMTP_STARTTLS_ENABLE, "true"); Context.getAdministrationService().setGlobalProperty("mail.smtp_host", "localhost"); Context.getAdministrationService().setGlobalProperty("mail.smtp_port", "25"); User createdUser = userService.createUser(u, "Openmr5xy"); assertNull(dao.getLoginCredential(createdUser).getActivationKey()); assertEquals(createdUser, userService.setUserActivationKey(createdUser)); assertNotNull(dao.getLoginCredential(createdUser).getActivationKey()); }</code><technical_language>is this necessary</technical_language>

Target:
public void setUserActivationKey_shouldCreateUserActivationKey() throws MessageException { User u = new User(); u.setPerson(new Person()); u.addName(new PersonName("Benjamin", "A", "Wolfe")); u.setUsername("bwolfe"); u.getPerson().setGender("M"); Context.getAdministrationService().setGlobalProperty(OpenmrsConstants.GP_HOST_URL, "http://localhost:8080/openmrs/admin/users/changePassword.form/{activationKey}"); User createdUser = userService.createUser(u, "Openmr5xy"); assertNull(dao.getLoginCredential(createdUser).getActivationKey()); assertEquals(createdUser, userService.setUserActivationKey(createdUser)); assertNotNull(dao.getLoginCredential(createdUser).getActivationKey()); }
Source:
<code>private SimpleFeatureCollection parseFeatures(FileItem zipFile, Charset cs, Set<String> validFiles, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws ActionParamsException { File dir = null; FeatureCollectionParser parser = null; try { dir = makeRandomTempDirectory(); File mainFile = unZip(zipFile, cs, validFiles, dir); parser = getParser(mainFile); return parse(parser, mainFile, sourceCRS, targetCRS); <START> } catch (ServiceException e){ <END> UserLayerHandlerHelper.addStringToErrorJSON(e.getOptions(), "error", "parser_error"); UserLayerHandlerHelper.addStringToErrorJSON(e.getOptions(), "parser", parser == null ? null : parser.getSuffix()); throw new ActionParamsException (e.getMessage(), e.getOptions() ); } finally { if (dir != null) { deleteDir(dir); } } }</code><technical_language>This catch block is catching potential exceptions makeRandomTempDirectory() unZip() do "parser_error"s. add a nested try block calls parser.parse() catch ServiceExceptions</technical_language>

Target:
private SimpleFeatureCollection parseFeatures(FileItem zipFile, Charset cs, Set<String> validFiles, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws UserLayerException, ActionParamsException { File dir = null; FeatureCollectionParser parser = null; try { dir = makeRandomTempDirectory(); File mainFile = unZip(zipFile, cs, validFiles, dir); parser = getParser(mainFile); return parser.parse(mainFile, sourceCRS, targetCRS); }catch (UserLayerException e) { if (parser != null) { e.addContent(UserLayerException.InfoType.PARSER, parser.getSuffix().toLowerCase()); } throw e; }catch (ServiceException e) { throw new ActionParamsException (e.getMessage()); } finally { if (dir != null) { deleteDir(dir); } } }
Source:
<code>public static InetAddress getLocalInetAddress(Context context) { if (!isConnectedToLocalNetwork(context) && !isEnabledWifiHotspot(context)) { return null; } if (isConnectedToWifi(context)) { WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); int ipAddress = wm.getConnectionInfo().getIpAddress(); if (ipAddress == 0) return null; return intToInet(ipAddress); } try { Enumeration<NetworkInterface> netinterfaces = NetworkInterface.getNetworkInterfaces(); while (netinterfaces.hasMoreElements()) { NetworkInterface netinterface = netinterfaces.nextElement(); Enumeration<InetAddress> addresses = netinterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); <START> if(address.getHostAddress().startsWith(WIFI_AP_ADDRESS_PREFIX) && isEnabledWifiHotspot(context)) <END> return address; if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && !isEnabledWifiHotspot(context)) return address; } } } catch (SocketException e) { e.printStackTrace(); } return null; }</code><technical_language>Please add a null check for address</technical_language>

Target:
public static InetAddress getLocalInetAddress(Context context) { if (!isConnectedToLocalNetwork(context) && !isEnabledWifiHotspot(context)) { return null; } if (isConnectedToWifi(context)) { WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); int ipAddress = wm.getConnectionInfo().getIpAddress(); if (ipAddress == 0) return null; return intToInet(ipAddress); } try { Enumeration<NetworkInterface> netinterfaces = NetworkInterface.getNetworkInterfaces(); while (netinterfaces.hasMoreElements()) { NetworkInterface netinterface = netinterfaces.nextElement(); Enumeration<InetAddress> addresses = netinterface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address == null) { continue; } if(address.getHostAddress().startsWith(WIFI_AP_ADDRESS_PREFIX) && isEnabledWifiHotspot(context)) return address; if (!address.isLoopbackAddress() && !address.isLinkLocalAddress() && !isEnabledWifiHotspot(context)) return address; } } } catch (SocketException e) { e.printStackTrace(); } return null; }
Source:
<code>protected void configure() { <START> bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); <END> super.configure(); }</code><technical_language>Call super first</technical_language>

Target:
protected void configure() { super.configure(); bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class); }
Source:
<code>private static void loadInternalInboundApis() { int internalInboundPort = HTTPEndpointManager.getInstance().getInternalInboundPort(); if (HTTPEndpointManager.getInstance().isAnyInternalHttpApiEnabled()) { HTTPEndpointManager.getInstance() .startListener(internalInboundPort, InboundHttpConstants.INTERNAL_INBOUND_ENDPOINT_NAME, null); } int internalInboundHttpsPort = HTTPEndpointManager.getInstance().getInternalHTTPSInboundPort(); if (HTTPEndpointManager.getInstance().isAnyInternalHttpsApiEnabled()) { <START> HTTPEndpointManager.getInstance(). <END> startSSLListener(internalInboundHttpsPort, InboundHttpConstants.INTERNAL_INBOUND_ENDPOINT_NAME, ConfigurationLoader.getSSLConfiguration(), null); } }</code><technical_language>Line wrapping period</technical_language>

Target:
private static void loadInternalInboundApis() { HTTPEndpointManager manager = HTTPEndpointManager.getInstance(); if (manager.isAnyInternalHttpApiEnabled()) { HTTPEndpointManager.getInstance().startListener(manager.getInternalInboundHttpPort(), InboundHttpConstants.INTERNAL_HTTP_INBOUND_ENDPOINT_NAME, null); } if (manager.isAnyInternalHttpsApiEnabled()) { if (ConfigurationLoader.isSslConfiguredSuccessfully()) { manager.startSSLListener(manager.getInternalInboundHttpsPort(), InboundHttpConstants.INTERNAL_HTTPS_INBOUND_ENDPOINT_NAME, ConfigurationLoader.getSslConfiguration(), null); } else { log.error("SSL is not configured for Internal apis. Hence Internal Apis will not be available via " + "https."); } } }
Source:
<code>public void testWithCheckConfigLocationFileDoesNotExists() { EnvironmentTestUtils.addEnvironment(this.context, "mybatis.config:foo.xml", "mybatis.check-config-location=true"); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); <START> try { <END> this.context.refresh(); fail(); } catch (BeanCreationException e) { assertEquals( "Cannot find config location: class path resource [foo.xml] (please add config file or check your Mybatis configuration)", e.getCause().getMessage()); } }</code><technical_language>ExpectedException Rule</technical_language>

Target:
public void testWithCheckConfigLocationFileDoesNotExists() { EnvironmentTestUtils.addEnvironment(this.context, "mybatis.config:foo.xml", "mybatis.check-config-location=true"); this.context.register(EmbeddedDataSourceConfiguration.class, MybatisAutoConfiguration.class); expectedException.expect(isA(BeanCreationException.class)); expectedException .expectMessage(is("Error creating bean with name 'mybatisAutoConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find config location: class path resource [foo.xml] (please add config file or check your Mybatis configuration)")); this.context.refresh(); }
Source:
<code>private int testConcurrently(int numThreads, int iterations, AccessAttempt accessAttempt) { LockPool<Integer> lockPool = new LockPool<>(); ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(numThreads); AtomicBoolean concurrencyIndicator = new AtomicBoolean(false); <START> AtomicInteger failureCounter = new AtomicInteger(0); <END> for (int i = 0; (i < numThreads); i++) { threadPool.execute(() -> tryAccess(iterations, startSignal, lockPool, concurrencyIndicator, failureCounter, doneSignal, accessAttempt)); } startSignal.countDown(); awaitWithoutInterrupt(doneSignal); threadPool.shutdown(); return failureCounter.get(); }</code><technical_language>failureCounter is incremented multiple places, easier for test fixing a failure log push a message to. matter for completeness of test though</technical_language>

Target:
private boolean testConcurrently(int numThreads, int iterations, AccessAttempt accessAttempt) { LockPool<Integer> lockPool = new LockPool<>(); ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(numThreads); AtomicBoolean concurrencyIndicator = new AtomicBoolean(false); AtomicBoolean failureIndicator = new AtomicBoolean(false); for (int i = 0; (i < numThreads); i++) { threadPool.execute(() -> tryAccess(iterations, startSignal, lockPool, concurrencyIndicator, failureIndicator, doneSignal, accessAttempt)); } startSignal.countDown(); awaitWithoutInterrupt(doneSignal); threadPool.shutdown(); return failureIndicator.get(); }
Source:
<code>public void preload() { if (!enabled) return; AdvancedCacheLoader preloadCl = null; for (CacheLoader l : loaders) { if (configMap.get(l).preload()) { if (!(l instanceof AdvancedCacheLoader)) { throw new PersistenceException("Cannot preload from cache loader '" + l.getClass().getName() + "' as it doesn't implement '" + AdvancedCacheLoader.class.getName() + "'"); } preloadCl = (AdvancedCacheLoader) l; if (preloadCl instanceof AdvancedAsyncCacheLoader) preloadCl = (AdvancedCacheLoader) ((AdvancedAsyncCacheLoader) preloadCl).undelegate(); break; } } if (preloadCl == null) return; long start = timeService.time(); <START> final long maxEntries = configuration.memory().size(); <END> final AtomicInteger loadedEntries = new AtomicInteger(0); final AdvancedCache<Object, Object> flaggedCache = getCacheForStateInsertion(); ByRef.Boolean preloaded = new ByRef.Boolean(true); preloadCl.process(null, (me, taskContext) -> { if (loadedEntries.getAndIncrement() >= maxEntries) { taskContext.stop(); preloaded.set(false); return; } Metadata metadata = me.getMetadata() != null ? ((InternalMetadataImpl) me.getMetadata()).actual() : null; preloadKey(flaggedCache, me.getKey(), me.getValue(), metadata); }, new WithinThreadExecutor(), true, true); this.preloaded = preloaded.get(); log.debugf("Preloaded %d keys in %s", loadedEntries.get(), Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }</code><technical_language>Hrmm this defaults -1, set this Long.MAX_VALUE ignore if is -1</technical_language>

Target:
public void preload() { if (!enabled) return; AdvancedCacheLoader preloadCl = null; for (CacheLoader l : loaders) { if (configMap.get(l).preload()) { if (!(l instanceof AdvancedCacheLoader)) { throw new PersistenceException("Cannot preload from cache loader '" + l.getClass().getName() + "' as it doesn't implement '" + AdvancedCacheLoader.class.getName() + "'"); } preloadCl = (AdvancedCacheLoader) l; if (preloadCl instanceof AdvancedAsyncCacheLoader) preloadCl = (AdvancedCacheLoader) ((AdvancedAsyncCacheLoader) preloadCl).undelegate(); break; } } if (preloadCl == null) return; long start = timeService.time(); final long maxEntries = getMaxEntries(); final AtomicInteger loadedEntries = new AtomicInteger(0); final AdvancedCache<Object, Object> flaggedCache = getCacheForStateInsertion(); ByRef.Boolean preloaded = new ByRef.Boolean(true); preloadCl.process(null, (me, taskContext) -> { if (loadedEntries.getAndIncrement() >= maxEntries) { taskContext.stop(); preloaded.set(false); return; } Metadata metadata = me.getMetadata() != null ? ((InternalMetadataImpl) me.getMetadata()).actual() : null; preloadKey(flaggedCache, me.getKey(), me.getValue(), metadata); }, new WithinThreadExecutor(), true, true); this.preloaded = preloaded.get(); log.debugf("Preloaded %d keys in %s", loadedEntries.get(), Util.prettyPrintTime(timeService.timeDuration(start, MILLISECONDS))); }
Source:
<code>private static List<File> searchDir(String mount) { <START> File photoDir = new File(mount + "/DCIM"); <END> File[] goProDirs = photoDir.listFiles(); if (goProDirs == null || goProDirs.length == 0) { return null; } List<File> photoFiles = new ArrayList<>(); for (File picDir : goProDirs) { if (picDir.getName().toLowerCase().contains("gopro")) { photoFiles.addAll(Arrays.asList(picDir.listFiles())); } } return photoFiles; }</code><technical_language>@chaviw /DCIM a constant</technical_language>

Target:
private static ArrayList<File> searchDir(String mount) { File photoDir = new File(mount + IMAGE_PATH); File[] goProDirs = photoDir.listFiles(); if (goProDirs == null || goProDirs.length == 0) { return null; } ArrayList<File> photoFiles = new ArrayList<>(); for (File picDir : goProDirs) { if (picDir.getName().toLowerCase().contains("gopro")) { photoFiles.addAll(Arrays.asList(picDir.listFiles())); } } return photoFiles; }
Source:
<code>public void onLoadFinished(Loader<String> arg0, String page) { if (page == null) { hasLoaderError = true; } else { viewstates = Login.getViewstates(page); trackables = GCParser.parseTrackableLog(page); possibleLogTypes = GCParser.parseTypes(page); <START> if (possibleLogTypes.isEmpty()) { <END> hasLoaderError = true; } else { hasLoaderError = false; } } activity.onLoadFinished(); }</code><technical_language>if-else transformed a simple assignment</technical_language>

Target:
public void onLoadFinished(Loader<String> arg0, String page) { if (page == null) { hasLoaderError = true; } else { viewstates = Login.getViewstates(page); trackables = GCParser.parseTrackableLog(page); possibleLogTypes = GCParser.parseTypes(page); hasLoaderError = possibleLogTypes.isEmpty(); } activity.onLoadFinished(); }
Source:
<code>protected String errorMessage(Exception e) { <START> return "Param must be \"true\" or \"false\"."; <END> }</code><technical_language>is i</technical_language>

Target:
protected String errorMessage(Exception e) { return "Parameter must be \"true\" or \"false\"."; }
Source:
<code>public static Driver createDriver(DriverContext driverContext, List<Operator> operators) { <START> Driver driver = new Driver(requireNonNull(driverContext, "driverContext is null"), requireNonNull(operators, "operators is null")); <END> driver.initialize(); return driver; }</code><technical_language>Move requireNonNull checks a separate line. Calling inline messy</technical_language>

Target:
public static Driver createDriver(DriverContext driverContext, List<Operator> operators) { requireNonNull(driverContext, "driverContext is null"); requireNonNull(operators, "operators is null"); Driver driver = new Driver(driverContext, operators); driver.initialize(); return driver; }
Source:
<code>public void removeDynamicMenuContributions(MenuManager menuManager, MMenu menuModel, ArrayList<MMenuElement> dump) { removeMenuContributions(menuModel, dump); for (MMenuElement mMenuElement : dump) { IContributionItem ici = getContribution(mMenuElement); if (ici == null && mMenuElement instanceof MMenu) { <START> ici = getManager((MMenu) mMenuElement); <END> } menuManager.remove(ici); clearModelToContribution(mMenuElement, ici); } }</code><technical_language>clearModelToManager(*) getManager(*), group together</technical_language>

Target:
public void removeDynamicMenuContributions(MenuManager menuManager, MMenu menuModel, ArrayList<MMenuElement> dump) { removeMenuContributions(menuModel, dump); for (MMenuElement mMenuElement : dump) { IContributionItem ici = getContribution(mMenuElement); if (ici == null && mMenuElement instanceof MMenu) { MMenu menuElement = (MMenu) mMenuElement; ici = getManager(menuElement); clearModelToManager(menuElement, (MenuManager) ici); } else { clearModelToContribution(menuModel, ici); } menuManager.remove(ici); } }
Source:
<code>void getPublicKey(DataInputStream din, DataOutputStream dout) throws Exception { String username = CoreNodeUtils.deserializeString(din); <START> Optional<PublicKeyHash> k = coreNode.getPublicKey(username).get(); <END> dout.writeBoolean(k.isPresent()); if (!k.isPresent()) return; byte[] b = k.get().serialize(); dout.writeInt(b.length); dout.write(b); }</code><technical_language>this method called getPublicKeyHash? more intuitive</technical_language>

Target:
void getPublicKey(DataInputStream din, DataOutputStream dout) throws Exception { String username = CoreNodeUtils.deserializeString(din); Optional<PublicKeyHash> k = coreNode.getPublicKeyHash(username).get(); dout.writeBoolean(k.isPresent()); if (!k.isPresent()) return; byte[] b = k.get().serialize(); dout.writeInt(b.length); dout.write(b); }
Source:
<code>public void testPattern() { DateTime dateTime = new DateTime().withDate(1995, 7, 4).withTime(14, 32, 12, 0); <START> try { <END> shouldCompileTo("{{jodaPatternHelper this \"y-MMM-d H:m:s\"}}", dateTime, "1995-Jul-4 14:32:12"); } catch (IOException e) { Assert.fail("IOException thrown"); } }</code><technical_language>need try/catch for valid tests. test fail exception occurs</technical_language>

Target:
public void testPattern() throws IOException { DateTime dateTime = new DateTime().withDate(1995, 7, 4).withTime(14, 32, 12, 0); shouldCompileTo("{{jodaPatternHelper this \"y-MMM-d H:m:s\"}}", dateTime, "1995-Jul-4 14:32:12"); }
Source:
<code>private CompositeJobParametersValidator compositeJobParametersValidator() { final List<JobParametersValidator> jobParametersValidators = Arrays.asList( new DbNameValidator(), new DbCollectionsVariantsNameValidator(), new DbCollectionsFilesNameValidator(), new InputStudyIdValidator(), new InputVcfIdValidator(), new InputVcfValidator(), <START> new OptionalValidator(new InputVcfAggregationValidator(), JobParametersNames.INPUT_VCF_AGGREGATION), <END> new OptionalValidator(new ConfigChunkSizeValidator(), JobParametersNames.CONFIG_CHUNK_SIZE) ); CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }</code><technical_language>This parameter is necessary for genotyped VCF, for aggregated assuming BASIC default that? 2 types of validator necessary, for genotyped aggregated files respectively</technical_language>

Target:
private CompositeJobParametersValidator compositeJobParametersValidator() { final List<JobParametersValidator> jobParametersValidators = Arrays.asList( new DbNameValidator(), new DbCollectionsVariantsNameValidator(), new InputStudyIdValidator(), new InputVcfIdValidator(), new InputVcfValidator(), new InputVcfAggregationValidator(), new OptionalValidator(new ConfigChunkSizeValidator(), JobParametersNames.CONFIG_CHUNK_SIZE) ); CompositeJobParametersValidator compositeJobParametersValidator = new CompositeJobParametersValidator(); compositeJobParametersValidator.setValidators(jobParametersValidators); return compositeJobParametersValidator; }
Source:
<code>public boolean isOpen() { <START> return closer.getState() == Closer.State.OPEN; <END> }</code><technical_language>Formatting? 3 spaces, I think</technical_language>

Target:
public boolean isOpen() { return closer.getState() == AVAILABLE; }
Source:
<code>private IAndroidTarget findDefaultRenderTarget() { Sdk current = Sdk.getCurrent(); if (current != null) { IAndroidTarget projectTarget = current.getTarget(mEditedFile.getProject()); int minProjectApi = Integer.MAX_VALUE; if (projectTarget != null) { <START> if (!projectTarget.isPlatform()) { <END> return projectTarget; } minProjectApi = projectTarget.getVersion().getApiLevel(); } IAndroidTarget best = null; int bestApiLevel = Integer.MAX_VALUE; for (IAndroidTarget target : current.getTargets()) { if (!target.isPlatform()) { continue; } int apiLevel = target.getVersion().getApiLevel(); if (apiLevel < minProjectApi) { continue; } String property = target.getProperty(PlatformPackage.PROP_LAYOUTLIB_API); if (property != null || apiLevel >= 11) { if (apiLevel < bestApiLevel) { bestApiLevel = apiLevel; best = target; } } } return best; } return null; }</code><technical_language>this is want. want if (!projectTarget.isPlatform() && projectTarget.hasRenderingLibrary()) This is want select addon if provides a custom rendering. (new today!)</technical_language>

Target:
private IAndroidTarget findDefaultRenderTarget() { Sdk current = Sdk.getCurrent(); if (current != null) { IAndroidTarget projectTarget = current.getTarget(mEditedFile.getProject()); int minProjectApi = Integer.MAX_VALUE; if (projectTarget != null) { if (!projectTarget.isPlatform() && projectTarget.hasRenderingLibrary()) { return projectTarget; } minProjectApi = projectTarget.getVersion().getApiLevel(); } IAndroidTarget best = null; int bestApiLevel = Integer.MAX_VALUE; for (IAndroidTarget target : current.getTargets()) { if (!target.isPlatform()) { continue; } int apiLevel = target.getVersion().getApiLevel(); if (apiLevel < minProjectApi) { continue; } String property = target.getProperty(PlatformPackage.PROP_LAYOUTLIB_API); if (property != null || apiLevel >= 11) { if (apiLevel < bestApiLevel) { bestApiLevel = apiLevel; best = target; } } } return best; } return null; }
Source:
<code>public void testDumbLocalizer() throws Exception { File[] sources = new File[]{new File("../test-projects/src/main/java/nopol_examples/nopol_example_1/NopolExample.java")}; URL[] classpath = new URL[]{ new File("../test-projects/target/classes").toURI().toURL(), new File("../test-projects/target/test-classes").toURI().toURL() }; String testClasses = new String[] {"nopol_examples.nopol_example_1.NopolExampleTest"}; Config config = new Config(); config.setLocalizer(Config.NopolLocalizer.DUMB); DumbFaultLocalizerImpl localizer = new DumbFaultLocalizerImpl(sources, classpath, testClasses, config); Map<SourceLocation, List<TestResult>> executedSourceLocationPerTest = localizer.getTestListPerStatement(); <START> assertEquals(8, executedSourceLocationPerTest.keySet().size()); <END> }</code><technical_language>add check specific source location</technical_language>

Target:
public void testDumbLocalizer() throws Exception { File[] sources = new File[]{new File("../test-projects/src/main/java/nopol_examples/nopol_example_1/NopolExample.java")}; URL[] classpath = new URL[]{ new File("../test-projects/target/classes").toURI().toURL(), new File("../test-projects/target/test-classes").toURI().toURL() }; String testClasses = new String[] {"nopol_examples.nopol_example_1.NopolExampleTest"}; Config config = new Config(); DumbFaultLocalizerImpl localizer = new DumbFaultLocalizerImpl(sources, classpath, testClasses, config); Map<SourceLocation, List<TestResult>> executedSourceLocationPerTest = localizer.getTestListPerStatement(); assertEquals(8, executedSourceLocationPerTest.keySet().size()); assertTrue(executedSourceLocationPerTest.keySet().contains(new SourceLocation("nopol_examples.nopol_example_1.NopolExample", 16))); }
Source:
<code>public boolean hasPermission(String permission, ContextReference contextReference, User user) { Permission perm = permissionDAO.findByName(permission); fi.otavanopisto.pyramus.domainmodel.users.User userEntity = getUser(user); boolean allowed = environmentUserRolePermissionDAO.hasEnvironmentPermissionAccess(userEntity.getRole(), perm); if (!allowed) { allowed = hasEveryonePermission(permission, contextReference); } PyramusPermissionCollection collection = findCollection(permission); try { PermissionFeature[] features = collection.listPermissionFeatures(permission); if (features != null) { for (PermissionFeature feature : features) { Instance<PermissionFeatureHandler> instance = featureHandlers.select(new PermissionFeatureLiteral(feature.value())); if (!instance.isUnsatisfied()) { PermissionFeatureHandler permissionFeatureHandler = instance.get(); allowed = permissionFeatureHandler.hasPermission(permission, userEntity, contextReference, allowed); } else logger.log(Level.SEVERE, String.format("Unsatisfied permission feature %s", feature.value())); } } } catch (Exception e) { <START> e.printStackTrace(); <END> } return allowed; }</code><technical_language>Log SEVERE exception</technical_language>

Target:
public boolean hasPermission(String permission, ContextReference contextReference, User user) { Permission perm = permissionDAO.findByName(permission); fi.otavanopisto.pyramus.domainmodel.users.User userEntity = getUser(user); boolean allowed = environmentUserRolePermissionDAO.hasEnvironmentPermissionAccess(userEntity.getRole(), perm); if (!allowed) { allowed = hasEveryonePermission(permission, contextReference); } PyramusPermissionCollection collection = findCollection(permission); try { PermissionFeature[] features = collection.listPermissionFeatures(permission); if (features != null) { for (PermissionFeature feature : features) { Instance<PermissionFeatureHandler> instance = featureHandlers.select(new PermissionFeatureLiteral(feature.value())); if (!instance.isUnsatisfied()) { PermissionFeatureHandler permissionFeatureHandler = instance.get(); allowed = permissionFeatureHandler.hasPermission(permission, userEntity, contextReference, allowed); } else logger.log(Level.SEVERE, String.format("Unsatisfied permission feature %s", feature.value())); } } } catch (Exception e) { logger.log(Level.SEVERE, String.format("Could not list permission features for permission %s", permission), e); } return allowed; }
Source:
<code>private void compareRegistryInfo(EndpointRegistryInfo expected, EndpointRegistryInfo actual) { <START> org.junit.Assert.assertEquals(expected.getUuid(), actual.getUuid()); <END> org.junit.Assert.assertEquals(expected.getName(), actual.getName()); org.junit.Assert.assertEquals(expected.getMode(), actual.getMode()); org.junit.Assert.assertEquals(expected.getType(), actual.getType()); org.junit.Assert.assertEquals(expected.getOwner(), actual.getOwner()); org.junit.Assert.assertEquals(expected.getRegistryId(), actual.getRegistryId()); }</code><technical_language>fully qualified name here</technical_language>

Target:
private void compareRegistryInfo(EndpointRegistryInfo expected, EndpointRegistryInfo actual) { Assert.assertEquals(expected.getUuid(), actual.getUuid()); Assert.assertEquals(expected.getName(), actual.getName()); Assert.assertEquals(expected.getMode(), actual.getMode()); Assert.assertEquals(expected.getType(), actual.getType()); Assert.assertEquals(expected.getOwner(), actual.getOwner()); Assert.assertEquals(expected.getRegistryId(), actual.getRegistryId()); }
Source:
<code>void onExecute(CommandSender sender, String[] args) { String searchedName = args[args.length - 1]; Entity[] entities = CommandUtils.getTargets(sender, searchedName); if (entities == null) { sender.sendMessage(pluginHeader + langEntityNotPlayer); return; } for (int i = 0; i < entities.length; i++) { if (entities[i] == null) { sender.sendMessage(pluginHeader + StringUtils.replaceOnce(langPlayerOffline, "PLAYER", searchedName)); break; } try { onExecuteForPlayer(sender, args, (Player) entities[i]); } catch (ClassCastException e) { <START> sender.sendMessage(pluginHeader + langEntityNotPlayer); <END> } } }</code><technical_language>error message more helpful if included ENTITY placeholder? write lines: StringUtils.replaceOnce(langEntityNotPlayer, "ENTITY", entity.getType().name())</technical_language>

Target:
void onExecute(CommandSender sender, String[] args) { String searchedName = args[args.length - 1]; Entity[] entities = CommandUtils.getTargets(sender, searchedName); if (entities == null) { sender.sendMessage(pluginHeader + langEntityNotPlayer); return; } for (int i = 0; i < entities.length; i++) { if (entities[i] == null) { sender.sendMessage(pluginHeader + StringUtils.replaceOnce(langPlayerOffline, "PLAYER", searchedName)); break; } if (entities[i] instanceof Player) { onExecuteForPlayer(sender, args, (Player) entities[i]); } else { sender.sendMessage( pluginHeader + StringUtils.replaceOnce(langEntityNotPlayer, "ENTITY", entities[i].getType().name())); } } }
Source:
<code><START> public static DateTime setEndValidTime(DateTime endValidTimeArg, DateTime issueInstant) { <END> DateTime endValidTime = endValidTimeArg; final DateTime now = new DateTime(); if (endValidTime == null || endValidTime.isBefore(now.plusMinutes(5))) { endValidTime = now.plusMinutes(5); } if (endValidTime.isBefore(issueInstant)) { endValidTime = issueInstant.plusMinutes(5); } return endValidTime; }</code><technical_language>here, public</technical_language>

Target:
private static DateTime setEndValidTime(DateTime endValidTimeArg, DateTime issueInstant) { DateTime endValidTime = endValidTimeArg; final DateTime now = new DateTime(); if (endValidTime == null || endValidTime.isBefore(now.plusMinutes(5))) { endValidTime = now.plusMinutes(5); } if (endValidTime.isBefore(issueInstant)) { endValidTime = issueInstant.plusMinutes(5); } return endValidTime; }
Source:
<code>public LabelWithToolTip(String text, int length) { this(text); <START> if (length > -1 && text.length() > length) { <END> setText(text.substring(0, length - 3) + "..."); } }</code><technical_language>I get rid of condition now, due change above</technical_language>

Target:
public LabelWithToolTip(String text, int length) { super(text); if (length > -1 && text.length() > length) { setText(text.substring(0, length - 3) + "..."); } tooltipPanel.setWidget(tooltip); tooltipPanel.getElement().getStyle().setZIndex(1); setTitle(text); registerHandlers(); }
Source:
<code><START> public static Collection testSheetParameters() { <END> File testFile = new File(ConferenceSchedulingScoreRulesXlsxTest.class.getResource(testFileName).getFile()); try (InputStream in = new BufferedInputStream(new FileInputStream(testFile))) { XSSFWorkbook workbook = new XSSFWorkbook(in); ConferenceSolution initialSolution = new ConferenceSchedulingXlsxFileIO(false).read(testFile); TestConferenceSchedulingScoreRulesReader reader = new TestConferenceSchedulingScoreRulesReader(workbook, initialSolution); List<Object[]> parametersList = new ArrayList<>(); for (Object[] parameters = reader.nextTestSheetParameters(); parameters != null; parameters = reader.nextTestSheetParameters()) { parametersList.add(parameters); } return parametersList; } catch (IOException | RuntimeException e) { throw new IllegalStateException("Failed reading inputSolutionFile (" + testFile.getName() + ").", e); } }</code><technical_language>suggestion public static Collection<Object[]> testSheetParameters() { * warnings: -1 * consistency: +1</technical_language>

Target:
public static Collection<Object[]> testSheetParameters() { File testFile = new File(ConferenceSchedulingScoreRulesXlsxTest.class.getResource(testFileName).getFile()); try (InputStream in = new BufferedInputStream(new FileInputStream(testFile))) { XSSFWorkbook workbook = new XSSFWorkbook(in); ConferenceSolution initialSolution = new ConferenceSchedulingXlsxFileIO(false).read(testFile); TestConferenceSchedulingScoreRulesReader reader = new TestConferenceSchedulingScoreRulesReader(workbook, initialSolution); List<Object[]> parametersList = new ArrayList<>(); for (Object[] parameters = reader.nextTestSheetParameters(); parameters != null; parameters = reader.nextTestSheetParameters()) { parametersList.add(parameters); } return parametersList; } catch (IOException | RuntimeException e) { throw new IllegalStateException("Failed reading inputSolutionFile (" + testFile.getName() + ").", e); } }
Source:
<code>public Map<String, String> getSessionProperties(String sessionId) throws SqlExecutionException { <START> return null; <END> }</code><technical_language>here. returning a Collections.emptyMap() better</technical_language>

Target:
public Map<String, String> getSessionProperties(String sessionId) throws SqlExecutionException { throw new UnsupportedOperationException("Not implemented."); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == StageActivity.STAGE_ACTIVITY_FINISH) { SensorHandler.stopSensorListeners(); FaceDetectionHandler.stopFaceDetection(); } if (requestCode != RESULT_OK && SettingsFragment.isCastSharedPreferenceEnabled(this) && ProjectManager.getInstance().getCurrentProject().isCastProject() && !CastManager.getInstance().isConnected()) { CastManager.getInstance().openDeviceSelectorOrDisconnectDialog(this); } Uri uri; switch (requestCode) { case PreStageActivity.REQUEST_RESOURCES_INIT: startStageActivity(); break; case SPRITE_POCKET_PAINT: uri = Uri.fromFile(new File(data.getStringExtra(EXTRA_PICTURE_PATH_POCKET_PAINT))); addSpriteFromUri(uri); break; case SPRITE_LIBRARY: uri = Uri.fromFile(new File(data.getStringExtra(MEDIA_FILE_PATH))); addSpriteFromUri(uri); break; case SPRITE_FILE: uri = data.getData(); addSpriteFromUri(uri); break; case SPRITE_CAMERA: uri = new ImportFromCameraLauncher(this).getCacheCameraUri(); addSpriteFromUri(uri); <START> break; <END> } }</code><technical_language>this nicer camera intent return uri a result data instead of making a new importFromCamerLauncher reproduce uri again</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == StageActivity.STAGE_ACTIVITY_FINISH) { SensorHandler.stopSensorListeners(); FaceDetectionHandler.stopFaceDetection(); } if (resultCode != RESULT_OK) { if (SettingsFragment.isCastSharedPreferenceEnabled(this) && ProjectManager.getInstance().getCurrentProject().isCastProject() && !CastManager.getInstance().isConnected()) { CastManager.getInstance().openDeviceSelectorOrDisconnectDialog(this); } return; } Uri uri; switch (requestCode) { case PreStageActivity.REQUEST_RESOURCES_INIT: startStageActivity(); break; case SPRITE_POCKET_PAINT: uri = Uri.fromFile(new File(data.getStringExtra(EXTRA_PICTURE_PATH_POCKET_PAINT))); addSpriteFromUri(uri); break; case SPRITE_LIBRARY: uri = Uri.fromFile(new File(data.getStringExtra(MEDIA_FILE_PATH))); addSpriteFromUri(uri); break; case SPRITE_FILE: uri = data.getData(); addSpriteFromUri(uri); break; case SPRITE_CAMERA: uri = new ImportFromCameraLauncher(this).getCacheCameraUri(); addSpriteFromUri(uri); break; } }
Source:
<code>public void testFreestyleWithFalsePublisher() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.getPublishersList().add(new TrueFalsePublisher(true)); p.getPublishersList().add(new TrueFalsePublisher(false)); p.getPublishersList().add(new ResultWriterPublisher("result.txt")); p.getPublishersList().add(new ArtifactArchiver("result.txt", "", false)); FreeStyleBuild b = p.scheduleBuild2(0).get(); assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE); File file = new File(b.getArtifactsDir(), "result.txt"); assertTrue("ArtifactArchiver is executed even prior publisher fails.", file.exists()); <START> assertTrue("Second publisher must see FAILURE status", FileUtils.readFileToString(file).equals(Result.FAILURE.toString())); <END> }</code><technical_language>this publisher (ResultWriterPublisher) talking about, right</technical_language>

Target:
public void testFreestyleWithFalsePublisher() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.getPublishersList().add(new TrueFalsePublisher(true)); p.getPublishersList().add(new TrueFalsePublisher(false)); p.getPublishersList().add(new ResultWriterPublisher("result.txt")); final ArtifactArchiver artifactArchiver = new ArtifactArchiver("result.txt"); artifactArchiver.setOnlyIfSuccessful(false); p.getPublishersList().add(artifactArchiver); FreeStyleBuild b = p.scheduleBuild2(0).get(); assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE); File file = new File(b.getArtifactsDir(), "result.txt"); assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists()); assertTrue("Publisher, after publisher with return false status, must see FAILURE status", FileUtils.readFileToString(file).equals(Result.FAILURE.toString())); }