auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TableResult executeSql(String statement) { List<Operation> operations = parser.parse(statement); if (operations.size() != 1) { throw new TableException(UNSUPPORTED_QUERY_IN_EXECUTE_SQL_MSG); } Operation operation = operations.get(0); if (operation instanceof CreateTableOperation || operation instanceof DropTableOperation || operation instanceof AlterTableOperation || operation instanceof CreateDatabaseOperation || operation instanceof DropDatabaseOperation || operation instanceof AlterDatabaseOperation || operation instanceof CreateCatalogFunctionOperation || operation instanceof CreateTempSystemFunctionOperation || operation instanceof DropCatalogFunctionOperation || operation instanceof DropTempSystemFunctionOperation || operation instanceof AlterCatalogFunctionOperation || operation instanceof CreateCatalogOperation || operation instanceof UseCatalogOperation || operation instanceof UseDatabaseOperation || operation instanceof ShowCatalogsOperation || operation instanceof ShowDatabasesOperation || operation instanceof ShowTablesOperation || operation instanceof ShowFunctionsOperation) { return executeOperation(operation); } else { throw new TableException(UNSUPPORTED_QUERY_IN_EXECUTE_SQL_MSG); } }

Target:
public TableResult executeSql(String statement) { List<Operation> operations = parser.parse(statement); if (operations.size() != 1) { throw new TableException(UNSUPPORTED_QUERY_IN_EXECUTE_SQL_MSG); } return executeOperation(operations.get(0)); }
Source:
private void verifyLog(String message) { elasticSleep(3000); assertTrue(slave.getLog().contains(message)); }

Target:
private void verifyLog(String message) { assertTrue(slave.getLog().contains(message)); }
Source:
public void testPruneExpiredTombstones() throws Exception { List<String> keepFilenames = new ArrayList<>( Arrays.asList("/dir1/fileK1", "/dir1/fileK2", "/dir1/fileK3")); List<String> removeFilenames = new ArrayList<>( Arrays.asList("/dir1/fileR1", "/dir1/fileR2", "/dir1/fileR3")); long cutoff = 9001; for(String fN : keepFilenames) { final PathMetadata pathMetadata = new PathMetadata(makeFileStatus(fN, 1)); pathMetadata.setLastUpdated(9002L); ms.put(pathMetadata); } for(String fN : removeFilenames) { final PathMetadata pathMetadata = new PathMetadata(makeFileStatus(fN, 1)); pathMetadata.setLastUpdated(9000L); pathMetadata.setIsDeleted(true); ms.put(pathMetadata); } ms.prune(MetadataStore.PruneMode.TOMBSTONES_BY_LASTUPDATED, cutoff); if(!allowMissing()) { for (String fN : keepFilenames) { final PathMetadata pathMetadata = ms.get(strToPath(fN)); assertNotNull(pathMetadata); } } for(String fN : removeFilenames) { final PathMetadata pathMetadata = ms.get(strToPath(fN)); assertNull(pathMetadata); } }

Target:
public void testPruneExpiredTombstones() throws Exception { List<String> keepFilenames = new ArrayList<>( Arrays.asList("/dir1/fileK1", "/dir1/fileK2", "/dir1/fileK3")); List<String> removeFilenames = new ArrayList<>( Arrays.asList("/dir1/fileR1", "/dir1/fileR2", "/dir1/fileR3")); long cutoff = 9001; for(String fN : keepFilenames) { final PathMetadata pathMetadata = new PathMetadata(makeFileStatus(fN, 1)); pathMetadata.setLastUpdated(9002L); ms.put(pathMetadata); } for(String fN : removeFilenames) { final PathMetadata pathMetadata = new PathMetadata(makeFileStatus(fN, 1)); pathMetadata.setLastUpdated(9000L); pathMetadata.setIsDeleted(true); ms.put(pathMetadata); } ms.prune(MetadataStore.PruneMode.TOMBSTONES_BY_LASTUPDATED, cutoff); if(!allowMissing()) { for (String fN : keepFilenames) { final PathMetadata pathMetadata = ms.get(strToPath(fN)); assertNotNull("Kept files should be in the metastore after prune", pathMetadata); } } for(String fN : removeFilenames) { final PathMetadata pathMetadata = ms.get(strToPath(fN)); assertNull("Expired tombstones should be removed from metastore after " + "the prune.", pathMetadata); } }
Source:
private void processSessionEndpoint() { if (getIntent().hasExtra(SESSION_ENDPOINT_ID)) { Endpoint endpoint = validateIntentForSessionEndpoint(getIntent()); if (endpoint != null) { Vector<String> endpointArguments = endpoint.getArguments(); ArrayList<String> intentArguments = getIntent().getStringArrayListExtra(SESSION_ENDPOINT_ARGUMENTS); HashMap<String, String> compositeArguments = new HashMap<>(endpointArguments.size()); for (int i = 0; i < endpointArguments.size(); i++) { compositeArguments.put(endpointArguments.elementAt(i), intentArguments.get(i)); } CommCareApplication.instance().getCurrentSessionWrapper() .executeStackActions(endpoint.getStackOperations(), compositeArguments); } } }

