auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testExecute_addCsrfTokenCookies_shouldAddToResponseAccordingToExistingCsrfToken() { MockHttpServletRequest mockRequest = new MockHttpServletRequest(getRequestMethod(), Const.ResourceURIs.URI_PREFIX + getActionUri()); String expectedCsrfToken = StringHelper.encrypt(mockRequest.getSession().getId()); String[] emptyParams = new String[] {}; ______TS("No logged in user"); gaeSimulation.logoutUser(); GetAuthInfoAction a = getAction(emptyParams); JsonResult r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with fake csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); Cookie cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, "someFakeCsrfToken"); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with non existing csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); a = getAction(emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with matched CSRF token cookies"); loginAsInstructor("idOfInstructor1OfCourse1"); cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, StringHelper.encrypt(mockRequest.getSession().getId())); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(0, r.getCookies().size()); }

Target:
public void testExecute_addCsrfTokenCookies_shouldAddToResponseAccordingToExistingCsrfToken() { String expectedCsrfToken = StringHelper.encrypt("1234"); String[] emptyParams = new String[] {}; ______TS("No logged in user"); gaeSimulation.logoutUser(); GetAuthInfoAction a = getAction(emptyParams); JsonResult r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with fake csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); Cookie cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, "someFakeCsrfToken"); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with non existing csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); a = getAction(emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with matched CSRF token cookies"); loginAsInstructor("idOfInstructor1OfCourse1"); cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, StringHelper.encrypt("1234")); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(0, r.getCookies().size()); }
Source:
public void endSuccessfully() { }

Target:
public void endSuccessfully() { enclosingCommand.getReturnValue().setSucceeded(true); }
Source:
Entity createEntityNaturally(EntityType type, Vector3d position) throws IllegalArgumentException, IllegalStateException; default Entity createEntityNaturally(EntityType type, Vector3i position) throws IllegalArgumentException, IllegalStateException { return createEntity(type, position.toDouble()); }

Target:
Entity createEntityNaturally(EntityType type, Vector3d position) throws IllegalArgumentException, IllegalStateException; default Entity createEntityNaturally(EntityType type, Vector3i position) throws IllegalArgumentException, IllegalStateException { checkNotNull(position, "position"); return createEntityNaturally(type, position.toDouble()); }
Source:
public void run() { log.info("Starting git/repo artifact migration"); Predicate<Pipeline> hasExpectedGitRepoArtifact = p -> { List<Map> expectedArtifacts = (List<Map>) p.get("expectedArtifacts"); if (expectedArtifacts == null) { return false; } return expectedArtifacts.stream() .anyMatch( e -> { Map matchArtifact = (Map<String, Object>) e.get("matchArtifact"); Map defaultArtifact = (Map<String, Object>) e.get("defaultArtifact"); return matchArtifact != null && isGitRepoArtifact(matchArtifact) && hasSubpathInMetadata(matchArtifact) || defaultArtifact != null && isGitRepoArtifact(defaultArtifact) && hasSubpathInMetadata(defaultArtifact); }); }; pipelineDAO.all().stream() .filter(hasExpectedGitRepoArtifact) .forEach(pipeline -> migrate(pipelineDAO, pipeline)); }

Target:
public void run() { log.info("Starting git/repo artifact migration"); Predicate<Pipeline> hasExpectedGitRepoArtifact = p -> { List<Map> expectedArtifacts = (List<Map>) p.get("expectedArtifacts"); if (expectedArtifacts == null) { return false; } return expectedArtifacts.stream() .anyMatch( e -> shouldMigrateArtifact((Map<String, Object>) e.get("matchArtifact")) || shouldMigrateArtifact((Map<String, Object>) e.get("defaultArtifact"))); }; pipelineDAO.all().stream() .filter(hasExpectedGitRepoArtifact) .forEach(pipeline -> migrate(pipelineDAO, pipeline)); }
Source:
public void put(HttpHeader header, String value) { Objects.requireNonNull(header, "header"); if (value == null) remove(header); else put(new HttpField(header, value)); }

Target:
public void put(HttpHeader header, String value) { Objects.requireNonNull(header, "header must not be null"); if (value == null) remove(header); else put(new HttpField(header, value)); }
Source:
public void test_unknown_locale() { Locale.setDefault(new Locale("en", "US")); JSONObject bundle = ResourceBundleUtil.getBundle("hudson.logging.Messages", new Locale("kok")); Assert.assertEquals("Initialing log recorders", bundle.getString("LogRecorderManager.init")); }

Target:
public void test_unknown_locale() { Locale defaultOSLocale = Locale.getDefault(); try { Locale.setDefault(new Locale("en", "US")); JSONObject bundle = ResourceBundleUtil.getBundle("hudson.logging.Messages", new Locale("kok")); Assert.assertEquals("Initialing log recorders", bundle.getString("LogRecorderManager.init")); }finally{ Locale.setDefault(defaultOSLocale); } }
Source:
public ResultScanner<Row> readRows(ReadRowsRequest request) { final ResultScanner<FlatRow> delegate = readFlatRows(request); return new ResultScanner<Row>(){ @Override public void close() throws IOException { delegate.close(); } @Override public Row[] next(int count) throws IOException { FlatRow[] flatRows = delegate.next(count); Row rows = new Row[flatRows.length]; for (int i = 0; i < flatRows.length; i++) { rows[i] = FlatRowConverter.convert(flatRows[i]); } return rows; } @Override public Row next() throws IOException { return FlatRowConverter.convert(delegate.next()); } @Override public int available() { return delegate.available(); } }; }

Target:
public ResultScanner<Row> readRows(ReadRowsRequest request) { final ResultScanner<FlatRow> delegate = readFlatRows(request); return new ResultScanner<Row>() { @Override public void close() throws IOException { delegate.close(); } @Override public Row[] next(int count) throws IOException { FlatRow[] flatRows = delegate.next(count); Row[] rows = new Row[flatRows.length]; for (int i = 0; i < flatRows.length; i++) { rows[i] = FlatRowConverter.convert(flatRows[i]); } return rows; } @Override public Row next() throws IOException { return FlatRowConverter.convert(delegate.next()); } @Override public int available() { return delegate.available(); } }; }
Source:
public void setPattern(String pattern) { this.compiledPattern = Pattern.compile("(" + pattern + ")"); this.pattern = pattern; }

Target:
public void setPattern(String pattern) throws PatternSyntaxException { this.compiledPattern = Pattern.compile("(" + pattern + ")"); this.pattern = pattern; }
Source:
private void postNicInit() { initSelectedType(); getName().setEntity(getNic().getName()); initMAC(); initLinked(); initNetworks(); initCustomPropertySheet(); getPlugged().setEntity(getNic().isPlugged()); if (!hotPlugSupported) { getPlugged().setChangeProhibitionReason(ConstantsManager.getInstance() .getMessages() .hotPlugNotSupported(getClusterCompatibilityVersion().toString())); } getPlugged().setIsChangable(hotPlugSupported); initCommands(); }

Target:
private void postNicInit() { initSelectedType(); getName().setEntity(getNic().getName()); initMAC(); initLinked(); initPortMirroring(); initNetworks(); initCustomPropertySheet(); getPlugged().setEntity(getNic().isPlugged()); if (!hotPlugSupported) { getPlugged().setChangeProhibitionReason(ConstantsManager.getInstance() .getMessages() .hotPlugNotSupported(getClusterCompatibilityVersion().toString())); } getPlugged().setIsChangable(hotPlugSupported); initCommands(); }
Source:
public void updateSettings(List<String> errors) { MotdSettings motdSettings; try { motdSettings = mapper.readValue(new File(websiteLocation.concat(MOTD_SETTINGS)), MotdSettings.class); this.settings = motdSettings; } catch (IOException ex) { errors.add(ex.getMessage()); LOGGER.error(ex.getMessage(), ex); } }

Target:
public String updateSettings(List<String> errors) { MotdSettings motdSettings; String msg = "{\"status\": \"OK\", \"message\" : \"New configuration accepted.\"}"; try { motdSettings = mapper.readValue(new File(websiteLocation.concat(MOTD_SETTINGS)), MotdSettings.class); this.settings = motdSettings; } catch (IOException ex) { errors.add("motd_config.json is invalid."); msg = String.format("{\"status\": \"FAILED\", \"message\": \"%s\"}", ex.getMessage()); LOGGER.error(ex.getMessage(), ex); } return msg; }
Source:
public TabletFile(String metadataEntry) { this.metadataEntry = Objects.requireNonNull(metadataEntry); String errorMsg = " is missing from tablet file metadata entry: " + metadataEntry; Path metaPath = new Path(metadataEntry); this.fileName = metaPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(fileName); Path tabletDirPath = Objects.requireNonNull(metaPath.getParent(), "Tablet dir" + errorMsg); this.tabletDir = tabletDirPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tabletDir); Path tableIdPath = Objects.requireNonNull(tabletDirPath.getParent(), "Table ID" + errorMsg); this.tableId = TableId.of(tableIdPath.getName()); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tableId.canonical()); Path volumePath = Objects.requireNonNull( TabletFileUtil.getVolumeFromFullPath(metaPath, "tables"), "Volume" + errorMsg); this.volume = volumePath.toString(); this.normalizedPath = volume + Constants.HDFS_TABLES_DIR + "/" + tableId.canonical() + "/" + tabletDir + "/" + fileName; }

