auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); if (!testMethod.isPresent()) { return enabled(""); } Class<?> testClass = extensionContext.getRequiredTestClass(); Optional<RequiredFeatures> methodRequires = testMethod.map(method -> method.getAnnotation(RequiredFeatures.class)); List<RequiredFeatures> classRequires = getClassRequiredFeatures(testMethod.get().getDeclaringClass()); Optional<SupportedFeatures> classSupports = Optional.ofNullable(testClass.getAnnotation(SupportedFeatures.class)); Set<ConnectorFeature> requiredFeatures = Stream.concat( streamOfRequired(methodRequires), classRequires.stream().flatMap(r -> Arrays.stream(r.value()))) .distinct() .collect(Collectors.toCollection(HashSet::new)); Set<ConnectorFeature> supportedFeatures = streamOfSupported(classSupports) .distinct() .collect(toImmutableSet()); requiredFeatures.removeAll(supportedFeatures); return requiredFeatures.isEmpty() ? enabled("All required features present") : disabled("Missing required features: " + Joiner.on(", ").join(requiredFeatures)); }

Target:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); if (!testMethod.isPresent()) { return enabled(""); } Class<?> testClass = extensionContext.getRequiredTestClass(); List<ConnectorFeature> classRequires = getClassRequiredFeatures(testMethod.get().getDeclaringClass()); Stream<ConnectorFeature> classSupports = streamOfSupported(testClass); Set<ConnectorFeature> requiredFeatures = Stream.concat( streamOfRequired(testMethod.get()), classRequires.stream()) .distinct() .collect(toImmutableSet()); Set<ConnectorFeature> supportedFeatures = streamOfSupported(testClass) .distinct() .collect(toImmutableSet()); Set<ConnectorFeature> missingFeatures = Sets.difference(requiredFeatures, supportedFeatures); return missingFeatures.isEmpty() ? enabled("All required features present") : disabled("Missing required features: " + Joiner.on(", ").join(missingFeatures)); }
Source:
public void addsCookieToResponse() throws IOException { MatcherAssert.assertThat( new RsPrint( new PsCookie( new CcPlain(), "foo", 1L ).exit(new RsEmpty(), PsCookieTest.identity) ).print(), Matchers.containsString( "Set-Cookie: foo=urn%3Atest%3A99;Path=/;HttpOnly;" ) ); }

Target:
public void addsCookieToResponse() throws IOException { MatcherAssert.assertThat( new RsPrint( new PsCookie( new CcPlain(), "foo", 1L ).exit(new RsEmpty(), new Identity.Simple("urn:test:99")) ).print(), Matchers.containsString( "Set-Cookie: foo=urn%3Atest%3A99;Path=/;HttpOnly;" ) ); }
Source:
public void setUp() { TestUtils.setUpOcBinary(); TestUtils.cleanupGitFolder("nodejs-ex"); OpenShiftExplorerView explorer = new OpenShiftExplorerView(); explorer.open(); this.connection = explorer.getOpenShift3Connection(requiredConnection.getConnection()); this.project = connection.getProject(requiredProject.getProjectName()); this.project.expand(); this.project.getService(OpenShiftResources.NODEJS_SERVICE).select(); new ContextMenu(OpenShiftLabel.ContextMenu.IMPORT_APPLICATION).select(); new DefaultShell(OpenShiftLabel.Shell.IMPORT_APPLICATION); new FinishButton().click(); new WaitWhile(new ShellWithTextIsAvailable(OpenShiftLabel.Shell.IMPORT_APPLICATION)); explorer.activate(); this.project.getService(OpenShiftResources.NODEJS_SERVICE).select(); new ContextMenu(OpenShiftLabel.ContextMenu.NEW_ADAPTER_FROM_EXPLORER).select(); new DefaultShell(OpenShiftLabel.Shell.SERVER_ADAPTER_SETTINGS); new FinishButton().click(); new WaitWhile(new ShellWithTextIsAvailable(""), TimePeriod.LONG); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); assertTrue("OpenShift 3 server adapter was not created.", new ServerAdapterExists(Version.OPENSHIFT3, OpenShiftResources.NODEJS_SERVICE).test()); this.adapter = new ServerAdapter(Version.OPENSHIFT3, OpenShiftResources.NODEJS_SERVICE); this.adapter.select(); new ContextMenu("Restart in Debug").select(); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); }

Target:
public void setUp() { TestUtils.setUpOcBinary(); TestUtils.cleanupGitFolder(OpenShiftResources.NODEJS_GIT_NAME); OpenShiftExplorerView explorer = new OpenShiftExplorerView(); explorer.open(); this.connection = explorer.getOpenShift3Connection(requiredConnection.getConnection()); this.project = connection.getProject(requiredProject.getProjectName()); this.project.expand(); this.project.getService(OpenShiftResources.NODEJS_SERVICE).select(); new ContextMenu(OpenShiftLabel.ContextMenu.IMPORT_APPLICATION).select(); new DefaultShell(OpenShiftLabel.Shell.IMPORT_APPLICATION); new FinishButton().click(); new WaitWhile(new ShellWithTextIsAvailable(OpenShiftLabel.Shell.IMPORT_APPLICATION)); explorer.activate(); this.project.getService(OpenShiftResources.NODEJS_SERVICE).select(); new ContextMenu(OpenShiftLabel.ContextMenu.NEW_ADAPTER_FROM_EXPLORER).select(); new DefaultShell(OpenShiftLabel.Shell.SERVER_ADAPTER_SETTINGS); new FinishButton().click(); new WaitWhile(new ShellWithTextIsAvailable(""), TimePeriod.LONG); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); assertTrue("OpenShift 3 server adapter was not created.", new ServerAdapterExists(Version.OPENSHIFT3, OpenShiftResources.NODEJS_SERVICE).test()); this.adapter = new ServerAdapter(Version.OPENSHIFT3, OpenShiftResources.NODEJS_SERVICE); this.adapter.select(); new ContextMenu("Restart in Debug").select(); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); }
Source:
private void removeDiskImages() { List<DiskImage> images = DisksFilter.filterImageDisks(getVm().getDiskMap().values(), ONLY_NOT_SHAREABLE, ONLY_ACTIVE); boolean shouldWipe = false; for (DiskImage image : images) { image.setStorageIds(new ArrayList<>(Arrays.asList(getParameters().getStorageDomainId()))); image.setStoragePoolId(getParameters().getStoragePoolId()); shouldWipe |= image.isWipeAfterDelete(); } List<Guid> allMemoryDisks = MemoryUtils.getMemoryDiskIdsFromSnapshots(getVm().getSnapshots()); for (Guid memoryDiskId : allMemoryDisks) { DiskImage metadataDisk = createMemoryDisk(memoryDiskId, shouldWipe); images.add(metadataDisk); } removeVmImages(images); }