Target:
private void processSessionEndpoint() { if (getIntent().hasExtra(SESSION_ENDPOINT_ID)) { Endpoint endpoint = validateIntentForSessionEndpoint(getIntent()); if (endpoint != null) { Bundle intentArgumentsAsBundle = getIntent().getBundleExtra(SESSION_ENDPOINT_ARGUMENTS_BUNDLE); ArrayList<String> intentArgumentsAsList = getIntent().getStringArrayListExtra(SESSION_ENDPOINT_ARGUMENTS_LIST); CommCareApplication.instance().getCurrentSessionWrapper().reset(); try { if (intentArgumentsAsBundle != null) { CommCareApplication.instance().getCurrentSessionWrapper() .executeEndpointStack(endpoint, AndroidUtil.bundleAsMap(intentArgumentsAsBundle)); } else { CommCareApplication.instance().getCurrentSessionWrapper() .executeEndpointStack(endpoint, intentArgumentsAsList); } } catch (Endpoint.InvalidEndpointArgumentsException e) { String noArgumentWithNameError = org.commcare.utils.StringUtils.getStringRobust( this, R.string.session_endpoint_no_argument_with_name, new String[]{e.getArgumentName(), endpoint.getId()}); UserfacingErrorHandling.createErrorDialog(this, noArgumentWithNameError, true); } catch (Endpoint.InvalidNumberOfEndpointArgumentsException e) { String invalidEndpointArgsError = org.commcare.utils.StringUtils.getStringRobust( this, R.string.session_endpoint_invalid_arguments, new String[]{ endpoint.getId(), intentArgumentsAsBundle != null ? StringUtils.join(intentArgumentsAsBundle, ",") : String.valueOf(intentArgumentsAsList.size()), StringUtils.join(endpoint.getArguments(), ",")}); UserfacingErrorHandling.createErrorDialog(this, invalidEndpointArgsError, true); } } } }
Source:
public List<Metric> transform(List<Metric> metrics, List<String> constants) { SystemAssert.requireArgument(metrics != null, "Cannot transform null metrics"); if (metrics.isEmpty()) { return metrics; } SystemAssert.requireArgument(constants.size() == 1 || constants.size()==4, "Downsampler Transform can either have exactly one constant or 4 constants"); SystemAssert.requireArgument(constants.get(0).contains("-"), "This downsampler expression is not valid."); String[] expArr = constants.get(0).split("-"); SystemAssert.requireArgument(expArr.length == 2, "This downsampler expression need both unit and type."); Long startTime = null; Long endTime = null; Double defaultValue = null; if(constants.size()==4) { long currMinuteStartTime = 60*1000*(System.currentTimeMillis()/(60*1000)); startTime = MetricReader.getTime(currMinuteStartTime, constants.get(1)); endTime = MetricReader.getTime(currMinuteStartTime, constants.get(2)); defaultValue = Double.parseDouble(constants.get(3)); } String windowSizeStr = expArr[0]; Long windowSize = getWindowInSeconds(windowSizeStr) * 1000; String windowUnit = windowSizeStr.substring(windowSizeStr.length() - 1); String downsampleType = expArr[1]; for (Metric metric : metrics) { metric.setDatapoints(createDownsampleDatapoints(metric.getDatapoints(), windowSize, downsampleType, windowUnit, startTime, endTime, defaultValue)); } return metrics; }

Target:
public List<Metric> transform(List<Metric> metrics, List<String> constants) { SystemAssert.requireArgument(metrics != null, "Cannot transform null metrics"); if (metrics.isEmpty()) { return metrics; } SystemAssert.requireArgument(constants.size() == 1 || constants.size()==4, "Downsampler Transform can either have exactly one constant or 4 constants"); SystemAssert.requireArgument(constants.get(0).contains("-"), "This downsampler expression is not valid."); String[] expArr = constants.get(0).split("-"); SystemAssert.requireArgument(expArr.length == 2, "This downsampler expression need both unit and type."); Long startTime = null; Long endTime = null; Double defaultValue = null; if(constants.size()==4) { long currMinuteEndTime = 60*1000*(System.currentTimeMillis()/(60*1000)) + 60*1000; startTime = MetricReader.getTime(currMinuteEndTime, constants.get(1)); endTime = MetricReader.getTime(currMinuteEndTime, constants.get(2)); defaultValue = Double.parseDouble(constants.get(3)); } String windowSizeStr = expArr[0]; Long windowSize = getWindowInSeconds(windowSizeStr) * 1000; String windowUnit = windowSizeStr.substring(windowSizeStr.length() - 1); String downsampleType = expArr[1]; for (Metric metric : metrics) { metric.setDatapoints(createDownsampleDatapoints(metric.getDatapoints(), windowSize, downsampleType, windowUnit, startTime, endTime, defaultValue)); } return metrics; }
Source:
protected JcloudsLocation newLocationFromString(String spec, brooklyn.location.LocationRegistry registry, Map properties, Map locationFlags) { JcloudsSpecParser details = JcloudsSpecParser.parse(spec, false); String locationName = (String) locationFlags.get("name"); boolean isProvider = details.isProvider(); String providerOrApi = details.providerOrApi; if (Strings.isEmpty(providerOrApi)) { throw new IllegalArgumentException("Cloud provider/API type not specified in spec \""+spec+"\""); } if (!isProvider && !details.isApi()) { throw new NoSuchElementException("Cloud provider/API type "+providerOrApi+" is not supported by jclouds"); } Map allProperties = getAllProperties(registry, properties, locationFlags); Map jcloudsProperties = JcloudsPropertiesFromEnv.getJcloudsPropertiesFromEnv(providerOrApi, locationName, allProperties); if (isProvider) { return new JcloudsLocationFactory(jcloudsProperties).newLocation(details.parameter); } else { return new JcloudsLocationFactory(jcloudsProperties).newLocation(null); } }

Target:
protected JcloudsLocation newLocationFromString(String spec, brooklyn.location.LocationRegistry registry, Map properties, Map locationFlags) { JcloudsSpecParser details = JcloudsSpecParser.parse(spec, false); String locationName = (String) locationFlags.get("name"); boolean isProvider = details.isProvider(); String providerOrApi = details.providerOrApi; if (Strings.isEmpty(providerOrApi)) { throw new IllegalArgumentException("Cloud provider/API type not specified in spec \""+spec+"\""); } if (!isProvider && !details.isApi()) { throw new NoSuchElementException("Cloud provider/API type "+providerOrApi+" is not supported by jclouds"); } Map allProperties = getAllProperties(registry, properties, locationFlags); Map jcloudsProperties = JcloudsPropertiesFromBrooklynProperties.getJcloudsProperties(providerOrApi, locationName, allProperties); if (isProvider) { return new JcloudsLocationFactory(jcloudsProperties).newLocation(details.parameter); } else { return new JcloudsLocationFactory(jcloudsProperties).newLocation(null); } }
Source:
public BaseVisualizationModel( Network<N, E> network, LayoutAlgorithm<N, Point2D> layoutAlgorithm, Function<N, Point2D> initializer, Dimension layoutSize) { Preconditions.checkNotNull(network); Preconditions.checkNotNull(layoutAlgorithm); Preconditions.checkNotNull(layoutSize); this.layoutAlgorithm = layoutAlgorithm; this.layoutModel = createLayoutModel(network, layoutSize); if (this.layoutModel instanceof LayoutModel.ChangeSupport) { ((LayoutModel.ChangeSupport) layoutModel).addChangeListener(this); } this.network = network; if (initializer != null) { this.layoutModel.setInitializer(initializer); } if (layoutAlgorithm != null) { this.layoutModel.accept(layoutAlgorithm); } }