Target:
public TabletFile(String metadataEntry) { this.metadataEntry = Objects.requireNonNull(metadataEntry); String errorMsg = "Missing or invalid part of tablet file metadata entry: " + metadataEntry; this.metaPath = new Path(metadataEntry); this.fileName = metaPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(fileName); Path tabletDirPath = Objects.requireNonNull(metaPath.getParent(), errorMsg); this.tabletDir = tabletDirPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tabletDir); Path tableIdPath = Objects.requireNonNull(tabletDirPath.getParent(), errorMsg); this.tableId = TableId.of(tableIdPath.getName()); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tableId.canonical()); Path tablePath = Objects.requireNonNull(tableIdPath.getParent(), errorMsg); String tpString = "/" + tablePath.getName(); Preconditions.checkArgument(tpString.equals(Constants.HDFS_TABLES_DIR), errorMsg); Path volumePath = Objects.requireNonNull(tablePath.getParent(), errorMsg); Preconditions.checkArgument(volumePath.toUri().getScheme() != null, errorMsg); this.volume = volumePath.toString(); this.normalizedPath = volume + Constants.HDFS_TABLES_DIR + "/" + tableId.canonical() + "/" + tabletDir + "/" + fileName; }
Source:
public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, (e, context, req, rsp) -> { if (rsp.isCommitted()) { LOGGER.log(isEOFException(e) ? Level.FINE : Level.WARNING, null, e); return; } req.setAttribute("javax.servlet.error.exception",e); try { reportMissingClassJava11Telemetry(e); WebApp.get(j.servletContext).getSomeStapler().invoke(req, rsp, j, "/oops"); } catch (ServletException | IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } }); try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); LOGGER.log(Level.FINE, "Successfully installed a global UncaughtExceptionHandler."); } catch (SecurityException ex) { LOGGER.log(Level.SEVERE, "Failed to set the default UncaughtExceptionHandler. " + "If any threads die due to unhandled coding errors then there will be no logging of this information. " + "The lack of this diagnostic information will make it harder to track down issues which will reduce the supportability of Jenkins. " + "It is highly recommended that you consult the documentation that comes with you servlet container on how to allow the " + "`setDefaultUncaughtExceptionHandler` permission and enable it.", ex); } }