Target:
private void removeDiskImages() { List<DiskImage> images = DisksFilter.filterImageDisks(getVm().getDiskMap().values(), ONLY_NOT_SHAREABLE, ONLY_ACTIVE); boolean shouldWipe = false; for (DiskImage image : images) { image.setStorageIds(new ArrayList<>(Arrays.asList(getParameters().getStorageDomainId()))); image.setStoragePoolId(getParameters().getStoragePoolId()); shouldWipe |= image.isWipeAfterDelete(); } Set<Guid> allMemoryDisks = MemoryUtils.getMemoryDiskIdsFromSnapshots(getVm().getSnapshots()); for (Guid memoryDiskId : allMemoryDisks) { DiskImage metadataDisk = createMemoryDisk(memoryDiskId, shouldWipe); images.add(metadataDisk); } removeVmImages(images); }
Source:
Pair<String, Boolean> process(OMUpdateEventBatch events) { LOG.info("Starting a 'process' run of FileSizeCountTask."); Iterator<OMDBUpdateEvent> eventIterator = events.getIterator(); while (eventIterator.hasNext()) { OMDBUpdateEvent<String, OmKeyInfo> omdbUpdateEvent = eventIterator.next(); String updatedKey = omdbUpdateEvent.getKey(); OmKeyInfo updatedValue = omdbUpdateEvent.getValue(); try{ switch (omdbUpdateEvent.getAction()) { case PUT: updateCountForKey(updatedValue, "PUT"); break; case DELETE: updateCountForKey(updatedValue, "DELETE"); break; default: LOG.debug("Skipping DB update event : " + omdbUpdateEvent .getAction()); } } catch (IOException e) { LOG.error("Unexpected exception while updating key data : ", updatedKey, e); return new ImmutablePair<>(getTaskName(), false); } } LOG.info("Completed a 'process' run of FileSizeCountTask."); return new ImmutablePair<>(getTaskName(), true); }

Target:
Pair<String, Boolean> process(OMUpdateEventBatch events) { LOG.info("Starting a 'process' run of FileSizeCountTask."); Iterator<OMDBUpdateEvent> eventIterator = events.getIterator(); updateCountFromDB(); while (eventIterator.hasNext()) { OMDBUpdateEvent<String, OmKeyInfo> omdbUpdateEvent = eventIterator.next(); String updatedKey = omdbUpdateEvent.getKey(); OmKeyInfo omKeyInfo = omdbUpdateEvent.getValue(); try{ switch (omdbUpdateEvent.getAction()) { case PUT: updateUpperBoundCount(omKeyInfo, PUT); break; case DELETE: updateUpperBoundCount(omKeyInfo, DELETE); break; default: LOG.trace("Skipping DB update event : " + omdbUpdateEvent .getAction()); } } catch (IOException e) { LOG.error("Unexpected exception while updating key data : {}", updatedKey, e.getMessage()); return new ImmutablePair<>(getTaskName(), false); } populateFileCountBySizeDB(); } LOG.info("Completed a 'process' run of FileSizeCountTask."); return new ImmutablePair<>(getTaskName(), true); }
Source:
private void throwIfInvalidSetup(PingableLeader cachedService, PingableLeader pingedService, String pingedServiceUuid) { if (cachedService == null) { return; } IllegalStateException exception = new IllegalStateException( "There is a fatal problem with the leadership election configuration! " + "This is probably caused by invalid pref files setting up the cluster " + "(exception.g. for lock server look at lock.prefs, leader.prefs, and lock_client.prefs)." + "If the preferences are specified with a host port pair list and localhost index " + "then make sure that the localhost index is correct (exception.g. actually the localhost)."); if (cachedService != pingedService) { log.error("Remote potential leaders are claiming to be each other!", exception); throw Throwables.rewrap(exception); } if (pingedServiceUuid.equals(getUUID())) { log.error("Remote potential leader is claiming to be you!", exception); throw Throwables.rewrap(exception); } }

Target:
private void throwIfInvalidSetup(PingableLeader cachedService, PingableLeader pingedService, String pingedServiceUuid) { if (cachedService == null) { return; } IllegalStateException exception = new IllegalStateException( "There is a fatal problem with the leadership election configuration! " + "This is probably caused by invalid pref files setting up the cluster " + "(e.g. for lock server look at lock.prefs, leader.prefs, and lock_client.prefs)." + "If the preferences are specified with a host port pair list and localhost index " + "then make sure that the localhost index is correct (e.g. actually the localhost)."); if (cachedService != pingedService) { log.error("Remote potential leaders are claiming to be each other!", exception); throw Throwables.rewrap(exception); } if (pingedServiceUuid.equals(getUUID())) { log.error("Remote potential leader is claiming to be you!", exception); throw Throwables.rewrap(exception); } }
Source:
public boolean couldMatch(ScriptPath path) { return path.eventLower.startsWith("bigdoors door"); }

Target:
public boolean couldMatch(ScriptPath path) { if (!path.eventLower.startsWith("bigdoors door")) { return false; } return true; }
Source:
public void statusMessageAndContinueSearch_withManyLogs_searchCorrectly() { Instant today = TimeHelper.getInstantDaysOffsetFromNow(0); AdminEmailLogPageAction action = getAction(); ShowPageResult result = getShowPageResult(action); verifyManyLogs(55, 0, 54, result.data, result.getStatusMessage()); long nextSearch = today.toEpochMilli() - 56 * LOG_MESSAGE_INTERVAL_MANY_LOGS * 1000; action = getAction("offset", String.valueOf(nextSearch)); result = getShowPageResult(action); verifyManyLogs(56, 55, 110, result.data, result.getStatusMessage()); nextSearch = today.toEpochMilli() - 112 * LOG_MESSAGE_INTERVAL_MANY_LOGS * 1000; action = getAction("offset", String.valueOf(nextSearch)); result = getShowPageResult(action); verifyManyLogs(39, 111, 149, result.data, result.getStatusMessage()); action = getAction("filterQuery", "receiver:email1@email.com"); result = getShowPageResult(action); verifyManyLogs(55, 0, 54, result.data, result.getStatusMessage()); nextSearch = today.toEpochMilli() - 56 * LOG_MESSAGE_INTERVAL_MANY_LOGS * 1000; action = getAction("filterQuery", "receiver:email1@email.com", "offset", String.valueOf(nextSearch)); result = getShowPageResult(action); verifyManyLogs(95, 55, 69, result.data, result.getStatusMessage()); }