Target:
public BaseVisualizationModel( Network<N, E> network, LayoutAlgorithm<N, Point2D> layoutAlgorithm, Function<N, Point2D> initializer, Dimension layoutSize) { Preconditions.checkNotNull(network); Preconditions.checkNotNull(layoutSize); Preconditions.checkArgument(layoutSize.width > 0, "width must be > 0"); Preconditions.checkArgument(layoutSize.height > 0, "height must be > 0"); this.layoutAlgorithm = layoutAlgorithm; this.layoutModel = SpatialQuadTreeLayoutModel.<N, Point2D>builder() .setGraph(network.asGraph()) .setPointModel(POINT_MODEL) .setSize(layoutSize.width, layoutSize.height) .build(); if (this.layoutModel instanceof LayoutModel.ChangeSupport) { ((LayoutModel.ChangeSupport) layoutModel).addChangeListener(this); } this.network = network; if (initializer != null) { this.layoutModel.setInitializer(initializer); } this.layoutModel.accept(layoutAlgorithm); }
Source:
public boolean rollback(String pushId) throws PublisherException { if (marked.size() == 0) return false; boolean matched = false; LinkNode prevNode = null; Node lastNode = current; for (Iterator<Node> it = marked.iterator(); it.hasNext(); ) { Node dataNode = it.next(); if (matched) { it.remove(); if (dataNode != lastNode) { LinkNode newNode = new LinkNode(dataNode); prevNode.setNext(newNode); prevNode = newNode; } } else if (dataNode.get().getPushId() == pushId || pushId == null) { if (dataNode == lastNode) return true; prevNode = new LinkNode(dataNode); current = prevNode; matched = true; } } if (prevNode != null) prevNode.setNext(lastNode); return matched; }

Target:
public boolean rollback(String pushId) throws PublisherException { if (current.data.isPushId(pushId)) return true; Node last = current; for (Data data : marked) { if (data.isPushId(pushId)) { current = new LinkingNode(Data.EMPTY, last); while (!marked.isEmpty() && !marked.getFirst().isPushId(pushId)) marked.removeFirst(); return true; } last = new LinkingNode(data, last); } return false; }
Source:
private static void checkClockProviderHasDefaultProperties(ClockProvider clockProvider) { Clock clock = clockProvider.getClock(); Clock systemClock = Clock.systemDefaultZone(); if ( !systemClock.getZone().equals( clock.getZone() ) ) { throw new RuntimeException( "The default clock provider should use the default system time zone." ); } if ( Math.abs( clock.millis() - systemClock.millis() ) > ACCEPTABLE_DEVIATION_IN_MS ) { throw new RuntimeException( "The default clock provider should return the system time." ); } }

Target:
private static void checkClockProviderHasDefaultProperties(ClockProvider clockProvider) { Clock clock = clockProvider.getClock(); Clock systemClock = Clock.systemDefaultZone(); if ( !systemClock.getZone().equals( clock.getZone() ) ) { throw new AssertionError( "The default clock provider should use the default system time zone." ); } if ( Math.abs( clock.millis() - systemClock.millis() ) > ACCEPTABLE_CLOCK_DEVIATION_IN_MS ) { throw new AssertionError( "The default clock provider should return the system time." ); } }
Source:
public void testInvalidPageRanges() { String url = "/v2/regions/20:60000-62000/variants?species=mmusculus&assembly=grcm38?&page=1000&size=1"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertEquals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, response.getStatusCode()); assertEquals("The correct page range is from 0 to 0 for the given page size", response.getBody()); }

Target:
public void testInvalidPageRanges() { String url = "/v2/regions/20:60000-62000/variants?species=mmusculus&assembly=grcm38?&pageNumber=1000&" + "pageSize=1"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); assertEquals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, response.getStatusCode()); assertEquals("For the given page size, there are 1 page(s), so the correct page range is from 0 to 0" + " (both included).", response.getBody()); }
Source:
private boolean initUpdate() { File updateDir = new File(UPDATE_DIRECTORY); if (!updateDir.exists() && !updateDir.mkdirs()) { logger.error("Failed to create update directories"); return false; } File replaceAndExecuteJar = new File(UPDATE_DIRECTORY + File.separator + UPDATE_RESTARTER_APP_NAME); if (!replaceAndExecuteJar.exists()) { try (InputStream in = UpdateManager.class.getResourceAsStream("replaceAndExecute.jar"); OutputStream out = new FileOutputStream(replaceAndExecuteJar);) { IOUtils.copy(in, out); } catch (IOException e) { logger.error("Can't copy replace and execute JAR", e); return false; } } return true; }

Target:
private boolean initUpdate() { logger.info("Initiating updater"); File updateDir = new File(UPDATE_DIRECTORY); if (!updateDir.exists() && !updateDir.mkdirs()) { logger.error("Failed to create update directories"); return false; } return extractJarUpdater(); }
Source:
public void testSharedPreferencesClearedAfterLoggingException() { Context context = InstrumentationRegistry.getTargetContext(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPreferences.edit(); Exception exception = new RuntimeException("Error"); CrashReporter crashReporter = new CrashReporter(context); crashReporter.setIsCrashReportEnabled(true); crashReporter.storeUnhandledException(exception); editor.commit(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").length() > 0); crashReporter.sendUnhandledCaughtException(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").length() == 0); }