Target:
public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, (e, context, req, rsp) -> { if (rsp.isCommitted()) { LOGGER.log(isEOFException(e) ? Level.FINE : Level.WARNING, null, e); return; } req.setAttribute("javax.servlet.error.exception",e); try { MissingClassTelemetry.reportExceptionInside(e); WebApp.get(j.servletContext).getSomeStapler().invoke(req, rsp, j, "/oops"); } catch (ServletException | IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } }); try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); LOGGER.log(Level.FINE, "Successfully installed a global UncaughtExceptionHandler."); } catch (SecurityException ex) { LOGGER.log(Level.SEVERE, "Failed to set the default UncaughtExceptionHandler. " + "If any threads die due to unhandled coding errors then there will be no logging of this information. " + "The lack of this diagnostic information will make it harder to track down issues which will reduce the supportability of Jenkins. " + "It is highly recommended that you consult the documentation that comes with you servlet container on how to allow the " + "`setDefaultUncaughtExceptionHandler` permission and enable it.", ex); } }
Source:
public void ignoreInterfaces() throws MalformedURLException { ServletContext context = mock(ServletContext.class); when(context.getResource(any(String.class))).thenReturn(null); IndexHtmlDispatcher.make(context, TestInterface.class); }

Target:
public void ignoreInterfaces() throws MalformedURLException { ServletContext context = mock(ServletContext.class); when(context.getResource(any(String.class))).thenReturn(null); assertNull(IndexHtmlDispatcher.make(context, TestInterface.class)); }
Source:
public EntityPermissions(EntityDictionary dictionary, Class<?> cls, Collection<AccessibleObject> fieldOrMethodList) { this.dictionary = dictionary; for (Class<? extends Annotation> annotationClass : PERMISSION_ANNOTATIONS) { final Map<String, ParseTree> fieldPermissions = new HashMap<>(); fieldOrMethodList.stream() .forEach(member -> bindMemberPermissions(fieldPermissions, member, annotationClass)); if (annotationClass == SharePermission.class && EntityDictionary.getFirstAnnotation(cls, Arrays.asList(annotationClass)) != null) { bindings.put(SharePermission.class, new AnnotationBinding(null, fieldPermissions)); } else { ParseTree classPermission = bindClassPermissions(cls, annotationClass); if (classPermission != null || !fieldPermissions.isEmpty()) { bindings.put(annotationClass, new AnnotationBinding(classPermission, fieldPermissions)); } } } }

Target:
public EntityPermissions(EntityDictionary dictionary, Class<?> cls, Collection<AccessibleObject> fieldOrMethodList) { this.dictionary = dictionary; for (Class<? extends Annotation> annotationClass : PERMISSION_ANNOTATIONS) { final Map<String, ParseTree> fieldPermissions = new HashMap<>(); fieldOrMethodList.stream() .forEach(member -> bindMemberPermissions(fieldPermissions, member, annotationClass)); if (annotationClass != SharePermission.class) { ParseTree classPermission = bindClassPermissions(cls, annotationClass); if (classPermission != null || !fieldPermissions.isEmpty()) { bindings.put(annotationClass, new AnnotationBinding(classPermission, fieldPermissions)); } } } }
Source:
public static boolean isTimeWithinPeriod(Date startTime, Date endTime, Date time, boolean isStartInclusive, boolean isEndInclusive) { if (startTime == null || endTime == null || time == null) { return false; } if (isStartInclusive && isEndInclusive) { return startTime.getTime() <= time.getTime() && time.getTime() <= endTime.getTime(); } else if (isStartInclusive && !isEndInclusive) { return startTime.getTime() <= time.getTime() && time.getTime() < endTime.getTime(); } else if (!isStartInclusive && isEndInclusive) { return startTime.getTime() < time.getTime() && time.getTime() <= endTime.getTime(); } else { return startTime.getTime() < time.getTime() && time.getTime() < endTime.getTime(); } }

Target:
public static boolean isTimeWithinPeriod(Date startTime, Date endTime, Date time, boolean isStartInclusive, boolean isEndInclusive) { if (startTime == null || endTime == null || time == null) { return false; } boolean isAfterStartTime = time.after(startTime) || (isStartInclusive && time.equals(startTime)); boolean isBeforeEndTime = time.before(endTime) || (isEndInclusive && time.equals(endTime)); return isAfterStartTime && isBeforeEndTime; }
Source:
private static ItemRequest createSubmissionRequest(final DBObject experiments, final ByteString review) { final ItemRequest.Builder build = ItemRequest.newBuilder(); build.setQuery(ItemQuery.EXPERIMENT); for (String key : experiments.keySet()) { if (SELF_ID.equals(key)) { continue; } final Object experimentId = experiments.get(key); if (experimentId == null || experimentId instanceof ObjectId) { continue; } final String sketchId = experiments.get(key).toString(); LOG.info("SketchId: {}", sketchId); build.addItemId(sketchId); } build.setAdvanceQuery(review); return build.build(); }

Target:
private static ItemRequest createSubmissionRequest(final DBObject experiments, final ByteString review) { final ItemRequest.Builder itemRequest = ItemRequest.newBuilder(); itemRequest.setQuery(ItemQuery.EXPERIMENT); for (String key : experiments.keySet()) { if (SELF_ID.equals(key)) { continue; } final Object experimentId = experiments.get(key); if (experimentId == null || experimentId instanceof ObjectId) { continue; } final String sketchId = experiments.get(key).toString(); LOG.info("SketchId: {}", sketchId); itemRequest.addItemId(sketchId); } itemRequest.setAdvanceQuery(review); return itemRequest.build(); }
Source:
public ElasticAgentExtension(PluginManager pluginManager) { super(pluginManager, new PluginRequestHelper(pluginManager, SUPPORTED_VERSIONS, ElasticAgentPluginConstants.EXTENSION_NAME), ElasticAgentPluginConstants.EXTENSION_NAME); addHandler(ElasticAgentExtensionConverterV1.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV1()); addHandler(ElasticAgentExtensionConverterV2.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV2()); jsonMessageHandlersForRequestProcessor.put(ElasticAgentExtensionConverterV1.VERSION, new JsonMessageHandlerForRequestProcessor1_0()); jsonMessageHandlersForRequestProcessor.put(ElasticAgentExtensionConverterV2.VERSION, new JsonMessageHandlerForRequestProcessor1_0()); }