Target:
public void statusMessageAndContinueSearch_withManyLogs_searchCorrectly() { Instant today = Instant.now(); AdminEmailLogPageAction action = getAction(); ShowPageResult result = getShowPageResult(action); verifyManyLogs(55, 0, 54, result.data, result.getStatusMessage()); long nextSearch = today.toEpochMilli() - 56 * LOG_MESSAGE_INTERVAL_MANY_LOGS * 1000; action = getAction("offset", String.valueOf(nextSearch)); result = getShowPageResult(action); verifyManyLogs(56, 55, 110, result.data, result.getStatusMessage()); nextSearch = today.toEpochMilli() - 112 * LOG_MESSAGE_INTERVAL_MANY_LOGS * 1000; action = getAction("offset", String.valueOf(nextSearch)); result = getShowPageResult(action); verifyManyLogs(39, 111, 149, result.data, result.getStatusMessage()); action = getAction("filterQuery", "receiver:email1@email.com"); result = getShowPageResult(action); verifyManyLogs(55, 0, 54, result.data, result.getStatusMessage()); nextSearch = today.toEpochMilli() - 56 * LOG_MESSAGE_INTERVAL_MANY_LOGS * 1000; action = getAction("filterQuery", "receiver:email1@email.com", "offset", String.valueOf(nextSearch)); result = getShowPageResult(action); verifyManyLogs(95, 55, 69, result.data, result.getStatusMessage()); }
Source:
public void run() { try { log.debug("Start event notification service iteration"); firstMatchSimpleFilter.clearFilterEntries(); firstMatchSimpleFilter.addFilterEntries(eventsManager.getAuditLogEventSubscribers()); firstMatchSimpleFilter.addFilterEntries( FirstMatchSimpleFilter.parse(prop.getProperty(NotificationProperties.FILTER)) ); String dbDownSubscribers = prop.getProperty(NotificationProperties.FAILED_QUERIES_NOTIFICATION_RECIPIENTS, true); if (!StringUtils.isEmpty(dbDownSubscribers)) { for (String subscriber : dbDownSubscribers.split(",")) { FilterEntry.createEntryFromAddress( EventsManager.DATABASE_UNREACHABLE, false, EventNotificationMethod.EMAIL.name(), subscriber); } } for (AuditLogEvent event : eventsManager.getAuditLogEvents()) { firstMatchSimpleFilter.processEvent(event); eventsManager.updateAuditLogEventProcessed(event.getId()); } deleteObsoleteHistoryData(); log.debug("Finished event notification service iteration"); } catch (Throwable t) { log.error("Exception while querying for notifications.", t); if (t instanceof SQLException) { distributeDbDownEvent(); } if (!Thread.interrupted()) { log.error(String.format("Failed to run the service."), t); } } }

Target:
public void run() { try { try { log.debug("Start event notification service iteration"); firstMatchSimpleFilter.clearFilterEntries(); firstMatchSimpleFilter.addFilterEntries(eventsManager.getAuditLogEventSubscribers()); firstMatchSimpleFilter.addFilterEntries( configurationFilters ); String dbDownSubscribers = prop.getProperty(NotificationProperties.FAILED_QUERIES_NOTIFICATION_RECIPIENTS, true); if (!StringUtils.isEmpty(dbDownSubscribers)) { for (String subscriber : dbDownSubscribers.split(",")) { FilterEntry.createEntry( EventsManager.DATABASE_UNREACHABLE, false, EventNotificationMethod.EMAIL.name(), subscriber); } } for (AuditLogEvent event : eventsManager.getAuditLogEvents()) { firstMatchSimpleFilter.processEvent(event); eventsManager.updateAuditLogEventProcessed(event.getId()); } deleteObsoleteHistoryData(); log.debug("Finished event notification service iteration"); } catch (SQLException se) { distributeDbDownEvent(); throw se; } } catch (Throwable t) { log.error(String.format("Failed to run the service."), t); } }
Source:
private static Map<Column, ObserverSpecification> readObservers(DataInputStream dis) throws IOException { ImmutableMap.Builder<Column, ObserverSpecification> omapBuilder = new ImmutableMap.Builder<Column, ObserverSpecification>(); ImmutableMap<Column, ObserverSpecification> omap = ImmutableMap.of(); int num = WritableUtils.readVInt(dis); for (int i = 0; i < num; i++) { Column col = ColumnUtil.readColumn(dis); String clazz = dis.readUTF(); Map<String, String> params = new HashMap<>(); int numParams = WritableUtils.readVInt(dis); for (int j = 0; j < numParams; j++) { String k = dis.readUTF(); String v = dis.readUTF(); params.put(k, v); } ObserverSpecification ospec = new ObserverSpecification(clazz, params); omapBuilder.put(col, ospec); } omap = omapBuilder.build(); return omap; }

Target:
private static Map<Column, ObserverSpecification> readObservers(DataInputStream dis) throws IOException { ImmutableMap.Builder<Column, ObserverSpecification> omapBuilder = new ImmutableMap.Builder<Column, ObserverSpecification>(); int num = WritableUtils.readVInt(dis); for (int i = 0; i < num; i++) { Column col = ColumnUtil.readColumn(dis); String clazz = dis.readUTF(); Map<String, String> params = new HashMap<>(); int numParams = WritableUtils.readVInt(dis); for (int j = 0; j < numParams; j++) { String k = dis.readUTF(); String v = dis.readUTF(); params.put(k, v); } ObserverSpecification ospec = new ObserverSpecification(clazz, params); omapBuilder.put(col, ospec); } return omapBuilder.build(); }
Source:
public void init() { if (isNeedFillDefaults()) { fillDefaults(); } if (isContextMode()) { adaptFormToEditable(); } String provider = getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_CLOUD); int indexOf = cloudProviders.indexOf(provider); if (indexOf != -1) { labelledCombo.select(indexOf); } getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_ENDPOINT); String endPoint = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_ENDPOINT)); endpointText.setText(endPoint); String clusterId = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_CLUSTER_ID)); clusterIDText.setText(clusterId); String token = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_TOKEN)); tokenText.setText(token); String folder = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_DBFS_DEP_FOLDER)); dbfsDepFolderText.setText(folder); useSparkPropertiesBtn.setSelection(getConnection().isUseSparkProperties()); updateStatus(IStatus.OK, EMPTY_STRING); }