Target:
public void testSharedPreferencesClearedAfterLoggingException() { CrashReporter.storeUnhandledException(exception); assertFalse(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); CrashReporter.sendUnhandledCaughtException(); assertTrue(sharedPreferences.getString(CrashReporter.EXCEPTION_FOR_REPORT, "").isEmpty()); }
Source:
long gtk_size_allocate (long widget, long allocation) { useFixedWidth = false; GtkAllocation widgetAllocation = new GtkAllocation (); GTK.gtk_widget_get_allocation (widget, widgetAllocation); boolean minimumResizeSignal = (widgetAllocation.width == 1 && widgetAllocation.height == 1); boolean movingSignal = (widgetAllocation.x == 0 && widgetAllocation.y == 0); int x = widgetAllocation.x; int width = widgetAllocation.width; if (x != lastX && !movingSignal) { lastX = x; sendEvent (SWT.Move); } if (width != lastWidth && !minimumResizeSignal) { boolean useNewWidth = true; if (GTK.GTK_VERSION >= OS.VERSION(3, 22, 0) && !GTK.GTK4 && OS.GTK_OVERLAY_SCROLLING_DISABLED) { int scrollbarWidth = parent.vScrollBarWidth(); boolean isLastColumn = parent.columns[parent.columnCount - 1] == this; if (isLastColumn && secondToLastWidth == width && Math.abs(lastWidth - width) == scrollbarWidth) { useNewWidth = false; } } if (useNewWidth) { secondToLastWidth = lastWidth; lastWidth = width; sendEvent (SWT.Resize); } } GTK.gtk_widget_set_can_focus(buttonHandle, false); return 0; }

Target:
long gtk_size_allocate (long widget, long allocation) { useFixedWidth = false; GtkAllocation widgetAllocation = new GtkAllocation (); GTK.gtk_widget_get_allocation (widget, widgetAllocation); boolean minimumResizeSignal = (widgetAllocation.width == 1 && widgetAllocation.height == 1); boolean movingSignal = (widgetAllocation.x == 0 && widgetAllocation.y == 0); int x = widgetAllocation.x; int width = widgetAllocation.width; if (x != lastX && !movingSignal) { lastX = x; sendEvent (SWT.Move); } if (width != lastWidth && !minimumResizeSignal) { boolean useNewWidth = true; if (GTK.GTK_VERSION >= OS.VERSION(3, 22, 0) && !GTK.GTK4 && OS.GTK_OVERLAY_SCROLLING_DISABLED) { int scrollbarWidth = parent.vScrollBarWidth(); boolean isLastColumn = parent.columnCount > 0 && parent.columns[parent.columnCount - 1] == this; if (isLastColumn && secondToLastWidth == width && Math.abs(lastWidth - width) == scrollbarWidth) { useNewWidth = false; } } if (useNewWidth) { secondToLastWidth = lastWidth; lastWidth = width; sendEvent (SWT.Resize); } } GTK.gtk_widget_set_can_focus(buttonHandle, false); return 0; }
Source:
public Subscriber<? super T> call(final Subscriber<? super T> child) { final AtomicLong requested = new AtomicLong(0); final ParentSubscriber<T> parent = new ParentSubscriber<T>(child, hasDefaultValue, defaultValue, requested); child.setProducer(new Producer() { @Override public void request(long n) { if (n > 0) { long numToRequest = Math.min(2 - requested.get(), n); if (numToRequest > 0) parent.requestMore(numToRequest); } } }); child.add(parent); return parent; }

Target:
public Subscriber<? super T> call(final Subscriber<? super T> child) { final ParentSubscriber<T> parent = new ParentSubscriber<T>(child, hasDefaultValue, defaultValue); child.setProducer(new Producer() { private final AtomicBoolean requestedTwo = new AtomicBoolean(false); @Override public void request(long n) { if (n > 0 && requestedTwo.compareAndSet(false, true)) { parent.requestMore(2); } } }); child.add(parent); return parent; }
Source:
public void drag(SWTBotTimeGraphEntry entry1, long t1, SWTBotTimeGraphEntry entry2, long t2, int mouseButton) { Point pDown = entry1.getPointForTime(t1); Point pUp = entry2.getPointForTime(t2); notify(SWT.MouseEnter); notify(SWT.MouseMove, createMouseEvent(pDown.x, pDown.y, 0, SWT.NONE, 0)); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseDown, createMouseEvent(pDown.x, pDown.y, 1, mouseButton, 1)); notify(SWT.DragDetect, createMouseEvent(pDown.x, pDown.y, 0, mouseButton, 0)); notify(SWT.MouseMove, createMouseEvent(pDown.x, pDown.y, 1, mouseButton, 1)); notify(SWT.MouseMove, createMouseEvent(pUp.x, pUp.y, 0, mouseButton, 0)); notify(SWT.MouseUp, createMouseEvent(pUp.x, pUp.y, 1, mouseButton, 1)); notify(SWT.MouseMove, createMouseEvent(pUp.x, pUp.y, 0, SWT.NONE, 0)); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); }