Target:
public ElasticAgentExtension(PluginManager pluginManager) { super(pluginManager, new PluginRequestHelper(pluginManager, SUPPORTED_VERSIONS, ElasticAgentPluginConstants.EXTENSION_NAME), ElasticAgentPluginConstants.EXTENSION_NAME); addHandler(ElasticAgentExtensionConverterV1.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV1(), new JsonMessageHandlerForRequestProcessor1_0()); addHandler(ElasticAgentExtensionConverterV2.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV2(), new JsonMessageHandlerForRequestProcessor1_0()); }
Source:
protected boolean canDoAction() { boolean returnValue = true; StorageServerConnections paramConnection = getConnection(); if (StringUtils.isNotEmpty(paramConnection.getid())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); } if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { returnValue = false; addCanDoActionMessage(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (isConnWithSameDetailsExists()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ALREADY_EXISTS); } if (getParameters().getVdsId().equals(Guid.Empty)) { returnValue = InitializeVds(); } else if (getVds() == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); returnValue = false; } else if (getVds().getStatus() != VDSStatus.Up) { addCanDoActionMessage(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); returnValue = false; } return returnValue; }

Target:
protected boolean canDoAction() { boolean returnValue = true; StorageServerConnections paramConnection = getConnection(); if (StringUtils.isNotEmpty(paramConnection.getid())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); } if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (paramConnection.getstorage_type() == StorageType.ISCSI && StringUtils.isEmpty(paramConnection.getiqn())) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (checkIsConnectionFieldEmpty(paramConnection)) { return false; } if (isConnWithSameDetailsExists()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ALREADY_EXISTS); } if (getParameters().getVdsId().equals(Guid.Empty)) { if (!initializeVds()) { return false; } } else if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_INVALID_SERVER_ID); } else if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); } return true; }
Source:
public void testTwoGroups() throws Exception { String header1 = "A, B"; String data1 = "a1, b1"; AtomicBoolean wasCalled1 = new AtomicBoolean(false); RecordGroup recordGroup1 = createTwoGroupsFirstRecordGroup(wasCalled1); String header2 = "C, D, E"; String data2 = "c1, d1, e1"; AtomicBoolean wasCalled2 = new AtomicBoolean(false); RecordGroup recordGroup2 = createTwoGroupsSecondRecordGroup(wasCalled2); GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header1, data1, "", header2, data2)), CSV, recordGroup1, recordGroup2); importer.load(); assertTrue(wasCalled1.get() && wasCalled2.get()); wasCalled1 = new AtomicBoolean(false); recordGroup1 = createTwoGroupsFirstRecordGroup(wasCalled1); wasCalled2 = new AtomicBoolean(false); recordGroup2 = createTwoGroupsSecondRecordGroup(wasCalled2); importer = new GanttCSVOpen(createSupplier(createXls(header1, data1, "", header2, data2)), XLS, recordGroup1, recordGroup2); importer.load(); assertTrue(wasCalled1.get() && wasCalled2.get()); }

Target:
public void testTwoGroups() throws Exception { String header1 = "A, B"; String data1 = "a1, b1"; String header2 = "C, D, E"; String data2 = "c1, d1, e1"; for (Pair<SpreadsheetFormat, Supplier<InputStream>> pair : createPairs(header1, data1, "", header2, data2)) { final AtomicBoolean wasCalled1 = new AtomicBoolean(false); RecordGroup recordGroup1 = new RecordGroup("AB", ImmutableSet.of("A", "B")) { @Override protected boolean doProcess(SpreadsheetRecord record) { if (!super.doProcess(record)) { return false; } assertEquals("a1", record.get("A")); assertEquals("b1", record.get("B")); wasCalled1.set(true); return true; } }; final AtomicBoolean wasCalled2 = new AtomicBoolean(false); RecordGroup recordGroup2 = new RecordGroup("CDE", ImmutableSet.of("C", "D", "E")) { @Override protected boolean doProcess(SpreadsheetRecord record) { if (!super.doProcess(record)) { return false; } assertEquals("c1", record.get("C")); assertEquals("d1", record.get("D")); assertEquals("e1", record.get("E")); wasCalled2.set(true); return true; } }; GanttCSVOpen importer = new GanttCSVOpen(pair.second(), pair.first(), recordGroup1, recordGroup2); importer.load(); assertTrue(wasCalled1.get() && wasCalled2.get()); } }
Source:
public static <K extends Comparable<? super K>, V> TreeMap<K, V> of(Comparator<? super K> keyComparator, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { return TreeMap.<K, V> empty(keyComparator).put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).put(k5, v5).put(k6, v6).put(k7, v7).put(k8, v8).put(k9, v9).put(k10, v10); }

Target:
public static <K, V> TreeMap<K, V> of(Comparator<? super K> keyComparator, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10) { return TreeMap.<K, V> empty(keyComparator).put(k1, v1).put(k2, v2).put(k3, v3).put(k4, v4).put(k5, v5).put(k6, v6).put(k7, v7).put(k8, v8).put(k9, v9).put(k10, v10); }
Source:
public Object associate(@Nullable UserIdentity user) { if (user == null || user.getUserPrincipal() == null) return null; Subject subject = (Subject) user.getUserPrincipal(); ThreadContext.bind(subject); return null; }

Target:
public Object associate(@Nullable UserIdentity user) { if (user != null && user.getUserPrincipal() != null) { Subject subject = (Subject) user.getUserPrincipal(); ThreadContext.bind(subject); } return null; }
Source:
public static List<String> getAppendersNames() { Enumeration enumeration = org.apache.log4j.Logger.getRootLogger().getAllAppenders(); List<String> names = new LinkedList<>(); while (enumeration.hasMoreElements()) { names.add(((Appender)enumeration.nextElement()).getName()); } return names; }