Target:
public void init() { if (isNeedFillDefaults()) { fillDefaults(); } if (isContextMode()) { adaptFormToEditable(); } String providerValue = getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_CLOUD_PROVIDER); if (providerValue != null) { cloudProviderCombo.setText(getDatabriksCloudProviderByVaule(providerValue).getProviderLableName()); } else { cloudProviderCombo.setText(EDatabriksCloudProvider.AWS.getProviderLableName()); } String endPoint = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_ENDPOINT)); endpointText.setText(endPoint); String clusterId = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_CLUSTER_ID)); clusterIDText.setText(clusterId); String token = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_TOKEN)); tokenText.setText(token); String folder = StringUtils .trimToEmpty(getConnection().getParameters().get(ConnParameterKeys.CONN_PARA_KEY_DATABRICKS_DBFS_DEP_FOLDER)); dbfsDepFolderText.setText(folder); useSparkPropertiesBtn.setSelection(getConnection().isUseSparkProperties()); updateStatus(IStatus.OK, EMPTY_STRING); }
Source:
public WebElement getNameField(int instrNum) { return browser.driver.findElement(By.id(Const.ParamsNames.INSTRUCTOR_NAME + instrNum)); }

Target:
public WebElement getNameField(int instrNum) { return browser.driver.findElement(By.id("instructorname" + instrNum)); }
Source:
public static void init(String fileContent) { Mapping mapping = JsonUtils.safeEval(fileContent); JSONObject mappingJson = new JSONObject(mapping); documentationPathMap = new HashMap<String, String>(); for (String docTag : mappingJson.keySet()) { JSONValue url = mappingJson.get(docTag); JSONString urlString = url.isString(); if (docTag != null && urlString != null && !docTag.isEmpty() && !urlString.stringValue().isEmpty() && !documentationPathMap.containsKey(docTag)) { documentationPathMap.put(docTag, urlString.stringValue()); } } }

Target:
public static void init(String fileContent) { Mapping mapping = JsonUtils.safeEval(fileContent); JSONObject mappingJson = new JSONObject(mapping); documentationPathMap = new HashMap<String, String>(); for (String docTag : mappingJson.keySet()) { JSONString urlString = mappingJson.get(docTag).isString(); if (docTag != null && urlString != null && !docTag.isEmpty() && !urlString.stringValue().isEmpty() && !documentationPathMap.containsKey(docTag)) { documentationPathMap.put(docTag, urlString.stringValue()); } } }
Source:
public void run() { for(; namesystem != null ;) { if(namesystem.isRunning()) checkLeases(); try { Thread.sleep(HdfsServerConstants.NAMENODE_LEASE_RECHECK_INTERVAL); } catch(InterruptedException ie) { if (LOG.isDebugEnabled()) { LOG.debug(name + " is interrupted.", ie); } } } }

Target:
public void run() { while(shouldRunMonitor) { if(namesystem.isRunning()) checkLeases(); try { Thread.sleep(HdfsServerConstants.NAMENODE_LEASE_RECHECK_INTERVAL); } catch(InterruptedException ie) { if (LOG.isDebugEnabled()) { LOG.debug(name + " is interrupted.", ie); } } } LOG.warn("Exiting LeaseMonitor."); }
Source:
public int getGracePeriodDaysForCompaction() { return config.get(PRIAM_PRE + ".forgottenFileGracePeriodDaysForCompaction", 5); }

Target:
public int getGracePeriodDaysForCompaction() { return config.get(PRIAM_PRE + ".gracePeriodDaysForCompaction", 5); }
Source:
public SubmissionDefinitionRest fromModel(SubmissionConfig obj) { SubmissionDefinitionRest sd = new SubmissionDefinitionRest(); sd.setName(obj.getSubmissionName()); sd.setDefaultConf(obj.isDefaultConf()); List<SubmissionSectionRest> panels = new LinkedList<SubmissionSectionRest>(); for (int idx = 0; idx < obj.getNumberOfSteps(); idx++) { SubmissionStepConfig step = obj.getStep(idx); SubmissionSectionRest sp = panelConverter.convert(step); panels.add(sp); } HttpServletRequest request = requestService.getCurrentRequest().getHttpServletRequest(); Context context = null; try { context = ContextUtil.obtainContext(request); List<Collection> collections = panelConverter.getSubmissionConfigReader().getCollectionsBySubmissionConfig(context, obj.getSubmissionName()); List<CollectionRest> collectionsRest = collections.stream().map((collection) -> collectionConverter.convert(collection)).collect( Collectors.toList()); sd.setCollections(collectionsRest); } catch (SQLException e) { log.error(e.getMessage(), e); } sd.setPanels(panels); return sd; }