Target:
public void drag(SWTBotTimeGraphEntry entry1, long t1, SWTBotTimeGraphEntry entry2, long t2, int mouseButton) { int button = 1; if(mouseButton == SWT.BUTTON2) { button = 2; } if(mouseButton == SWT.BUTTON3) { button = 3; } if(mouseButton == SWT.BUTTON4) { button = 4; } if(mouseButton == SWT.BUTTON5) { button = 5; } Point pDown = entry1.getPointForTime(t1); Point pUp = entry2.getPointForTime(t2); notify(SWT.MouseEnter); notify(SWT.MouseMove, createMouseEvent(pDown.x, pDown.y, 0, SWT.NONE, 0)); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseDown, createMouseEvent(pDown.x, pDown.y, button, mouseButton, 1)); notify(SWT.DragDetect, createMouseEvent(pDown.x, pDown.y, 0, mouseButton, 0)); notify(SWT.MouseMove, createMouseEvent(pDown.x, pDown.y, button, mouseButton, 1)); notify(SWT.MouseMove, createMouseEvent(pUp.x, pUp.y, 0, mouseButton, 0)); notify(SWT.MouseUp, createMouseEvent(pUp.x, pUp.y, button, mouseButton, 1)); notify(SWT.MouseMove, createMouseEvent(pUp.x, pUp.y, 0, SWT.NONE, 0)); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); }
Source:
public Document cmisDocument(CmisObject cmisObject) { org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document) cmisObject; DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, doc.getId())); ObjectType objectType = cmisObject.getType(); if (objectType.isBaseType()) { writer.setPrimaryType(NodeType.NT_FILE); } else { writer.setPrimaryType(objectType.getId()); } List<Folder> parents = doc.getParents(); ArrayList parentIds = new ArrayList(); for (Folder f : parents) { parentIds.add(ObjectId.toString(ObjectId.Type.OBJECT, f.getId())); } writer.setParents(parentIds); writer.addMixinType(NodeType.MIX_CREATED); writer.addMixinType(NodeType.MIX_LAST_MODIFIED); writer.addMixinType(NodeType.MIX_REFERENCEABLE); cmisProperties(doc, writer); writer.addChild(ObjectId.toString(ObjectId.Type.CONTENT, doc.getId()), JcrConstants.JCR_CONTENT); return writer.document(); }

Target:
public Document cmisDocument(CmisObject cmisObject) { org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document) cmisObject; DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, doc.getId())); ObjectType objectType = cmisObject.getType(); if (objectType.isBaseType()) { writer.setPrimaryType(NodeType.NT_FILE); } else { writer.setPrimaryType(objectType.getId()); } List<Folder> parents = doc.getParents(); ArrayList parentIds = new ArrayList(); for (Folder f : parents) { parentIds.add(ObjectId.toString(ObjectId.Type.OBJECT, f.getId())); } writer.setParents(parentIds); writer.addMixinType(NodeType.MIX_REFERENCEABLE); cmisProperties(doc, writer); writer.addChild(ObjectId.toString(ObjectId.Type.CONTENT, doc.getId()), JcrConstants.JCR_CONTENT); return writer.document(); }
Source:
public void shouldParseParentPomFile() { Properties properties = new Properties(); properties.put("test.properties", "testParent"); properties.put("project.version", "0-27-SNAPSHOT"); InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("parentPom.xml"); pomInformation = new PomInformation(); pomInformation.parseParentPom(inputStream); PomInformation parentPom = pomInformation.getParentPomInformation(); assertEquals(properties, parentPom.getProperties()); Parent parentFromParsing = parentPom.getParent(); assertEquals("0.27-SNAPSHOT", parentFromParsing.getVersion()); assertEquals("motech", parentFromParsing.getArtifactId()); assertEquals("org.motechproject", parentFromParsing.getGroupId()); }

Target:
public void shouldParseParentPomFile() throws IOException { Properties properties = new Properties(); properties.put("test.properties", "testParent"); properties.put("project.version", "0-27-SNAPSHOT"); properties.put("project.artifactId", "motech-platform-server-api"); try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("parentPom.xml")) { pomInformation = new PomInformation(); pomInformation.parseParentPom(inputStream); } PomInformation parentPom = pomInformation.getParentPomInformation(); assertEquals(properties, parentPom.getProperties()); Parent parentFromParsing = parentPom.getParent(); assertEquals("0.27-SNAPSHOT", parentFromParsing.getVersion()); assertEquals("motech", parentFromParsing.getArtifactId()); assertEquals("org.motechproject", parentFromParsing.getGroupId()); }
Source:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) refreshInterval = Long.parseLong(refreshIntervalString); setProperlyConfigured(true); }

Target:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } setProperlyConfigured(true); }
Source:
public void testSetValue() { Variable v = getVariable(); assertFalse("newly created variable incorrectly appears to be assigned", v.isAssigned()); try{ v.setValue(getTypeExpression()); }catch(MultipleAssignmentException mae){ fail("MultipleAssignmentException thrown, but multiple assignment did not happen"); } try{ v.setValue(getTypeExpression()); fail("multiple assignment to variable was allowed"); }catch(MultipleAssignmentException mae){ } }

Target:
public void testSetValue() throws MultipleAssignmentException, VariableNotAssignedException { Variable v = getVariable(); v.setValue(getValueExpression()); assertEquals(getValueExpression().evaluate(), v.getValue()); }
Source:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); FileStore s; try { if (Files.exists(dir)) { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } if (!Files.isWritable(dir)) { return FALLBACK_TIMESTAMP_RESOLUTION; } } else { return FALLBACK_TIMESTAMP_RESOLUTION; } CompletableFuture<Optional<Duration>> f = CompletableFuture .supplyAsync(() -> { Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (!lock.tryLock()) { return Optional.empty(); } Optional<Duration> resolution; FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return Optional .of(c.getFsTimestampResolution()); } try { resolution = measureFsTimestampResolution(s, dir); if (resolution.isPresent()) { FileStoreAttributeCache cache = new FileStoreAttributeCache( resolution.get()); attributeCache.put(s, cache); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } } } finally { lock.unlock(); locks.remove(s); } return resolution; }); Optional<Duration> d = f.get(background.get() ? 50 : 2000, TimeUnit.MILLISECONDS); if (d.isPresent()) { return d.get(); } } catch (IOException | InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } catch (TimeoutException e) { } return FALLBACK_TIMESTAMP_RESOLUTION; }