Target:
public static List<String> getAppendersNames() { Enumeration enumeration = LogManager.getRootLogger().getAllAppenders(); List<String> names = new LinkedList<>(); while (enumeration.hasMoreElements()) { names.add(((Appender)enumeration.nextElement()).getName()); } return names; }
Source:
@Override public void start() throws IgniteCheckedException { if (ctx.isDaemon()) return; GridInternalSubscriptionProcessor isp = ctx.internalSubscriptionProcessor(); isp.registerDistributedMetastorageListener(new DistributedMetastorageLifecycleListener() { @Override public void onReadyForRead(ReadableDistributedMetaStorage metastorage) { distributedMetastorage = ctx.distributedMetastorage(); distributedMetastorage.listen( (key) -> key.startsWith(DIST_CONF_PREFIX), (String key, Serializable oldVal, Serializable newVal) -> { DistributedChangeableProperty prop = props.get(toPropertyKey(key)); if (prop != null) prop.localUpdate(newVal); } ); switchCurrentActionTo(ACTUALIZE); isp.getDistributedConfigurationListeners() .forEach(listener -> listener.onReadyToRegister(DistributedConfigurationProcessor.this)); } @Override public void onReadyForWrite(DistributedMetaStorage metastorage) { switchCurrentActionTo(CLUSTER_WIDE_UPDATE); isp.getDistributedConfigurationListeners() .forEach(DistributedConfigurationLifecycleListener::onReadyToWrite); } }); }

Target:
@Override public void start() throws IgniteCheckedException { GridInternalSubscriptionProcessor isp = ctx.internalSubscriptionProcessor(); isp.registerDistributedMetastorageListener(new DistributedMetastorageLifecycleListener() { @Override public void onReadyForRead(ReadableDistributedMetaStorage metastorage) { distributedMetastorage = ctx.distributedMetastorage(); distributedMetastorage.listen( (key) -> key.startsWith(DIST_CONF_PREFIX), (String key, Serializable oldVal, Serializable newVal) -> { DistributedChangeableProperty prop = props.get(toPropertyKey(key)); if (prop != null) prop.localUpdate(newVal); } ); switchCurrentActionTo(ACTUALIZE); isp.getDistributedConfigurationListeners() .forEach(listener -> listener.onReadyToRegister(DistributedConfigurationProcessor.this)); } @Override public void onReadyForWrite(DistributedMetaStorage metastorage) { switchCurrentActionTo(CLUSTER_WIDE_UPDATE); isp.getDistributedConfigurationListeners() .forEach(DistributedConfigurationLifecycleListener::onReadyToWrite); } }); }
Source:
private void findNegotiatingProfiles(ServletRequest req) { if (profiles == null) { synchronized (this) { if (profiles == null) { profiles = new ArrayList<AuthenticationProfile>(1); long caps = 0; for (String nego : req.getServletContext().getInitParameter(CAPABILITIES_PARAMETER).split("|")) { if (nego.trim().equals("AUTHENTICATE_NEGOTIATE_INTERACTIVE")) { caps |= Authn.Capabilities.AUTHENTICATE_NEGOTIATE_INTERACTIVE; } else if (nego.trim().equals("AUTHENTICATE_NEGOTIATE_NON_INTERACTIVE")) { caps |= Authn.Capabilities.AUTHENTICATE_NEGOTIATE_NON_INTERACTIVE; } } for (AuthenticationProfile profile : AuthenticationProfileRepository.getInstance().getProfiles()) { if (profile != null) { if ((profile.getAuthn().getContext().<Long> get(Authn.ContextKeys.CAPABILITIES).longValue() & caps) != 0) { profiles.add(0, profile); } } } } } } }