Target:
public SubmissionDefinitionRest fromModel(SubmissionConfig obj) { SubmissionDefinitionRest sd = new SubmissionDefinitionRest(); sd.setName(obj.getSubmissionName()); sd.setDefaultConf(obj.isDefaultConf()); List<SubmissionSectionRest> panels = new LinkedList<SubmissionSectionRest>(); for (int idx = 0; idx < obj.getNumberOfSteps(); idx++) { SubmissionStepConfig step = obj.getStep(idx); SubmissionSectionRest sp = panelConverter.convert(step); panels.add(sp); } HttpServletRequest request = requestService.getCurrentRequest().getHttpServletRequest(); Context context = null; try { context = ContextUtil.obtainContext(request); List<Collection> collections = panelConverter.getSubmissionConfigReader().getCollectionsBySubmissionConfig(context, obj.getSubmissionName()); List<CollectionRest> collectionsRest = collections.stream().map((collection) -> collectionConverter.convert(collection)).collect( Collectors.toList()); sd.setCollections(collectionsRest); } catch (SQLException | IllegalStateException | SubmissionConfigReaderException e) { log.error(e.getMessage(), e); } sd.setPanels(panels); return sd; }
Source:
public static String threadDump() { final StringBuilder dump = new StringBuilder(); @SuppressWarnings("checkstyle:AbbreviationAsWordInName") final java.lang.management.ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); final java.lang.management.ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100); for (Entry<Thread, StackTraceElement[]> entry: Thread.getAllStackTraces().entrySet()) { Thread t = entry.getKey(); ThreadInfo threadInfo = threadMXBean.getThreadInfo(t.getId()); if (threadInfo == null) { continue; } dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append("\" "); if (t.isDaemon()) { dump.append("(DAEMON)"); } dump.append("\n lock: "); dump.append(threadInfo.getLockName()); dump.append(" owner: "); dump.append(threadInfo.getLockOwnerName()); final Thread.State state = threadInfo.getThreadState(); dump.append("\n java.lang.Thread.State: "); dump.append(state); for (final StackTraceElement stackTraceElement : entry.getValue()) { dump.append("\n at "); dump.append(stackTraceElement); } dump.append("\n\n"); } return dump.toString(); }

Target:
public static String threadDump() { final StringBuilder dump = new StringBuilder(); final java.lang.management.ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); final java.lang.management.ThreadInfo[] threadInfos = threadMxBean.getThreadInfo(threadMxBean.getAllThreadIds(), 100); for (Entry<Thread, StackTraceElement[]> entry: Thread.getAllStackTraces().entrySet()) { Thread t = entry.getKey(); ThreadInfo threadInfo = threadMxBean.getThreadInfo(t.getId()); if (threadInfo == null) { continue; } dump.append('"'); dump.append(threadInfo.getThreadName()); dump.append("\" "); if (t.isDaemon()) { dump.append("(DAEMON)"); } dump.append("\n lock: "); dump.append(threadInfo.getLockName()); dump.append(" owner: "); dump.append(threadInfo.getLockOwnerName()); final Thread.State state = threadInfo.getThreadState(); dump.append("\n java.lang.Thread.State: "); dump.append(state); for (final StackTraceElement stackTraceElement : entry.getValue()) { dump.append("\n at "); dump.append(stackTraceElement); } dump.append("\n\n"); } return dump.toString(); }
Source:
public void testConnection() throws Exception { try(SpliceWatcher watcher2 = new SpliceWatcher(CLASS_NAME)) { watcher2.setConnection( watcher2.connectionBuilder().useOLAP(true).build() ); ResultSet rs = watcher2.executeQuery("select testConnection() from test"); String result = rs.next() ? rs.getString(1) : null; Assert.assertNotNull(result); Assert.assertTrue(result, result.compareTo("Got an internal connection") == 0); } }

Target:
public void testConnection() throws Exception { try(SpliceWatcher watcher2 = new SpliceWatcher(CLASS_NAME)) { watcher2.setConnection( watcher2.connectionBuilder().useOLAP(true).build() ); try(ResultSet rs = watcher2.executeQuery("select testConnection() from test")) { String result = rs.next() ? rs.getString(1) : null; Assert.assertNotNull(result); Assert.assertTrue(result, result.compareTo("Got an internal connection") == 0); } } }
Source:
private Path executeNcksAndOutputToFile(String baseFilename, Path tempFile) throws IOException, InterruptedException { List<String> ncksCommand = new ArrayList<>(); ncksCommand.add(ncksPath); ncksCommand.add("--no_nm_prn"); ncksCommand.add("-a"); ncksCommand.add(tempFile.toString()); logger.info(ncksCommand.toString()); ProcessBuilder processor = new ProcessBuilder(ncksCommand); processor.redirectError(ProcessBuilder.Redirect.PIPE); final Process process = processor.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder builder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { builder.append(line + System.getProperty("line.separator")); } try { process.waitFor(); } catch (InterruptedException e) { logger.error(String.format("Interrupted: '%s'", e.getMessage())); logger.error(process.getErrorStream().toString()); throw e; } String rawOutput = builder.toString(); String outputCSV = parseNcks(rawOutput); String csvFilename = String.format("%s.%s", baseFilename, extension); File csvFile = new File(csvFilename); FileUtils.writeStringToFile(csvFile, outputCSV); return csvFile.toPath(); }

Target:
private Path executeNcksAndOutputToFile(String baseFilename, Path tempFile) throws IOException, InterruptedException { List<String> ncksCommand = new ArrayList<>(); ncksCommand.add(ncksPath); ncksCommand.add("--no_nm_prn"); ncksCommand.add("-a"); ncksCommand.add(tempFile.toString()); logger.info(ncksCommand.toString()); ProcessBuilder processor = new ProcessBuilder(ncksCommand); processor.redirectError(ProcessBuilder.Redirect.PIPE); final Process process = processor.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); InputStreamReader errorStream = new InputStreamReader(process.getErrorStream()); BufferedReader bufferedErrorStream = new BufferedReader(errorStream); StringBuilder builder = new StringBuilder(); String line; String errLine = null; while ((line = br.readLine()) != null || (errLine = bufferedErrorStream.readLine()) != null) { if (line != null) { builder.append(line + System.getProperty("line.separator")); } if (errLine != null) { logger.error(errLine); } } try { process.waitFor(); } catch (InterruptedException e) { logger.error(String.format("Interrupted: '%s'", e.getMessage())); throw e; } String rawOutput = builder.toString(); String outputCSV = parseNcks(rawOutput); String csvFilename = String.format("%s.%s", baseFilename, extension); File csvFile = new File(csvFilename); FileUtils.writeStringToFile(csvFile, outputCSV); return csvFile.toPath(); }
Source:
public static Collection<ExtMap> populateGroups(final ExtensionProxy extension, final String namespace, final ExtMap input) { final Collection<ExtMap> groups = new ArrayList<>(); queryImpl(extension, namespace, input, new QueryResultHandler() { @Override public boolean handle(Collection<ExtMap> queryResults) { boolean result = true; for (ExtMap queryResult : queryResults) { if (groups.size() < QUERIES_RESULTS_LIMIT) { groups.add(queryResult); } else { result = false; break; } } return result; } }); return groups; }