Target:
private static Duration getFsTimestampResolution(Path file) { Path dir = Files.isDirectory(file) ? file : file.getParent(); FileStore s; try { if (Files.exists(dir)) { s = Files.getFileStore(dir); FileStoreAttributeCache c = attributeCache.get(s); if (c != null) { return c.getFsTimestampResolution(); } if (!Files.isWritable(dir)) { return FALLBACK_TIMESTAMP_RESOLUTION; } } else { return FALLBACK_TIMESTAMP_RESOLUTION; } CompletableFuture<Optional<Duration>> f = CompletableFuture .supplyAsync(() -> { Lock lock = locks.computeIfAbsent(s, l -> new ReentrantLock()); if (!lock.tryLock()) { return Optional.empty(); } Optional<Duration> resolution; try { FileStoreAttributeCache c = attributeCache .get(s); if (c != null) { return Optional .of(c.getFsTimestampResolution()); } resolution = measureFsTimestampResolution(s, dir); if (resolution.isPresent()) { FileStoreAttributeCache cache = new FileStoreAttributeCache( resolution.get()); attributeCache.put(s, cache); if (LOG.isDebugEnabled()) { LOG.debug(cache.toString()); } } } finally { lock.unlock(); locks.remove(s); } return resolution; }); Optional<Duration> d = f.get(background.get() ? 50 : 2000, TimeUnit.MILLISECONDS); if (d.isPresent()) { return d.get(); } } catch (IOException | InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } catch (TimeoutException e) { } return FALLBACK_TIMESTAMP_RESOLUTION; }
Source:
private void checkFields(CtModel model) { List<CtField<?>> fields = model.getElements(new TypeFilter<>(CtField.class)); fields.removeIf(v -> !v.isPrivate()); fields.removeIf(v -> v.getSimpleName().equals("serialVersionUID")); List<CtFieldRead<?>> fieldRead = model.getElements(new TypeFilter<>(CtFieldRead.class)); fieldRead.removeIf(v -> v.getVariable().getFieldDeclaration() == null); List<CtField<?>> fieldsWithRead = fields.stream() .filter(field -> fieldRead.stream().anyMatch(read -> read.getVariable().getFieldDeclaration().equals(field))) .collect(Collectors.toList()); fields.removeAll(fieldsWithRead); assertEquals("Some Fields have no read/write", Collections.emptyList(), fields); }

Target:
private void checkFields(CtModel model) { List<CtField<?>> fields = model.getElements(new TypeFilter<>(CtField.class)); fields.removeIf(v -> !v.isPrivate()); fields.removeIf(v -> v.getSimpleName().equals("serialVersionUID")); List<CtFieldRead<?>> fieldRead = model.getElements(new TypeFilter<>(CtFieldRead.class)); fieldRead.removeIf(v -> v.getVariable().getFieldDeclaration() == null); HashSet<CtField<?>> lookUp = fieldRead.stream() .map(CtFieldRead::getVariable) .map(v -> v.getFieldDeclaration()) .collect(Collectors.toCollection(HashSet::new)); List<CtField<?>> fieldsWithRead = fields.stream() .filter(field -> lookUp.contains(field)) .collect(Collectors.toList()); fields.removeAll(fieldsWithRead); assertEquals("Some Fields have no read/write", Collections.emptyList(), fields); }
Source:
default JobInstance getLastJobInstance(String jobName) { return null; }

Target:
default JobInstance getLastJobInstance(String jobName) { throw new UnsupportedOperationException(); }
Source:
private synchronized void ensureClient(boolean createNew) { try { if (s3Client != null && !createNew) { return; } s3Client = newS3Client(); } catch (Exception e) { LOG.warning(String.format("Exception while getting new s3 client. Error: %s. Continuing with old client.", e.getMessage())); } }

Target:
private synchronized void ensureClient(boolean createNew) throws Exception { if (s3Client != null && !createNew) { return; } s3Client = newS3Client(); }
Source:
void generateSmali(ClassNode cls) { Path path = cls.dex().getDexFile().getPath(); String className = Utils.makeQualifiedObjectName(cls.getClassInfo().getType().getObject()); try { DexBackedDexFile dexFile = DexFileFactory.loadDexFile(path.toFile(), Opcodes.getDefault()); boolean decompiled = false; for (DexBackedClassDef classDef : dexFile.getClasses()) { if (classDef.getType().equals(className)) { ClassDefinition classDefinition = new ClassDefinition(new BaksmaliOptions(), classDef); StringWriter sw = new StringWriter(); classDefinition.writeTo(new IndentingWriter(sw)); cls.setSmali(sw.toString()); decompiled = true; break; } } if (!decompiled) { LOG.error("Failed to find smali class {}", className); } } catch (IOException e) { LOG.error("Error generating smali", e); } }

Target:
void generateSmali(ClassNode cls) { Path path = cls.dex().getDexFile().getPath(); String className = Utils.makeQualifiedObjectName(cls.getClassInfo().getType().getObject()); try { DexBackedDexFile dexFile = DexFileFactory.loadDexFile(path.toFile(), Opcodes.getDefault()); boolean decompiled = false; for (DexBackedClassDef classDef : dexFile.getClasses()) { if (classDef.getType().equals(className)) { ClassDefinition classDefinition = new ClassDefinition(new BaksmaliOptions(), classDef); StringWriter sw = new StringWriter(); classDefinition.writeTo(new IndentingWriter(sw)); cls.setSmali(sw.toString()); decompiled = true; break; } } if (!decompiled) { LOG.error("Failed to find smali class {}", className); } } catch (Exception e) { LOG.error("Error generating smali", e); } }
Source:
protected void tearDownContext() { view.getComputeService().destroyNodesMatching(inGroup(nodeGroup)); super.tearDownContext(); }