Target:
private void findNegotiatingProfiles(ServletRequest req) { List<String> schemes = new ArrayList<String>(); if (profiles == null) { synchronized (this) { if (profiles == null) { schemes = new ArrayList<>(); profiles = new ArrayList<AuthenticationProfile>(1); long caps = 0; for (String nego : req.getServletContext().getInitParameter(CAPABILITIES_PARAMETER).trim().split("*|*")) { try { caps |= Authn.Capabilities.class.getField(nego).getInt(null); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException ex) { } } for (AuthenticationProfile profile : AuthenticationProfileRepository.getInstance().getProfiles()) { if (profile != null) { ExtMap authnContext = profile.getAuthn().getContext(); if ((authnContext.<Long> get(Authn.ContextKeys.CAPABILITIES).longValue() & caps) != caps) { profiles.add(0, profile); } schemes.addAll(authnContext.<List<String>>get(Authn.ContextKeys.HTTP_AUTHENTICATION_SCHEME, Collections.<String>emptyList())); } } } } } ((HttpServletRequest) req).setAttribute(FiltersHelper.Constants.SCHEMES_KEY, schemes); }
Source:
private int countIndexedNodes( GraphDatabaseAPI db, Label label, String... keys ) throws Exception { try ( Transaction tx = db.beginTx() ) { KernelTransaction ktx = db.getDependencyResolver() .resolveDependency( ThreadToStatementContextBridge.class ) .getKernelTransactionBoundToThisThread( true ); try ( Statement statement = ktx.acquireStatement() ) { TokenRead tokenRead = ktx.tokenRead(); int labelId = tokenRead.nodeLabel( label.name() ); int[] propertyKeyIds = new int[keys.length]; for ( int i = 0; i < keys.length; i++ ) { propertyKeyIds[i] = tokenRead.propertyKey( keys[i] ); } CapableIndexReference index = ktx.schemaRead().index( labelId, propertyKeyIds ); final long timeout = 5000; final long start = System.currentTimeMillis(); long runningFor; InternalIndexState state; do { state = ktx.schemaRead().indexGetState( index ); runningFor = System.currentTimeMillis() - start; } while ( state != InternalIndexState.ONLINE && runningFor < timeout ); int count; StorageStatement storeStatement = ((KernelStatement) statement).getStoreStatement(); IndexReader reader = storeStatement.getIndexReader( DefaultIndexReference.toDescriptor( index ) ); IndexQuery[] predicates = new IndexQuery[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { predicates[i] = IndexQuery.exists( propertyKeyIds[i] ); } count = count( reader.query( predicates ) ); tx.success(); return count; } } }

Target:
private int countIndexedNodes( GraphDatabaseAPI db, Label label, String... keys ) throws Exception { try ( Transaction tx = db.beginTx() ) { KernelTransaction ktx = db.getDependencyResolver() .resolveDependency( ThreadToStatementContextBridge.class ) .getKernelTransactionBoundToThisThread( true ); try ( Statement statement = ktx.acquireStatement() ) { TokenRead tokenRead = ktx.tokenRead(); int labelId = tokenRead.nodeLabel( label.name() ); int[] propertyKeyIds = new int[keys.length]; for ( int i = 0; i < keys.length; i++ ) { propertyKeyIds[i] = tokenRead.propertyKey( keys[i] ); } CapableIndexReference index = ktx.schemaRead().index( labelId, propertyKeyIds ); db.schema().awaitIndexesOnline(5, TimeUnit.SECONDS ); int count; StorageStatement storeStatement = ((KernelStatement) statement).getStoreStatement(); IndexReader reader = storeStatement.getIndexReader( DefaultIndexReference.toDescriptor( index ) ); IndexQuery[] predicates = new IndexQuery[propertyKeyIds.length]; for ( int i = 0; i < propertyKeyIds.length; i++ ) { predicates[i] = IndexQuery.exists( propertyKeyIds[i] ); } count = count( reader.query( predicates ) ); tx.success(); return count; } } }
Source:
public static Long getPID() { if (cachedPid == null) { initPid(); } if (log.isDebugEnabled()) { log.debug("My PID is " + cachedPid); } return cachedPid; }

Target:
public static Long getPID() { if (cachedPid == null) { initPid(); } log.debug("My PID is {}", cachedPid); return cachedPid; }
Source:
public void run() { try { while (running) { if (!hardDelete()) { try { Thread.sleep(hardDeleterSleepTimeWhenCaughtUpMs); } catch (InterruptedException e) { logger.info("Caught interrupted exception"); } } } } finally { shutdownLatch.countDown(); } }

Target:
public void run() { try { while (running) { if (!hardDelete()) { try { Thread.sleep(hardDeleterSleepTimeWhenCaughtUpMs); } catch (InterruptedException e) { logger.info("Caught interrupted exception"); } } } } finally { close(); } }
Source:
public void testFirstLast_CreateSparseContainersAfterRun() { RoaringBitmap rb = new RoaringBitmap(); rb.add(1L, 1 << 14); for(int i = 18; i < 31; ++i) { int x = 1 << i; rb.add(x); Assert.assertEquals(1, rb.first()); rb.last(); Assert.assertEquals(x, rb.last()); } }

Target:
public void testFirstLast_CreateSparseContainersAfterRun() { RoaringBitmap rb = new RoaringBitmap(); rb.add(1L, 1 << 14); for(int i = 18; i < 31; ++i) { int x = 1 << i; rb.add(x); Assert.assertEquals(1, rb.first()); Assert.assertEquals(x, rb.last()); } }
Source:
public void testObtainCertificateChainMissingLocationURL() throws Exception { server = setupTestObtainCertificate(true); AcmeAccount account = populateAccount(ACCOUNT_3_V2); String domainName = "fjsljghasldfjgkv2.com"; try { obtainCertificateChain(null, -1, account, domainName); fail("Expected AcmeException not thrown"); } catch(AcmeException e) { assertTrue(e.getMessage().contains("order location URL")); } }

Target:
public void testObtainCertificateChainMissingLocationURL() throws Exception { server = setupTestObtainCertificate(true); AcmeAccount account = populateAccount(ACCOUNT_3_V2); String domainName = "fjsljghasldfjgkv2.com"; try { obtainCertificateChain(null, -1, account, domainName); fail("Expected AcmeException not thrown"); } catch(AcmeException e) { assertTrue(e.getMessage().contains(ORDER)); } }
Source:
public EnhancementAsProxyLazinessInterceptor( String entityName, Set<String> identifierAttributeNames, CompositeType nonAggregatedCidMapper, EntityKey entityKey, SharedSessionContractImplementor session) { super( entityName, session ); this.identifierAttributeNames = identifierAttributeNames; assert identifierAttributeNames != null; this.nonAggregatedCidMapper = nonAggregatedCidMapper; assert nonAggregatedCidMapper != null || identifierAttributeNames.size() == 1; this.entityKey = entityKey; final EntityPersister entityPersister = session.getFactory().getMetamodel().entityPersister( entityName ); this.inLineDirtyChecking = entityPersister.getEntityMode() == EntityMode.POJO && SelfDirtinessTracker.class.isAssignableFrom( entityPersister.getMappedClass() ); initializeOnRead = !inLineDirtyChecking || !entityPersister.getEntityMetamodel().isDynamicUpdate(); }

Target:
public EnhancementAsProxyLazinessInterceptor( String entityName, Set<String> identifierAttributeNames, CompositeType nonAggregatedCidMapper, EntityKey entityKey, SharedSessionContractImplementor session) { super( entityName, session ); this.identifierAttributeNames = identifierAttributeNames; assert identifierAttributeNames != null; this.nonAggregatedCidMapper = nonAggregatedCidMapper; assert nonAggregatedCidMapper != null || identifierAttributeNames.size() == 1; this.entityKey = entityKey; final EntityPersister entityPersister = session.getFactory().getMetamodel().entityPersister( entityName ); this.inLineDirtyChecking = entityPersister.getEntityMode() == EntityMode.POJO && SelfDirtinessTracker.class.isAssignableFrom( entityPersister.getMappedClass() ); initializeBeforeWrite = !inLineDirtyChecking || !entityPersister.getEntityMetamodel().isDynamicUpdate(); }
Source:
public void testTwoBrokerCluster() throws InterruptedException { final KafkaCluster cluster = app.createAndManageChild(EntitySpec.create(KafkaCluster.class) .configure(KafkaCluster.INITIAL_SIZE, 2)); cluster.start(ImmutableList.of(testLocation)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Callable<Void>() { @Override public Void call() { assertTrue(cluster.getAttribute(Startable.SERVICE_UP)); assertTrue(cluster.getZooKeeper().getAttribute(Startable.SERVICE_UP)); assertEquals(cluster.getCurrentSize().intValue(), 2); return null; } }); Entities.dumpInfo(cluster); final KafkaSupport support = new KafkaSupport(cluster); support.sendMessage("brooklyn", "TEST_MESSAGE"); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.FIVE_SECONDS), new Callable<Void>() { @Override public Void call() throws Exception { String message = support.getMessage("brooklyn"); assertEquals(message, "TEST_MESSAGE"); return null; } }); }