Target:
public static Collection<ExtMap> populateGroups(final ExtensionProxy extension, final String namespace, final ExtMap input) { final Collection<ExtMap> groups = new ArrayList<>(); queryImpl(extension, namespace, input, new LimitingQueryResultSizeHandler(groups)); return groups; }
Source:
public Session getSession(String keyspace) { Session session = sessions.get(keyspace); if (session == null) { LOG.debug("Constructing session for keyspace [" + keyspace + "]"); session = initializeSession(keyspace); sessions.put(keyspace, session); } return session; }

Target:
public Session getSession(String keyspace) { Session session = sessions.get(keyspace); if (session == null) { LOG.debug("Constructing session for keyspace [" + keyspace + "]"); session = initializeSession(keyspace); } return session; }
Source:
public void initialize() { logger.debug("Initializing hue light handler."); final String configLightId = (String) getConfig().get(LIGHT_ID); if (configLightId != null) { lightId = configLightId; if (getHueBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); FullLight fullLight = getLight(); if (fullLight != null) { String modelId = fullLight.getModelID().replaceAll(NORMALIZE_ID_REGEX, "_"); updateProperty(Thing.PROPERTY_MODEL_ID, modelId); updateProperty(Thing.PROPERTY_FIRMWARE_VERSION, fullLight.getSoftwareVersion()); String vendor = getVendor(modelId); if (vendor != null) { updateProperty(Thing.PROPERTY_VENDOR, vendor); } isOsramPar16 = OSRAM_PAR16_50_TW_MODEL_ID.equals(modelId); } } } }

Target:
public void initialize() { logger.debug("Initializing hue light handler."); final String configLightId = (String) getConfig().get(LIGHT_ID); if (configLightId != null) { lightId = configLightId; if (getHueBridgeHandler() != null) { ThingStatusInfo statusInfo = getBridge().getStatusInfo(); updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription()); updateProperties(); } } }
Source:
public Map<String, Object> parse(String input) { try { Map<String, Object> map = new LinkedHashMap<>(); JsonNode root = objectMapper.readTree(input); Iterator<String> keysIter = (fieldNames == null ? root.fieldNames() : fieldNames.iterator()); while (keysIter.hasNext()) { String key = keysIter.next(); if (exclude.contains(key)) { continue; } JsonNode node = root.path(key); if (node.isArray()) { final List<Object> nodeValue = Lists.newArrayListWithExpectedSize(node.size()); for (final JsonNode subnode : node) { final Object subnodeValue = valueFunction.apply(subnode); if (subnodeValue != null) { nodeValue.add(subnodeValue); } } map.put(key.toLowerCase(), nodeValue); } else { final Object nodeValue = valueFunction.apply(node); if (nodeValue != null) { map.put(key.toLowerCase(), nodeValue); } } } return map; } catch (Exception e) { throw new ParseException(e, "Unable to parse row [%s]", input); } }

Target:
public Map<String, Object> parse(String input) { try { Map<String, Object> map = new LinkedHashMap<>(); JsonNode root = objectMapper.readTree(input); Iterator<String> keysIter = (fieldNames == null ? root.fieldNames() : fieldNames.iterator()); while (keysIter.hasNext()) { String key = keysIter.next(); if (exclude.contains(key.toLowerCase())) { continue; } JsonNode node = root.path(key); if (node.isArray()) { final List<Object> nodeValue = Lists.newArrayListWithExpectedSize(node.size()); for (final JsonNode subnode : node) { final Object subnodeValue = valueFunction.apply(subnode); if (subnodeValue != null) { nodeValue.add(subnodeValue); } } map.put(key.toLowerCase(), nodeValue); } else { final Object nodeValue = valueFunction.apply(node); if (nodeValue != null) { map.put(key.toLowerCase(), nodeValue); } } } return map; } catch (Exception e) { throw new ParseException(e, "Unable to parse row [%s]", input); } }
Source:
private HttpResponse handleGet(List<String> storeList) { logger.info("Received a Http GET Admin request"); String response; if(storeList == null || storeList.isEmpty()) { response = storeClientConfigs.getAllConfigs(); } else { response = storeClientConfigs.getSpecificConfigs(storeList); } HttpResponseStatus responseStatus; if(response.contains(StoreClientConfigService.ERROR_MESSAGE_PARAM_KEY) && response.contains(StoreClientConfigService.STORE_NOT_FOUND_ERROR)) { responseStatus = NOT_FOUND; } else { responseStatus = OK; } return sendResponse(responseStatus, response); }

Target:
private HttpResponse handleGet(List<String> storeList) { logger.info("Handling a Http GET Admin request"); String response; if(storeList == null || storeList.isEmpty()) { response = storeClientConfigs.getAllConfigs(); } else { response = storeClientConfigs.getSpecificConfigs(storeList); } HttpResponseStatus responseStatus; if(response.contains(StoreClientConfigService.ERROR_MESSAGE_PARAM_KEY) && response.contains(StoreClientConfigService.STORE_NOT_FOUND_ERROR)) { responseStatus = NOT_FOUND; } else { responseStatus = OK; } return sendResponse(responseStatus, response); }
Source:
public Event read(Player caster, GameMessage msg) { int targetPlayerId = msg.getPayload().getShort(false, ValueType.ADD); int targetSpellId = msg.getPayload().getShort(false, ByteOrder.LITTLE); MobList<Player> players = caster.getWorld().getPlayers(); Optional<Player> targetPlayer = players.retrieve(targetPlayerId); if (targetPlayer.isEmpty()) { throw new InvalidSpellTargetException(targetPlayerId); } return new CastOnPlayerEvent(caster, targetSpellId, targetPlayerId); }

Target:
public Event read(Player caster, GameMessage msg) { int targetId = msg.getPayload().getShort(false, ValueType.ADD); int spellId = msg.getPayload().getShort(false, ByteOrder.LITTLE); Optional<Player> targetPlayer = findTarget(caster, targetId); if (targetPlayer.isPresent()) { Player target = targetPlayer.get(); this.submitEventFor(target, new CastOnPlayerEvent(caster, spellId, target)); } return null; }
Source:
public final Object getContents(final String directory) { File f = new File(directory); String[] content = f.list(); Object[] o = new Object[content.length]; for (int i = 0; i < content.length; i++) { o[i] = content[i]; } if (content != null) { SImmutableArray sia = new SImmutableArray(o, Classes.arrayClass); return sia; } else { return Nil.nilObject; } }