Target:
protected void tearDownContext() { try { cleanup(); } catch (Exception e) { } super.tearDownContext(); }
Source:
public static void accountAndContainerNamePreconditionCheck(RestRequest restRequest) throws RestServiceException { String accountNameFromHeader = getHeader(restRequest.getArgs(), Headers.TARGET_ACCOUNT_NAME, false); String containerNameFromHeader = getHeader(restRequest.getArgs(), Headers.TARGET_CONTAINER_NAME, false); if (accountNameFromHeader != null) { Account targetAccount = getAccountFromArgs(restRequest.getArgs()); String accountNameFromBlobId = targetAccount.getName(); if (!accountNameFromHeader.equals(accountNameFromBlobId)) { throw new RestServiceException( "Account name: " + accountNameFromHeader + " from request doesn't match the account name from Blob id : " + accountNameFromBlobId, RestServiceErrorCode.PreconditionFailed); } if (containerNameFromHeader != null) { Container targetContainer = getContainerFromArgs(restRequest.getArgs()); String containerNameFromBlobId = targetContainer.getName(); if (!containerNameFromHeader.equals(containerNameFromBlobId)) { throw new RestServiceException("Container name: " + containerNameFromHeader + "from request doesn't match the container name from Blob id : " + containerNameFromBlobId, RestServiceErrorCode.PreconditionFailed); } } } }

Target:
public static void accountAndContainerNamePreconditionCheck(RestRequest restRequest) throws RestServiceException { String accountNameFromHeader = getHeader(restRequest.getArgs(), Headers.TARGET_ACCOUNT_NAME, false); String containerNameFromHeader = getHeader(restRequest.getArgs(), Headers.TARGET_CONTAINER_NAME, false); if (accountNameFromHeader != null) { Account targetAccount = getAccountFromArgs(restRequest.getArgs()); String accountNameFromBlobId = targetAccount.getName(); if (!accountNameFromHeader.equals(accountNameFromBlobId)) { throw new RestServiceException( "Account name: " + accountNameFromHeader + " from request doesn't match the account name from Blob id : " + accountNameFromBlobId, RestServiceErrorCode.PreconditionFailed); } if (containerNameFromHeader != null) { Container targetContainer = getContainerFromArgs(restRequest.getArgs()); String containerNameFromBlobId = targetContainer.getName(); if (!containerNameFromHeader.equals(containerNameFromBlobId)) { throw new RestServiceException("Container name: " + containerNameFromHeader + "from request doesn't match the container name from Blob id : " + containerNameFromBlobId, RestServiceErrorCode.PreconditionFailed); } } } else if (containerNameFromHeader != null) { throw new RestServiceException( "Only container name is set in request with no corresponding account name is not allowed.", RestServiceErrorCode.BadRequest); } }
Source:
private void addDefaultMessageHandlers() { messageListener.addHandler(AbortMessage.class, m -> { messageListener.removeAnyMessage(m.getTags()); return Response.empty(); }); messageListener.addHandler(ConfigMessage.class, new ConfigMessageHandler(this)); messageListener.addHandler(NormalMessage.class, m -> { messageListener.addMessage(m); return Response.empty(); }); messageListener.addHandler(ProjectMessage.class, new ProjectMessageHandler(this)); messageListener.addHandler(RefreshMessage.class, m -> { maybeRefreshIndexSearchers(m.getTags()); return Response.empty(); }); messageListener.addHandler(RepositoryMessage.class, new RepositoryMessageHandler(this)); messageListener.addHandler(StatsMessage.class, new StatsMessageHandler(this)); }

Target:
private void addDefaultMessageHandlers() { messageListener.addMessageHandler(AbortMessage.class, m -> { messageListener.removeAnyMessage(m.getTags()); return Response.empty(); }); messageListener.addMessageHandler(ConfigMessage.class, new ConfigMessageHandler(this)); messageListener.addMessageHandler(NormalMessage.class, m -> { messageListener.addMessage(m); return Response.empty(); }); messageListener.addMessageHandler(ProjectMessage.class, new ProjectMessageHandler(this)); messageListener.addMessageHandler(RefreshMessage.class, m -> { maybeRefreshIndexSearchers(m.getTags()); return Response.empty(); }); messageListener.addMessageHandler(RepositoryMessage.class, new RepositoryMessageHandler(this)); messageListener.addMessageHandler(StatsMessage.class, new StatsMessageHandler(this)); }
Source:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartErrorEvent emptySubprocess = getStartNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, getStartEventType()); assertGeneralSet(emptySubprocess.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertErrorEventExecutionSet(emptySubprocess.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, ""); assertDataIOSet(emptySubprocess.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_START_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); StartErrorEvent emptySubprocess = getStartNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, getStartEventType()); assertGeneralSet(emptySubprocess.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertErrorEventExecutionSet(emptySubprocess.getExecutionSet(), EMPTY_VALUE, NON_INTERRUPTING, EMPTY_VALUE); assertDataIOSet(emptySubprocess.getDataIOSet(), EMPTY_VALUE); }
Source:
public void runAtDriver(RuntimeContainer container) { String mlcpCommand = prepareMlcpCommand(); LOGGER.debug(MESSAGES.getMessage("messages.debug.command", mlcpCommand)); LOGGER.info(MESSAGES.getMessage("messages.info.startBulkLoad")); try { Process mlcpProcess = CommandExecutor.executeCommand(mlcpCommand); mlcpProcess.waitFor(); try (InputStream normalInput = mlcpProcess.getInputStream(); BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(normalInput)); InputStream errorInput = mlcpProcess.getErrorStream(); BufferedReader errorReader = new BufferedReader(new java.io.InputStreamReader(errorInput))) { while (reader.ready()) { System.out.println(reader.readLine()); } while (errorReader.ready()) { System.err.println(errorReader.readLine()); } LOGGER.info(MESSAGES.getMessage("messages.info.finishBulkLoad")); } catch (IOException e) { LOGGER.error(MESSAGES.getMessage("messages.error.ioexception", e.getMessage())); throw new ComponentException(e); } } catch (Exception e) { LOGGER.error(MESSAGES.getMessage("messages.error.exception", e.getMessage())); throw new ComponentException(e); } }