Target:
public void testTwoBrokerCluster() throws InterruptedException { final KafkaCluster cluster = app.createAndManageChild(EntitySpec.create(KafkaCluster.class) .configure(KafkaCluster.INITIAL_SIZE, 2)); cluster.start(ImmutableList.of(testLocation)); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.TWO_MINUTES), new Callable<Void>() { @Override public Void call() { assertTrue(cluster.getAttribute(Startable.SERVICE_UP)); assertTrue(cluster.getZooKeeper().getAttribute(Startable.SERVICE_UP)); assertEquals(cluster.getCurrentSize().intValue(), 2); return null; } }); Entities.dumpInfo(cluster); final KafkaSupport support = new KafkaSupport(cluster); support.sendMessage("brooklyn", "TEST_MESSAGE"); Asserts.succeedsEventually(MutableMap.of("timeout", Duration.FIVE_SECONDS), new Runnable() { @Override public void run() { String message = support.getMessage("brooklyn"); assertEquals(message, "TEST_MESSAGE"); } }); }
Source:
static void bindField(PreparedStatement statement, int index, Schema schema, Object value) throws SQLException { if (value == null) { statement.setObject(index, null); } else { if (schema.name() != null) { LogicalTypeConverter logicalConverter = LOGICAL_CONVERTERS.get(schema.name()); if (logicalConverter != null) value = logicalConverter.convert(schema, value); } Schema.Type type = schema.type(); switch (type) { case INT8: statement.setByte(index, (Byte) value); break; case INT16: statement.setShort(index, (Short) value); break; case INT32: statement.setInt(index, (Integer) value); break; case INT64: statement.setLong(index, (Long) value); break; case FLOAT32: statement.setFloat(index, (Float) value); break; case FLOAT64: statement.setDouble(index, (Double) value); break; case BOOLEAN: statement.setBoolean(index, (Boolean) value); break; case STRING: statement.setString(index, (String) value); break; case BYTES: final byte[] bytes; if (value instanceof ByteBuffer) { final ByteBuffer buffer = ((ByteBuffer) value).slice(); bytes = new byte[buffer.remaining()]; buffer.get(bytes); } else { bytes = (byte[]) value; } statement.setBytes(index, bytes); break; default: throw new ConnectException("Unsupported source data type: " + type); } } }

Target:
static void bindField(PreparedStatement statement, int index, Schema schema, Object value) throws SQLException { if (value == null) { statement.setObject(index, null); } else { if (schema.name() != null) { LogicalTypeConverter logicalConverter = LOGICAL_CONVERTERS.get(schema.name()); if (logicalConverter != null) { value = logicalConverter.convert(schema, value); } } switch (schema.type()) { case INT8: statement.setByte(index, (Byte) value); break; case INT16: statement.setShort(index, (Short) value); break; case INT32: statement.setInt(index, (Integer) value); break; case INT64: statement.setLong(index, (Long) value); break; case FLOAT32: statement.setFloat(index, (Float) value); break; case FLOAT64: statement.setDouble(index, (Double) value); break; case BOOLEAN: statement.setBoolean(index, (Boolean) value); break; case STRING: statement.setString(index, (String) value); break; case BYTES: final byte[] bytes; if (value instanceof ByteBuffer) { final ByteBuffer buffer = ((ByteBuffer) value).slice(); bytes = new byte[buffer.remaining()]; buffer.get(bytes); } else { bytes = (byte[]) value; } statement.setBytes(index, bytes); break; default: throw new ConnectException("Unsupported source data type: " + schema.type()); } } }
Source:
public boolean unloadChunk(int x, int z, boolean save, boolean safe) { boolean success = !isChunkLoaded(x, z) || getChunkAt(x, z).unload(save, safe); if(success) rsManager.dropRedChunk(x, z); return success; }

Target:
public boolean unloadChunk(int x, int z, boolean save, boolean safe) { boolean success = (!isChunkLoaded(x, z) || getChunkAt(x, z).unload(save, safe)); if(success) { getRSManager().dropChunk(x, z); } return success; }
Source:
public void comparesToAnotherDocument() throws Exception { final String xml = "<hi><dude> </dude></hi>"; MatcherAssert.assertThat( new XMLDocument(xml), Matchers.equalTo(new XMLDocument(xml)) ); MatcherAssert.assertThat( new XMLDocument("<hi><man></man></hi>"), Matchers.not( Matchers.equalTo(new XMLDocument("<hi><man> </man></hi>")) ) ); }

Target:
public void comparesToAnotherDocument() throws Exception { MatcherAssert.assertThat( new XMLDocument("<hi>\n<dude> </dude></hi>"), Matchers.equalTo(new XMLDocument("<hi><dude> </dude></hi>")) ); MatcherAssert.assertThat( new XMLDocument("<hi><man></man></hi>"), Matchers.not( Matchers.equalTo(new XMLDocument("<hi><man> </man></hi>")) ) ); }
Source:
public PluginConfig(String className) { requireNonNull(className); this.className = className; }