Target:
public final Object getContents(final String directory) { File f = new File(directory); String[] content = f.list(); if (content == null) { return Nil.nilObject; } Object[] o = new Object[content.length]; System.arraycopy(content, 0, o, 0, content.length); return new SImmutableArray(o, Classes.arrayClass); }
Source:
boolean validateGroup(AmbariTProxyConfiguration tProxyConfiguration, String proxyUserName, UserEntity userEntity) { String allowedGroups = tProxyConfiguration.getAllowedGroups(proxyUserName); if (StringUtils.isNotEmpty(allowedGroups)) { Set<String> groupSpecs = Arrays.stream(allowedGroups.split("\\s*,\\s*")) .map(s -> s.trim().toLowerCase()) .collect(toSet()); if (groupSpecs.contains("*")) { return true; } else { Set<MemberEntity> memberEntities = userEntity.getMemberEntities(); if (memberEntities != null) { for (MemberEntity memberEntity : memberEntities) { GroupEntity group = memberEntity.getGroup(); if (group != null) { String groupName = group.getGroupName(); if (groupSpecs.contains(groupName.toLowerCase())) { return true; } } } } } } return false; }

Target:
boolean validateGroup(AmbariTProxyConfiguration tProxyConfiguration, String proxyUserName, UserEntity userEntity) { String allowedGroups = tProxyConfiguration.getAllowedGroups(proxyUserName); if (StringUtils.isNotEmpty(allowedGroups)) { Set<String> groupSpecs = Arrays.stream(allowedGroups.split("\\s*,\\s*")) .map(s -> s.trim().toLowerCase()) .collect(toSet()); if (groupSpecs.contains("*")) { return true; } else { Set<MemberEntity> memberEntities = userEntity.getMemberEntities(); if (memberEntities != null) { for (MemberEntity memberEntity : memberEntities) { GroupEntity group = memberEntity.getGroup(); if (group != null) { String groupName = group.getGroupName(); if (StringUtils.isNotEmpty(groupName) && groupSpecs.contains(groupName.toLowerCase())) { return true; } } } } } } return false; }
Source:
public void restoreRedundancyWithIncludeRegionArgumentRestoresOnlyThoseRegions() { List<String> regionNames = getAllRegionNames(); createAndPopulateRegions(regionNames); int numberOfServers = servers.size(); regionNames.forEach(region -> locator .waitUntilRegionIsReadyOnExactlyThisManyServers(SEPARATOR + region, numberOfServers)); String regionToInclude = HIGH_REDUNDANCY_REGION_NAME; List<String> nonIncludedRegions = new ArrayList<>(regionNames); nonIncludedRegions.remove(regionToInclude); String command = new CommandStringBuilder(COMMAND_NAME) .addOption(INCLUDE_REGION, regionToInclude).getCommandString(); CommandResultAssert commandResult = gfsh.executeAndAssertThat(command).statusIsSuccess() .hasNoSection(ZERO_REDUNDANCY_SECTION) .hasNoSection(UNDER_REDUNDANCY_SECTION) .doesNotContainOutput(nonIncludedRegions.toArray(new String[0])); InfoResultModelAssert summary = commandResult.hasInfoSection(SUMMARY_SECTION); summary.hasOutput().contains(ZERO_REDUNDANT_COPIES + 0); summary.hasOutput().contains(PARTIALLY_SATISFIED_REDUNDANCY + 0); summary.hasOutput().contains(FULLY_SATISFIED_REDUNDANCY + 1); InfoResultModelAssert satisfiedSection = commandResult.hasInfoSection(SATISFIED_REDUNDANCY_SECTION); satisfiedSection.hasHeader().isEqualTo(REDUNDANCY_SATISFIED_FOR_REGIONS); satisfiedSection.hasOutput().contains(regionToInclude); InfoResultModelAssert primariesSection = commandResult.hasInfoSection(PRIMARIES_INFO_SECTION); primariesSection.hasOutput().contains(PRIMARY_TRANSFERS_COMPLETED, PRIMARY_TRANSFER_TIME); int numberOfActiveServers = servers.size(); servers.get(0).invoke(() -> { for (String regionName : regionNames) { boolean shouldBeSatisfied = regionName.equals(regionToInclude); assertRedundancyStatusForRegion(regionName, shouldBeSatisfied); assertPrimariesBalanced(regionName, numberOfActiveServers, shouldBeSatisfied); } }); }