Target:
public void runAtDriver(RuntimeContainer container) { String mlcpCommand = prepareMlcpCommand(); LOGGER.debug(MESSAGES.getMessage("messages.debug.command", mlcpCommand)); LOGGER.info(MESSAGES.getMessage("messages.info.startBulkLoad")); try { Process mlcpProcess = CommandExecutor.executeCommand(mlcpCommand); try (InputStream normalInput = mlcpProcess.getInputStream(); InputStream errorInput = mlcpProcess.getErrorStream()) { Thread normalInputReadProcess = new Thread() { public void run() { try(BufferedReader reader = new BufferedReader(new InputStreamReader(normalInput))) { String line; while((line = reader.readLine()) != null) { System.out.println(line); } } catch(IOException ioe) { LOGGER.error(MESSAGES.getMessage("messages.error.ioexception", ioe.getMessage())); ioe.printStackTrace(); } } }; normalInputReadProcess.start(); Thread errorInputReadProcess = new Thread() { public void run() { try(BufferedReader reader = new BufferedReader(new InputStreamReader(errorInput))) { String line; while((line = reader.readLine()) != null) { System.err.println(line); } } catch(IOException ioe) { LOGGER.error(MESSAGES.getMessage("messages.error.ioexception", ioe.getMessage())); ioe.printStackTrace(); } } }; errorInputReadProcess.start(); mlcpProcess.waitFor(); normalInputReadProcess.interrupt(); errorInputReadProcess.interrupt(); LOGGER.info(MESSAGES.getMessage("messages.info.finishBulkLoad")); } } catch (Exception e) { LOGGER.error(MESSAGES.getMessage("messages.error.exception", e.getMessage())); throw new ComponentException(e); } }
Source:
private Metric predictAnomalies(Map<Long, Double> metricData) { Metric predictions = new Metric(getResultScopeName(), getResultMetricName()); Map<Long, Double> predictionDatapoints = new HashMap<>(); for (Map.Entry<Long, Double> entry : metricData.entrySet()) { Long timestamp = entry.getKey(); double value = entry.getValue(); try { double anomalyScore = calculateAnomalyScore(value); predictionDatapoints.put(timestamp, anomalyScore); } catch (ArithmeticException e) { continue; } } predictions.setDatapoints(new HashMap<>(predictionDatapoints)); return predictions; }

Target:
private Metric predictAnomalies(Map<Long, Double> metricData) { Metric predictions = new Metric(getResultScopeName(), getResultMetricName()); Map<Long, Number> predictionDatapoints = new HashMap<>(); for (Map.Entry<Long, Double> entry : metricData.entrySet()) { Long timestamp = entry.getKey(); double value = entry.getValue(); try { double anomalyScore = calculateAnomalyScore(value); predictionDatapoints.put(timestamp, anomalyScore); } catch (ArithmeticException e) { continue; } } predictions.setDatapoints(predictionDatapoints); return predictions; }
Source:
public void generate(final Ds3ApiSpec spec, final FileUtils fileUtils, final Path destDir) throws IOException { this.fileUtils = fileUtils; try { final ImmutableList<Enum> allEnums = getAllEnums(spec); final Set<String> enumNames = allEnums.stream().map(Enum::getName).collect(Collectors.toSet()); final ImmutableList<Struct> allStructs = getStructsOrderedList(spec, enumNames); final ImmutableList<Request> allRequests = getAllRequests(spec); generateHeader(allEnums, allStructs, allRequests); generateSource(allEnums, allStructs, allRequests); } catch (final ParseException e) { LOG.error("Caught exception: ", e); } }

Target:
public void generate(final Ds3ApiSpec spec, final FileUtils fileUtils, final Path destDir) throws IOException { this.fileUtils = fileUtils; try { final ImmutableList<Enum> allEnums = getAllEnums(spec); final ImmutableSet<String> enumNames = ImmutableSet.copyOf(allEnums.stream().map(Enum::getName).collect(Collectors.toSet())); final ImmutableList<Struct> allStructs = getStructsOrderedList(spec, enumNames); final ImmutableList<Request> allRequests = getAllRequests(spec); generateHeader(allEnums, allStructs, allRequests); generateSource(allEnums, allStructs, allRequests); } catch (final ParseException e) { LOG.error("Caught exception: ", e); } }
Source:
public void spec306_afterSubscriptionIsCancelledRequestMustBeNops_shouldFailBy_unexpectedElement() throws Throwable { requireTestFailure(new ThrowingRunnable() { @Override public void run() throws Throwable { demandIgnoringSynchronousPublisherVerification().spec306_afterSubscriptionIsCancelledRequestMustBeNops(); } }, "Did not expect an element but got 0"); }

Target:
public void spec306_afterSubscriptionIsCancelledRequestMustBeNops_shouldFailBy_unexpectedElement() throws Throwable { requireTestFailure(new ThrowingRunnable() { @Override public void run() throws Throwable { demandIgnoringSynchronousPublisherVerification().spec306_afterSubscriptionIsCancelledRequestMustBeNops(); } }, "Did not expect an element but got element [0]"); }
Source:
public void describe(SensorDescriptor descriptor) { descriptor.name("php.ini analyzer"); }

Target:
public void describe(SensorDescriptor descriptor) { descriptor.name("Analyzer for \"php.ini\" files"); }
Source:
public void testGetLastMajorVersion() throws OperationException { createDocumentVersions(docWithMajorVersions, VersioningOption.MAJOR, 3); DocumentModel lastVersion = runOperation(docWithMajorVersions); assertNotNull(lastVersion); assertEquals("3", lastVersion.getPropertyValue("dc:description")); assertEquals("3.0", lastVersion.getVersionLabel()); }

Target:
public void testGetLastMajorVersion() throws OperationException { doc = session.createDocumentModel("/Folder", "DocWithMajorVersions", "File"); doc.setPropertyValue("dc:title", "DocWithMajorVersions"); doc = session.createDocument(doc); session.save(); doc = session.getDocument(doc.getRef()); doc = createDocumentVersions(doc, VersioningOption.MAJOR, 3); DocumentModel lastVersion = runOperation(doc); assertNotNull(lastVersion); assertEquals("3", lastVersion.getPropertyValue("dc:description")); assertEquals("3.0", lastVersion.getVersionLabel()); }