Target:
public PluginConfig(String className) { this.className = requireNonNull(className); this.options = Map.of(); }
Source:
private Issue applyInput(Issue issue, IssueInputView input) { String issueUri = input.getIssueUri(); if (issueUri != null) { IssueIdentifier issueId = IssueIdentifier.create(issueUri); issue.setIssueUri(issueId.getIssueUri()); } String displayName = input.getDisplayName(); if (displayName != null) { issue.setDisplayName(displayName); } else if (issue.getDisplayName() == null) { issue.setDisplayName(""); } String imageUri = input.getImageUri(); if (imageUri != null) { ArticleIdentifier imageArticleId = ArticleIdentifier.create(imageUri); if (!imageArticleId.getDoiName().equals(issue.getImageUri())) { updateImageArticle(issue, imageArticleId); } } else if (issue.getImageUri() == null) { issue.setImageUri(""); } Boolean respectOrder = input.getRespectOrder(); if (respectOrder != null) { issue.setRespectOrder(respectOrder); } List<String> inputArticleDois = input.getArticleOrder(); if (inputArticleDois != null) { List<IssueArticle> existingIssueArticles = getIssueArticles(issue); for (IssueArticle issueArticle : existingIssueArticles) { hibernateTemplate.delete(issueArticle); } List<ArticleTable> inputArticles = inputArticleDois.stream() .map(doi -> articleCrudService.getArticle(ArticleIdentifier.create(doi))) .collect(Collectors.toList()); int sortOrder = 0; for (ArticleTable article : inputArticles) { IssueArticle issueArticle = new IssueArticle(issue, article, sortOrder); hibernateTemplate.save(issueArticle); sortOrder++; } } return issue; }

Target:
private Issue applyInput(Issue issue, IssueInputView input) { String issueDoi = input.getDoi(); if (issueDoi != null) { IssueIdentifier issueId = IssueIdentifier.create(issueDoi); issue.setDoi(issueId.getDoi().getName()); } String displayName = input.getDisplayName(); if (displayName != null) { issue.setDisplayName(displayName); } else if (issue.getDisplayName() == null) { issue.setDisplayName(""); } String imageDoi = input.getImageArticleDoi(); if (imageDoi != null) { ArticleIdentifier imageArticleId = ArticleIdentifier.create(imageDoi); ArticleTable imageArticle = articleCrudService.getArticle(imageArticleId); issue.setImageArticle(imageArticle); } else { issue.setImageArticle(null); } List<String> inputArticleDois = input.getArticleOrder(); if (inputArticleDois != null) { List<ArticleTable> inputArticles = inputArticleDois.stream() .map(doi -> articleCrudService.getArticle(ArticleIdentifier.create(doi))) .collect(Collectors.toList()); issue.setArticles(inputArticles); } return issue; }
Source:
public void testObserverConfig() { FluoConfiguration config = new FluoConfiguration(); config.setProperty("key1", "com.foo.Observer2,configKey1=configVal1,configKey2=configVal2"); ObserverConfiguration oc = config.getObserverConfig("key1"); Assert.assertEquals("com.foo.Observer2", oc.getClassName()); Assert.assertEquals("configVal1", oc.getParameters().get("configKey1")); Assert.assertEquals(2, oc.getParameters().size()); assertIAE("index,check,,phrasecount.PhraseCounter"); assertIAE(""); assertIAE(" "); assertIAE(",key=value"); assertIAE(","); assertIAE("com.foo.Observer2,configKey1=,configKey2=configVal2"); assertIAE("com.foo.Observer2,configKey1=val,=configVal2"); config.setProperty("key3", "Class,"); oc = config.getObserverConfig("key3"); Assert.assertEquals("Class", oc.getClassName()); Assert.assertEquals(0, oc.getParameters().size()); config = new FluoConfiguration(); try { config.setProperty(FluoConfiguration.OBSERVER_PREFIX+"1", "class,bad,input"); config.validate(); Assert.fail(); } catch (IllegalArgumentException e) { } }

Target:
public void testObserverConfig() { FluoConfiguration config = new FluoConfiguration(); config.setProperty(FluoConfiguration.OBSERVER_PREFIX+"1", "com.foo.Observer2,configKey1=configVal1,configKey2=configVal2"); List<ObserverConfiguration> ocList = config.getObserverConfig(); Assert.assertEquals(1, ocList.size()); Assert.assertEquals("com.foo.Observer2", ocList.get(0).getClassName()); Assert.assertEquals("configVal1", ocList.get(0).getParameters().get("configKey1")); Assert.assertEquals("configVal2", ocList.get(0).getParameters().get("configKey2")); Assert.assertEquals(2, ocList.get(0).getParameters().size()); assertIAE("index,check,,phrasecount.PhraseCounter"); assertIAE(""); assertIAE(" "); assertIAE(",key=value"); assertIAE(","); assertIAE("com.foo.Observer2,configKey1=,configKey2=configVal2"); assertIAE("com.foo.Observer2,configKey1=val,=configVal2"); config = new FluoConfiguration(); config.setProperty(FluoConfiguration.OBSERVER_PREFIX+"1", "Class,"); ocList = config.getObserverConfig(); Assert.assertEquals(1, ocList.size()); Assert.assertEquals("Class", ocList.get(0).getClassName()); Assert.assertEquals(0, ocList.get(0).getParameters().size()); config = new FluoConfiguration(); try { config.setProperty(FluoConfiguration.OBSERVER_PREFIX+"1", "class,bad,input"); config.validate(); Assert.fail(); } catch (IllegalArgumentException e) { } }
Source:
private void removeOvfForTemplatesAndVmsOfStoragePool(Guid poolId) { List<Guid> idsForRemoval = new LinkedList<Guid>(getVmAndTemplatesGenerationsDao().getIdsForOvfDeletion(poolId)); for (Guid id : idsForRemoval){ executeRemoveVmInSpm(poolId, id, Guid.Empty); } getVmAndTemplatesGenerationsDao().deleteOvfGenerations(idsForRemoval); }

Target:
private void removeOvfForTemplatesAndVmsOfStoragePool(Guid poolId) { List<Guid> idsForRemoval = getVmAndTemplatesGenerationsDao().getIdsForOvfDeletion(poolId); for (Guid id : idsForRemoval){ executeRemoveVmInSpm(poolId, id, Guid.Empty); } getVmAndTemplatesGenerationsDao().deleteOvfGenerations(idsForRemoval); }