Target:
public void restoreRedundancyWithIncludeRegionArgumentRestoresOnlyThoseRegions() { List<String> regionNames = getAllRegionNames(); createAndPopulateRegions(regionNames); int numberOfServers = servers.size(); regionNames.forEach(region -> locator .waitUntilRegionIsReadyOnExactlyThisManyServers(SEPARATOR + region, numberOfServers)); String regionToInclude = HIGH_REDUNDANCY_REGION_NAME; List<String> nonIncludedRegions = new ArrayList<>(regionNames); nonIncludedRegions.remove(regionToInclude); String command = new CommandStringBuilder(RESTORE_REDUNDANCY) .addOption(REDUNDANCY_INCLUDE_REGION, regionToInclude).getCommandString(); CommandResultAssert commandResult = gfsh.executeAndAssertThat(command).statusIsSuccess() .doesNotContainOutput(nonIncludedRegions.toArray(new String[0])); verifyGfshOutput(commandResult, new ArrayList<>(), new ArrayList<>(), Collections.singletonList(regionToInclude)); int numberOfActiveServers = servers.size(); servers.get(0).invoke(() -> { for (String regionName : regionNames) { boolean shouldBeSatisfied = regionName.equals(regionToInclude); assertRedundancyStatusForRegion(regionName, shouldBeSatisfied); assertPrimariesBalanced(regionName, numberOfActiveServers, shouldBeSatisfied); } }); }
Source:
public WorkunitInfo createWUFromECL(WorkunitInfo wu) throws Exception { WorkunitInfo createdWU = null; if (wsWorkunitsServiceSoapProxy == null) throw new Exception("wsWorkunitsServiceSoapProxy not available"); else { WUCreateAndUpdate wucreateparameters = new WUCreateAndUpdate(); wucreateparameters.setAction(1); wucreateparameters.setQueryText(wu.getECL()); wucreateparameters.setApplicationValues(wu.getRawApplicationValues()); wucreateparameters.setDebugValues(wu.getDebugValues()); wucreateparameters.setJobname(wu.getJobname()); wucreateparameters.setClusterOrig(wu.getCluster()); wucreateparameters.setResultLimit(wu.getResultLimit()); wucreateparameters.setWuid(wu.getWuid()); WUUpdateResponse wuUpdateResponse = wsWorkunitsServiceSoapProxy.WUCreateAndUpdate(wucreateparameters); ArrayOfEspException exceptions = wuUpdateResponse.getExceptions(); if (exceptions != null) throwWsWUExceptions(exceptions, "Error compiling ECL query"); if (wuUpdateResponse.getWorkunit().getStateID() != 1) { WUWaitCompiled wuwaitcompiledparameters = new WUWaitCompiled(); wuwaitcompiledparameters.setWait(10); wuwaitcompiledparameters.setWuid(wuUpdateResponse.getWorkunit().getWuid()); WUWaitResponse wuWaitResponse = wsWorkunitsServiceSoapProxy.WUWaitCompiled(wuwaitcompiledparameters); exceptions = wuWaitResponse.getExceptions(); if (exceptions != null) throwWsWUExceptions(exceptions, "Error compiling ECL query"); if (wuWaitResponse.getStateID() != 1) throw new Exception("Error: compilation exceeded timeout"); } createdWU = new WorkunitInfo(wuUpdateResponse.getWorkunit()); createdWU.setMaxMonitorMillis(wu.getMaxMonitorMillis()); createdWU.setCluster(wu.getCluster()); createdWU.setJobname(wu.getJobname()); createdWU.setSleepMillis(wu.getSleepMillis()); createdWU.setOriginalEclWatchUrl(getEclWatchUrl()); } return createdWU; }

Target:
public WorkunitInfo createWUFromECL(WorkunitInfo wu) throws Exception { WorkunitInfo createdWU = null; if (wsWorkunitsServiceSoapProxy == null) throw new Exception("wsWorkunitsServiceSoapProxy not available"); else { WUCreateAndUpdate wucreateparameters = new WUCreateAndUpdate(); wucreateparameters.setAction(1); wucreateparameters.setQueryText(wu.getECL()); wucreateparameters.setApplicationValues(wu.getRawApplicationValues()); wucreateparameters.setDebugValues(wu.getDebugValues()); wucreateparameters.setJobname(wu.getJobname()); wucreateparameters.setClusterOrig(wu.getCluster()); wucreateparameters.setResultLimit(wu.getResultLimit()); wucreateparameters.setWuid(wu.getWuid()); WUUpdateResponse wuUpdateResponse = wsWorkunitsServiceSoapProxy.WUCreateAndUpdate(wucreateparameters); ArrayOfEspException exceptions = wuUpdateResponse.getExceptions(); if (exceptions == null) { createdWU = new WorkunitInfo(wuUpdateResponse.getWorkunit()); createdWU.setMaxMonitorMillis(wu.getMaxMonitorMillis()); createdWU.setCluster(wu.getCluster()); createdWU.setJobname(wu.getJobname()); createdWU.setSleepMillis(wu.getSleepMillis()); createdWU.setOriginalEclWatchUrl(getEclWatchUrl()); } else { throwWsWUExceptions(exceptions, "Error compiling ECL query"); } } return createdWU; }
Source:
public void execute() throws Exception { if (!CassandraMonitor.isCassadraStarted()) { logger.debug("Cassandra is not started, hence SnapshotMetaService will not run"); return; } try { logger.info("Initializaing SnapshotMetaService"); snapshotName = generateSnapshotName(); metaFileWriter.cleanupOldMetaFiles(); cassandraOperations.takeSnapshot(snapshotName); Path metaFilePath = processSnapshot(); metaFileWriter.uploadMetaFile(metaFilePath, true); logger.info("Finished processing snapshot meta service"); } catch (Exception e) { logger.error("Error while executing SnapshotMetaService", e); } }

Target:
public void execute() throws Exception { if (!CassandraMonitor.hasCassadraStarted()) { logger.debug("Cassandra has not started, hence SnapshotMetaService will not run"); return; } try { Instant snapshotInstant = DateUtil.getInstant(); snapshotName = generateSnapshotName(snapshotInstant); logger.info("Initializing SnapshotMetaService for taking a snapshot {}" + snapshotName); metaFileManager.cleanupOldMetaFiles(); cassandraOperations.takeSnapshot(snapshotName); processSnapshot(snapshotInstant).uploadMetaFile(true); logger.info("Finished processing snapshot meta service"); } catch (Exception e) { logger.error("Error while executing SnapshotMetaService", e); } }
Source:
public Placement(@NonNull String divName, long networkId, long siteId, int... adTypes) { setDivName(divName); setNetworkId(networkId); setSiteId(siteId); if (adTypes == null || adTypes.length < 1) { throw new IllegalArgumentException("At least one ad type must be specified"); } for (int adType : adTypes ) { addAdType(adType); } }

Target:
public Placement(@NonNull String divName, long networkId, long siteId, int... adTypes) { setDivName(divName); setNetworkId(networkId); setSiteId(siteId); if (adTypes == null || adTypes.length < 1) { throw new IllegalArgumentException("At least one ad type must be specified"); } addAdTypes(adTypes); }
Source:
public void loadSegment() throws Exception { _indexSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR, SEGMENT_NAME), ReadMode.heap); _upsertIndexSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR, SEGMENT_NAME), ReadMode.heap); ((ImmutableSegmentImpl) _upsertIndexSegment) .enableUpsert(new PartitionUpsertMetadataManager("testTable", 0, _serverMetrics), new ThreadSafeMutableRoaringBitmap()); }

Target:
public void loadSegment() throws Exception { _indexSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR, SEGMENT_NAME), ReadMode.heap); ServerMetrics serverMetrics = Mockito.mock(ServerMetrics.class); _upsertIndexSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR, SEGMENT_NAME), ReadMode.heap); ((ImmutableSegmentImpl) _upsertIndexSegment) .enableUpsert(new PartitionUpsertMetadataManager("testTable_REALTIME", 0, serverMetrics), new ThreadSafeMutableRoaringBitmap()); }