method2testcases
stringlengths
118
6.63k
### Question: Benchmark { protected static byte[] fileAsBytes(String deviceDataFile) throws IOException { File file = new File(deviceDataFile); byte fileContent[] = new byte[(int) file.length()]; FileInputStream fin = new FileInputStream(file); try { int bytesRead = fin.read(fileContent); if (bytesRead != file.length()) { throw new IllegalStateException("File not completely read"); } } finally { fin.close(); } return fileContent; } Benchmark(String userAgentFile); double getAverageDetectionTimePerThread(); int getCount(); void run(Dataset dataSet, int numberOfThreads); static void main(String[] args); }### Answer: @Test public void testStreamMemory() throws Exception { logger.info("Stream Array / Memory"); testDataSet(StreamFactory.create(Benchmark.fileAsBytes(Shared.getLitePatternV32()))); }
### Question: Match { void reset() { this.state.reset(); this.overriddenProfiles = null; this.cookie = null; this.propertyValueOverridesCookies = null; } Match(Provider provider); Match(Provider provider, String targetUserAgent); Dataset getDataSet(); String getTargetUserAgent(); long getElapsed(); Signature getSignature(); MatchMethods getMethod(); int getClosestSignaturesCount(); int getSignaturesCompared(); int getSignaturesRead(); int getRootNodesEvaluated(); int getNodesEvaluated(); int getNodesFound(); int getStringsRead(); Profile[] getProfiles(); int getDifference(); String getDeviceId(); byte[] getDeviceIdAsByteArray(); String getUserAgent(); @Deprecated Map<String, String[]> getResults(); Values getValues(Property property); Values getValues(String propertyName); void updateProfile(int profileId); @Override String toString(); public String cookie; }### Answer: @Test public void testCreate() throws IOException, InterruptedException { long start; Provider provider = new Provider(MemoryFactory.create(new FileInputStream(Filename.LITE_PATTERN_V32))); List<Match> matches= new ArrayList<Match>(NUMBER_OF_TESTS); for (int i = 0; i< NUMBER_OF_TESTS; i++) { matches.add(provider.createMatch()); } create(provider, matches); System.gc(); Thread.sleep(2000); start = System.currentTimeMillis(); create(provider, matches); System.out.printf("%,d millis to create%n", System.currentTimeMillis()-start); newMatch(provider, matches); System.gc(); Thread.sleep(2000); start = System.currentTimeMillis(); newMatch(provider, matches); System.out.printf("%,d millis for new %n", System.currentTimeMillis()-start); reset(matches); System.gc(); Thread.sleep(2000); start = System.currentTimeMillis(); reset(matches); System.out.printf("%,d millis to reset%n", System.currentTimeMillis()-start); System.gc(); Thread.sleep(2000); start = System.currentTimeMillis(); reset(matches); System.out.printf("%,d millis to reset%n", System.currentTimeMillis()-start); System.gc(); Thread.sleep(2000); start = System.currentTimeMillis(); newMatch(provider, matches); System.out.printf("%,d millis new%n", System.currentTimeMillis()-start); System.gc(); Thread.sleep(2000); start = System.currentTimeMillis(); create(provider, matches); System.out.printf("%,d millis create%n", System.currentTimeMillis()-start); }
### Question: DatasetBuilder { public static BuildFromFile file() { return new DatasetBuilder().new BuildFromFile(); } private DatasetBuilder(); static BuildFromFile file(); static BuildFromBuffer buffer(); static final int STRINGS_CACHE_SIZE; static final int NODES_CACHE_SIZE; static final int VALUES_CACHE_SIZE; static final int PROFILES_CACHE_SIZE; static final int SIGNATURES_CACHE_SIZE; }### Answer: @Test public void testDefaultIsNoCaches () throws IOException { IndirectDataset dataset = DatasetBuilder.file() .build(Filename.LITE_PATTERN_V32); assertEquals(null, dataset.getCache(StringsCache)); assertEquals(null, dataset.getCache(SignaturesCache)); assertEquals(null, dataset.getCache(NodesCache)); assertEquals(null, dataset.getCache(ValuesCache)); assertEquals(null, dataset.getCache(ProfilesCache)); } @Test public void testAddDefaultCaches () throws IOException { IndirectDataset dataset = DatasetBuilder.file() .configureDefaultCaches() .build(Filename.LITE_PATTERN_V32); assertEquals(LruCache.class, dataset.getCache(StringsCache).getClass()); assertEquals(LruCache.class, dataset.getCache(SignaturesCache).getClass()); assertEquals(LruCache.class, dataset.getCache(NodesCache).getClass()); assertEquals(LruCache.class, dataset.getCache(ValuesCache).getClass()); assertEquals(LruCache.class, dataset.getCache(ProfilesCache).getClass()); } @Test public void testCreate32FromBuilder () throws Exception { File temp = File.createTempFile("Test",".dat"); File source = new File(Filename.LITE_PATTERN_V32); Files.copy(source, temp); Dataset dataset = DatasetBuilder.file() .lastModified(new Date()) .build(temp.getPath()); ViableProvider.ensureViableProvider(new Provider(dataset)); dataset.close(); assertTrue(temp.exists()); dataset = DatasetBuilder.file() .setTempFile() .lastModified(new Date()) .build(temp.getPath()); ViableProvider.ensureViableProvider(new Provider(dataset)); dataset.close(); assertFalse(temp.exists()); } @Test(expected = NoSuchElementException.class) public void testIterator () throws Exception { IndirectDataset indirectDataset = DatasetBuilder.file() .lastModified(new Date()) .build(Filename.LITE_PATTERN_V32); Iterator it = indirectDataset.profiles.iterator(); while (it.hasNext()) { it.next(); } it.next(); } @Test public void testMemoryStreamDatasetConsistentNoCache () throws IOException { IndirectDataset indirectDataset = DatasetBuilder.file() .lastModified(new Date()) .build(Filename.LITE_PATTERN_V32); Dataset memoryDataset = MemoryFactory.create(Filename.LITE_PATTERN_V32); compareDatasets(indirectDataset, memoryDataset); } @Test public void testMemoryStreamDatasetConsistentPartialLruCache () throws IOException { IndirectDataset indirectDataset = DatasetBuilder.file() .configureCache(NodesCache, new CacheOptions(20, LruCache.builder())) .configureCache(ValuesCache, new CacheOptions(100, LruCache.builder())) .configureCache(StringsCache, new CacheOptions(100, LruCache.builder())) .build(Filename.LITE_PATTERN_V32); Dataset memoryDataset = MemoryFactory.create(Filename.LITE_PATTERN_V32); compareDatasets(indirectDataset, memoryDataset); }
### Question: StreamFactory { public static IndirectDataset create(byte[] data) throws IOException { return DatasetBuilder.buffer() .configureDefaultCaches() .build(data); } static IndirectDataset create(byte[] data); static IndirectDataset create(String filePath); static IndirectDataset create(String filePath, boolean isTempFile); static IndirectDataset create(String filepath, Date lastModified, boolean isTempFile); }### Answer: @Test public void testCreate32FromFilename () throws Exception { File temp = File.createTempFile("Test",".dat"); File source = new File(Filename.LITE_PATTERN_V32); Files.copy(source, temp); Dataset dataset = StreamFactory.create(temp.getPath()); ViableProvider.ensureViableProvider(new Provider(dataset)); dataset.close(); assertTrue(temp.exists()); dataset = StreamFactory.create(temp.getPath(), true); ViableProvider.ensureViableProvider(new Provider(dataset)); dataset.close(); assertFalse(temp.exists()); } @Test public void testCreate31FromFilename () throws Exception { Dataset dataset = StreamFactory.create(Filename.LITE_PATTERN_V31); ViableProvider.ensureViableProvider(new Provider(dataset)); } @Test public void testMemoryStreamDatasetConsistentDefault () throws IOException { IndirectDataset indirectDataset = StreamFactory.create(Filename.LITE_PATTERN_V32); Dataset memoryDataset = MemoryFactory.create(Filename.LITE_PATTERN_V32); compareDatasets(indirectDataset, memoryDataset); } @Test public void testDefaultCache () throws Exception { Dataset dataset = StreamFactory.create(Filename.LITE_PATTERN_V32); Provider provider = new Provider(dataset, 20); cacheTests(provider); }
### Question: FindProfiles implements Closeable { public FindProfiles() throws IOException { provider = new Provider(StreamFactory.create(Shared.getLitePatternV32(), false)); } FindProfiles(); static void main(String[] args); @Override void close(); }### Answer: @Test public void FindProfilesExample() throws IOException { fp = new FindProfiles(); List<Profile> profiles = fp.provider.dataSet.findProfiles("IsMobile", "True", null); for (Profile profile : profiles) { assertEquals(profile.getValues("IsMobile").toString(), "True"); } profiles = fp.provider.dataSet.findProfiles("IsMobile", "False", null); for (Profile profile : profiles) { assertEquals(profile.getValues("IsMobile").toString(), "False"); } }
### Question: Provider { public Match match(final Map<String, String> headers) throws IOException { return match(headers, createMatch()); } Provider(Dataset dataSet); Provider(Dataset dataSet, int cacheSize); Provider(Dataset dataSet, ILoadingCache cache); Provider(Dataset dataSet, boolean recordDetectionTime, ILoadingCache cache); long getDetectionCount(); long[] getMethodCounts(); double getPercentageCacheMisses(); @Deprecated long getCacheSwitches(); double getCacheRequests(); long getCacheMisses(); Match createMatch(); Match match(final Map<String, String> headers); Match match(final Map<String, String> headers, Match match); Match match(String targetUserAgent); Match match(String targetUserAgent, Match match); Match matchForDeviceId(byte[] deviceIdArray); Match matchForDeviceId(String deviceId); Match matchForDeviceId(ArrayList<Integer> profileIds); Match matchForDeviceId(byte[] deviceIdArray, Match match); Match matchForDeviceId(String deviceId, Match match); Match matchForDeviceId(ArrayList<Integer> profileIds, Match match); final Dataset dataSet; }### Answer: @Test public void testMemoryAndStreamSame () throws IOException { IndirectDataset cachedDataset = DatasetBuilder.file() .configureDefaultCaches() .build(Filename.LITE_PATTERN_V32); Provider cachedProvider = new Provider(cachedDataset, new LruCache(5000)); IndirectDataset unCachedDataset = DatasetBuilder.file() .build(Filename.LITE_PATTERN_V32); Provider unCachedProvider = new Provider(unCachedDataset); Dataset memoryDataset = MemoryFactory.create(Filename.LITE_PATTERN_V32); Provider memoryProvider = new Provider(memoryDataset); FileInputStream is = new FileInputStream(Filename.GOOD_USERAGENTS_FILE); BufferedReader source = new BufferedReader(new InputStreamReader(is)); String line; int count = 0; while ((line = source.readLine()) != null) { Match cachedMatch = cachedProvider.match(line); Match unCachedMatch = unCachedProvider.match(line); Match memoryMatch = memoryProvider.match(line); matchEquals(memoryMatch,cachedMatch); matchEquals(memoryMatch,unCachedMatch); count++; } logger.info("{} tests done", count); source.close(); cachedDataset.close(); unCachedDataset.close(); memoryDataset.close(); }
### Question: DynamicFilters { public ArrayList<Signature> filterBy(String propertyName, String propertyValue, ArrayList<Signature> listToFilter) throws IOException { if (propertyName.isEmpty() || propertyValue.isEmpty()) { throw new IllegalArgumentException("Property and Value can not be " + "empty or null."); } if (listToFilter == null) { listToFilter = signatures; } Property property = dataset.get(propertyName); if (property == null) { throw new IllegalArgumentException("Property you requested " + propertyName + " does not appear to exist in the current " + "data file."); } ArrayList<Signature> filterResults = new ArrayList<Signature>(); for (Signature sig : listToFilter) { Values vals = sig.getValues(property); if (vals.get(propertyValue) != null) { filterResults.add(sig); } } return filterResults; } DynamicFilters(); static void main(String[] args); void run(); ArrayList<Signature> filterBy(String propertyName, String propertyValue, ArrayList<Signature> listToFilter); static ArrayList<E> iterableToArrayList(Iterable<E> iter); void close(); }### Answer: @Test public void dynamicFilter() throws IOException { ArrayList<Signature> signatures; int signaturesOriginal = df.signatures.size(); signatures = df.filterBy("IsMobile", "True", null); int signaturesIsMobile = signatures.size(); signatures = df.filterBy("PlatformName", "Android", signatures); int signaturesPlatformname = signatures.size(); signatures = df.filterBy("BrowserName", "Chrome", signatures); int signaturesBrowserName = signatures.size(); assertTrue(signaturesOriginal >= signaturesIsMobile); assertTrue(signaturesIsMobile >= signaturesPlatformname); assertTrue(signaturesPlatformname >= signaturesBrowserName); for (Signature sig : signatures) { assertTrue(sig.getDeviceId() != null); } }
### Question: AllProfiles implements Closeable { public AllProfiles() throws IOException { provider = new Provider(StreamFactory.create( Shared.getLitePatternV32(), false)); hardwareComponent = provider.dataSet.getComponent("HardwarePlatform"); hardwareProperties = hardwareComponent.getProperties(); hardwareProfiles = hardwareComponent.getProfiles(); } AllProfiles(); void run(String outputFilename); static void main(String[] args); @Override void close(); public String outputFilePath; }### Answer: @Test public void testAllProfiles() throws Exception { assertEquals(outputFile.length(), 0); example.run(outputFile.getAbsolutePath()); assertNotEquals(outputFile.length(), 0); }
### Question: GettingStarted implements Closeable { public String detect(String userAgent) throws IOException { Match match = provider.match(userAgent); return match.getValues("IsMobile").toString(); } GettingStarted(); String detect(String userAgent); static void main(String[] args); @Override void close(); }### Answer: @Test public void testLiteGettingStartedMobileUA() throws IOException { String result = gs.detect(gs.mobileUserAgent); System.out.println("Mobile User-Agent: " + gs.mobileUserAgent); System.out.println("IsMobile: " + result); assertTrue(result.equals("True")); } @Test public void testLiteGettingStartedDesktopUA() throws IOException { String result = gs.detect(gs.desktopUserAgent); System.out.println("Desktop User-Agent: " + gs.desktopUserAgent); System.out.println("IsMobile: " + result); assertTrue(result.equals("False")); } @Test public void testLiteGettingStartedMediahubUA() throws IOException { String result = gs.detect(gs.mediaHubUserAgent); System.out.println("MediaHub User-Agent: " + gs.mediaHubUserAgent); System.out.println("IsMobile: " + result); assertTrue(result.equals("False")); }
### Question: OfflineProcessingExample implements Closeable { public void processCsv(String inputFileName, String outputFilename) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFileName)); try { FileWriter fileWriter = new FileWriter(outputFilename); try { Match match = provider.createMatch(); for (int i = 0; i < 20; i++) { String userAgentString = bufferedReader.readLine(); provider.match(userAgentString, match); Values isMobile = match.getValues("IsMobile"); Values platformName = match.getValues("PlatformName"); Values platformVersion = match.getValues("PlatformVersion"); fileWriter.append("\"") .append(userAgentString) .append("\", ") .append(getValueForDisplay(isMobile)) .append(", ") .append(getValueForDisplay(platformName)) .append(", ") .append(getValueForDisplay(platformVersion)) .append('\n') .flush(); } } finally { fileWriter.close(); } } finally { bufferedReader.close(); } } OfflineProcessingExample(); void processCsv(String inputFileName, String outputFilename); @Override void close(); static void main(String[] args); public String outputFilePath; }### Answer: @Test public void testProcessCsv() throws Exception { assertEquals(outputFile.length(), 0); example.processCsv(Shared.getGoodUserAgentsFile(), outputFile.getAbsolutePath()); assertNotEquals(outputFile.length(), 0); }
### Question: ContentSummary implements Writable { @Override @InterfaceAudience.Private public void write(DataOutput out) throws IOException { out.writeLong(length); out.writeLong(fileCount); out.writeLong(directoryCount); out.writeLong(quota); out.writeLong(spaceConsumed); out.writeLong(spaceQuota); } @Deprecated ContentSummary(); @Deprecated ContentSummary(long length, long fileCount, long directoryCount); @Deprecated ContentSummary( long length, long fileCount, long directoryCount, long quota, long spaceConsumed, long spaceQuota); private ContentSummary( long length, long fileCount, long directoryCount, long quota, long spaceConsumed, long spaceQuota, long typeConsumed[], long typeQuota[]); long getLength(); long getDirectoryCount(); long getFileCount(); long getQuota(); long getSpaceConsumed(); long getSpaceQuota(); long getTypeQuota(StorageType type); long getTypeConsumed(StorageType type); boolean isTypeQuotaSet(); boolean isTypeConsumedAvailable(); @Override @InterfaceAudience.Private void write(DataOutput out); @Override @InterfaceAudience.Private void readFields(DataInput in); static String getHeader(boolean qOption); static String[] getHeaderFields(); static String[] getQuotaHeaderFields(); @Override String toString(); String toString(boolean qOption); String toString(boolean qOption, boolean hOption); }### Answer: @Test public void testWrite() throws IOException { long length = 11111; long fileCount = 22222; long directoryCount = 33333; long quota = 44444; long spaceConsumed = 55555; long spaceQuota = 66666; ContentSummary contentSummary = new ContentSummary.Builder().length(length). fileCount(fileCount).directoryCount(directoryCount).quota(quota). spaceConsumed(spaceConsumed).spaceQuota(spaceQuota).build(); DataOutput out = mock(DataOutput.class); InOrder inOrder = inOrder(out); contentSummary.write(out); inOrder.verify(out).writeLong(length); inOrder.verify(out).writeLong(fileCount); inOrder.verify(out).writeLong(directoryCount); inOrder.verify(out).writeLong(quota); inOrder.verify(out).writeLong(spaceConsumed); inOrder.verify(out).writeLong(spaceQuota); }
### Question: ContentSummary implements Writable { @Override @InterfaceAudience.Private public void readFields(DataInput in) throws IOException { this.length = in.readLong(); this.fileCount = in.readLong(); this.directoryCount = in.readLong(); this.quota = in.readLong(); this.spaceConsumed = in.readLong(); this.spaceQuota = in.readLong(); } @Deprecated ContentSummary(); @Deprecated ContentSummary(long length, long fileCount, long directoryCount); @Deprecated ContentSummary( long length, long fileCount, long directoryCount, long quota, long spaceConsumed, long spaceQuota); private ContentSummary( long length, long fileCount, long directoryCount, long quota, long spaceConsumed, long spaceQuota, long typeConsumed[], long typeQuota[]); long getLength(); long getDirectoryCount(); long getFileCount(); long getQuota(); long getSpaceConsumed(); long getSpaceQuota(); long getTypeQuota(StorageType type); long getTypeConsumed(StorageType type); boolean isTypeQuotaSet(); boolean isTypeConsumedAvailable(); @Override @InterfaceAudience.Private void write(DataOutput out); @Override @InterfaceAudience.Private void readFields(DataInput in); static String getHeader(boolean qOption); static String[] getHeaderFields(); static String[] getQuotaHeaderFields(); @Override String toString(); String toString(boolean qOption); String toString(boolean qOption, boolean hOption); }### Answer: @Test public void testReadFields() throws IOException { long length = 11111; long fileCount = 22222; long directoryCount = 33333; long quota = 44444; long spaceConsumed = 55555; long spaceQuota = 66666; ContentSummary contentSummary = new ContentSummary.Builder().build(); DataInput in = mock(DataInput.class); when(in.readLong()).thenReturn(length).thenReturn(fileCount) .thenReturn(directoryCount).thenReturn(quota).thenReturn(spaceConsumed) .thenReturn(spaceQuota); contentSummary.readFields(in); assertEquals("getLength", length, contentSummary.getLength()); assertEquals("getFileCount", fileCount, contentSummary.getFileCount()); assertEquals("getDirectoryCount", directoryCount, contentSummary.getDirectoryCount()); assertEquals("getQuota", quota, contentSummary.getQuota()); assertEquals("getSpaceConsumed", spaceConsumed, contentSummary.getSpaceConsumed()); assertEquals("getSpaceQuota", spaceQuota, contentSummary.getSpaceQuota()); }
### Question: ContentSummary implements Writable { public static String getHeader(boolean qOption) { return qOption ? QUOTA_HEADER : HEADER; } @Deprecated ContentSummary(); @Deprecated ContentSummary(long length, long fileCount, long directoryCount); @Deprecated ContentSummary( long length, long fileCount, long directoryCount, long quota, long spaceConsumed, long spaceQuota); private ContentSummary( long length, long fileCount, long directoryCount, long quota, long spaceConsumed, long spaceQuota, long typeConsumed[], long typeQuota[]); long getLength(); long getDirectoryCount(); long getFileCount(); long getQuota(); long getSpaceConsumed(); long getSpaceQuota(); long getTypeQuota(StorageType type); long getTypeConsumed(StorageType type); boolean isTypeQuotaSet(); boolean isTypeConsumedAvailable(); @Override @InterfaceAudience.Private void write(DataOutput out); @Override @InterfaceAudience.Private void readFields(DataInput in); static String getHeader(boolean qOption); static String[] getHeaderFields(); static String[] getQuotaHeaderFields(); @Override String toString(); String toString(boolean qOption); String toString(boolean qOption, boolean hOption); }### Answer: @Test public void testGetHeaderWithQuota() { String header = " QUOTA REM_QUOTA SPACE_QUOTA " + "REM_SPACE_QUOTA DIR_COUNT FILE_COUNT CONTENT_SIZE "; assertEquals(header, ContentSummary.getHeader(true)); } @Test public void testGetHeaderNoQuota() { String header = " DIR_COUNT FILE_COUNT CONTENT_SIZE "; assertEquals(header, ContentSummary.getHeader(false)); }
### Question: DatanodeDescriptor extends DatanodeInfo { public Block[] getInvalidateBlocks(int maxblocks) { synchronized (invalidateBlocks) { Block[] deleteList = invalidateBlocks.pollToArray(new Block[Math.min( invalidateBlocks.size(), maxblocks)]); return deleteList.length == 0 ? null : deleteList; } } DatanodeDescriptor(DatanodeID nodeID); DatanodeDescriptor(DatanodeID nodeID, String networkLocation); int updateBlockReportContext(BlockReportContext context); void clearBlockReportContext(); CachedBlocksList getPendingCached(); CachedBlocksList getCached(); CachedBlocksList getPendingUncached(); @VisibleForTesting DatanodeStorageInfo getStorageInfo(String storageID); StorageReport[] getStorageReports(); void resetBlocks(); void clearBlockQueues(); int numBlocks(); void updateHeartbeat(StorageReport[] reports, long cacheCapacity, long cacheUsed, int xceiverCount, int volFailures, VolumeFailureSummary volumeFailureSummary); void updateHeartbeatState(StorageReport[] reports, long cacheCapacity, long cacheUsed, int xceiverCount, int volFailures, VolumeFailureSummary volumeFailureSummary); List<BlockTargetPair> getReplicationCommand(int maxTransfers); BlockInfoContiguousUnderConstruction[] getLeaseRecoveryCommand(int maxTransfers); Block[] getInvalidateBlocks(int maxblocks); long getRemaining(StorageType t, long minSize); int getBlocksScheduled(StorageType t); int getBlocksScheduled(); @Override int hashCode(); @Override boolean equals(Object obj); void setDisallowed(boolean flag); boolean isDisallowed(); int getVolumeFailures(); VolumeFailureSummary getVolumeFailureSummary(); @Override void updateRegInfo(DatanodeID nodeReg); long getBalancerBandwidth(); void setBalancerBandwidth(long bandwidth); @Override String dumpDatanode(); long getLastCachingDirectiveSentTimeMs(); void setLastCachingDirectiveSentTimeMs(long time); boolean checkBlockReportReceived(); static final Log LOG; static final DatanodeDescriptor[] EMPTY_ARRAY; final DecommissioningStatus decommissioningStatus; public boolean isAlive; public boolean needKeyUpdate; }### Answer: @Test public void testGetInvalidateBlocks() throws Exception { final int MAX_BLOCKS = 10; final int REMAINING_BLOCKS = 2; final int MAX_LIMIT = MAX_BLOCKS - REMAINING_BLOCKS; DatanodeDescriptor dd = DFSTestUtil.getLocalDatanodeDescriptor(); ArrayList<Block> blockList = new ArrayList<Block>(MAX_BLOCKS); for (int i=0; i<MAX_BLOCKS; i++) { blockList.add(new Block(i, 0, GenerationStamp.LAST_RESERVED_STAMP)); } dd.addBlocksToBeInvalidated(blockList); Block[] bc = dd.getInvalidateBlocks(MAX_LIMIT); assertEquals(bc.length, MAX_LIMIT); bc = dd.getInvalidateBlocks(MAX_LIMIT); assertEquals(bc.length, REMAINING_BLOCKS); }
### Question: CommonNodeLabelsManager extends AbstractService { @SuppressWarnings("unchecked") public void addToCluserNodeLabels(Set<String> labels) throws IOException { if (!nodeLabelsEnabled) { LOG.error(NODE_LABELS_NOT_ENABLED_ERR); throw new IOException(NODE_LABELS_NOT_ENABLED_ERR); } if (null == labels || labels.isEmpty()) { return; } Set<String> newLabels = new HashSet<String>(); labels = normalizeLabels(labels); for (String label : labels) { checkAndThrowLabelName(label); } for (String label : labels) { if (this.labelCollections.get(label) == null) { this.labelCollections.put(label, new NodeLabel(label)); newLabels.add(label); } } if (null != dispatcher && !newLabels.isEmpty()) { dispatcher.getEventHandler().handle( new StoreNewClusterNodeLabels(newLabels)); } LOG.info("Add labels: [" + StringUtils.join(labels.iterator(), ",") + "]"); } CommonNodeLabelsManager(); @SuppressWarnings("unchecked") void addToCluserNodeLabels(Set<String> labels); void addLabelsToNode(Map<NodeId, Set<String>> addedLabelsToNode); void removeFromClusterNodeLabels(Collection<String> labelsToRemove); void removeLabelsFromNode(Map<NodeId, Set<String>> removeLabelsFromNode); void replaceLabelsOnNode(Map<NodeId, Set<String>> replaceLabelsToNode); Map<NodeId, Set<String>> getNodeLabels(); Map<String, Set<NodeId>> getLabelsToNodes(); Map<String, Set<NodeId>> getLabelsToNodes(Set<String> labels); Set<String> getClusterNodeLabels(); void setInitNodeLabelStoreInProgress( boolean initNodeLabelStoreInProgress); static final Set<String> EMPTY_STRING_SET; static final String ANY; static final Set<String> ACCESS_ANY_LABEL_SET; static final int WILDCARD_PORT; @VisibleForTesting static final String NODE_LABELS_NOT_ENABLED_ERR; static final String NO_LABEL; }### Answer: @Test(timeout = 5000) public void testAddInvalidlabel() throws IOException { boolean caught = false; try { Set<String> set = new HashSet<String>(); set.add(null); mgr.addToCluserNodeLabels(set); } catch (IOException e) { caught = true; } Assert.assertTrue("null label should not add to repo", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of(CommonNodeLabelsManager.NO_LABEL)); } catch (IOException e) { caught = true; } Assert.assertTrue("empty label should not add to repo", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of("-?")); } catch (IOException e) { caught = true; } Assert.assertTrue("invalid label charactor should not add to repo", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of(StringUtils.repeat("c", 257))); } catch (IOException e) { caught = true; } Assert.assertTrue("too long label should not add to repo", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of("-aaabbb")); } catch (IOException e) { caught = true; } Assert.assertTrue("label cannot start with \"-\"", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of("_aaabbb")); } catch (IOException e) { caught = true; } Assert.assertTrue("label cannot start with \"_\"", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of("a^aabbb")); } catch (IOException e) { caught = true; } Assert.assertTrue("label cannot contains other chars like ^[] ...", caught); caught = false; try { mgr.addToCluserNodeLabels(ImmutableSet.of("aa[a]bbb")); } catch (IOException e) { caught = true; } Assert.assertTrue("label cannot contains other chars like ^[] ...", caught); }
### Question: LinuxContainerExecutor extends ContainerExecutor { @Override public void setConf(Configuration conf) { super.setConf(conf); resourcesHandler = ReflectionUtils.newInstance( conf.getClass(YarnConfiguration.NM_LINUX_CONTAINER_RESOURCES_HANDLER, DefaultLCEResourcesHandler.class, LCEResourcesHandler.class), conf); resourcesHandler.setConf(conf); if (conf.get(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY) != null) { containerSchedPriorityIsSet = true; containerSchedPriorityAdjustment = conf .getInt(YarnConfiguration.NM_CONTAINER_EXECUTOR_SCHED_PRIORITY, YarnConfiguration.DEFAULT_NM_CONTAINER_EXECUTOR_SCHED_PRIORITY); } nonsecureLocalUser = conf.get( YarnConfiguration.NM_NONSECURE_MODE_LOCAL_USER_KEY, YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER); nonsecureLocalUserPattern = Pattern.compile( conf.get(YarnConfiguration.NM_NONSECURE_MODE_USER_PATTERN_KEY, YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_USER_PATTERN)); containerLimitUsers = conf.getBoolean( YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS, YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LIMIT_USERS); if (!containerLimitUsers) { LOG.warn(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS + ": impersonation without authentication enabled"); } } LinuxContainerExecutor(); @VisibleForTesting LinuxContainerExecutor(LinuxContainerRuntime linuxContainerRuntime); @Override void setConf(Configuration conf); @Override void init(); @Override void startLocalizer(LocalizerStartContext ctx); @Override int prepareContainer(ContainerStartContext ctx); @VisibleForTesting void buildMainArgs(List<String> command, String user, String appId, String locId, InetSocketAddress nmAddr, List<String> localDirs); @Override int launchContainer(ContainerStartContext ctx); @Override int reacquireContainer(ContainerReacquisitionContext ctx); @Override boolean signalContainer(ContainerSignalContext ctx); @Override void deleteAsUser(DeletionAsUserContext ctx); @Override boolean isContainerAlive(ContainerLivenessContext ctx); void mountCgroups(List<String> cgroupKVs, String hierarchy); }### Answer: @Test public void testNonSecureRunAsSubmitter() throws Exception { Assume.assumeTrue(shouldRun()); Assume.assumeFalse(UserGroupInformation.isSecurityEnabled()); String expectedRunAsUser = appSubmitter; conf.set(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS, "false"); exec.setConf(conf); File touchFile = new File(workSpace, "touch-file"); int ret = runAndBlock("touch", touchFile.getAbsolutePath()); assertEquals(0, ret); FileStatus fileStatus = FileContext.getLocalFSFileContext().getFileStatus( new Path(touchFile.getAbsolutePath())); assertEquals(expectedRunAsUser, fileStatus.getOwner()); cleanupAppFiles(expectedRunAsUser); conf.unset(YarnConfiguration.NM_NONSECURE_MODE_LIMIT_USERS); exec.setConf(conf); }
### Question: LinuxContainerExecutor extends ContainerExecutor { @Override public boolean signalContainer(ContainerSignalContext ctx) throws IOException { Container container = ctx.getContainer(); String user = ctx.getUser(); String pid = ctx.getPid(); Signal signal = ctx.getSignal(); verifyUsernamePattern(user); String runAsUser = getRunAsUser(user); ContainerRuntimeContext runtimeContext = new ContainerRuntimeContext .Builder(container) .setExecutionAttribute(RUN_AS_USER, runAsUser) .setExecutionAttribute(USER, user) .setExecutionAttribute(PID, pid) .setExecutionAttribute(SIGNAL, signal) .build(); try { linuxContainerRuntime.signalContainer(runtimeContext); } catch (ContainerExecutionException e) { int retCode = e.getExitCode(); if (retCode == PrivilegedOperation.ResultCode.INVALID_CONTAINER_PID .getValue()) { return false; } LOG.warn("Error in signalling container " + pid + " with " + signal + "; exit = " + retCode, e); logOutput(e.getOutput()); throw new IOException("Problem signalling container " + pid + " with " + signal + "; output: " + e.getOutput() + " and exitCode: " + retCode, e); } return true; } LinuxContainerExecutor(); @VisibleForTesting LinuxContainerExecutor(LinuxContainerRuntime linuxContainerRuntime); @Override void setConf(Configuration conf); @Override void init(); @Override void startLocalizer(LocalizerStartContext ctx); @Override int prepareContainer(ContainerStartContext ctx); @VisibleForTesting void buildMainArgs(List<String> command, String user, String appId, String locId, InetSocketAddress nmAddr, List<String> localDirs); @Override int launchContainer(ContainerStartContext ctx); @Override int reacquireContainer(ContainerReacquisitionContext ctx); @Override boolean signalContainer(ContainerSignalContext ctx); @Override void deleteAsUser(DeletionAsUserContext ctx); @Override boolean isContainerAlive(ContainerLivenessContext ctx); void mountCgroups(List<String> cgroupKVs, String hierarchy); }### Answer: @Test public void testContainerKill() throws Exception { Assume.assumeTrue(shouldRun()); final ContainerId sleepId = getNextContainerId(); Thread t = new Thread() { public void run() { try { runAndBlock(sleepId, "sleep", "100"); } catch (IOException e) { LOG.warn("Caught exception while running sleep", e); } }; }; t.setDaemon(true); t.start(); assertTrue(t.isAlive()); String pid = null; int count = 10; while ((pid = exec.getProcessId(sleepId)) == null && count > 0) { LOG.info("Sleeping for 200 ms before checking for pid "); Thread.sleep(200); count--; } assertNotNull(pid); LOG.info("Going to killing the process."); exec.signalContainer(new ContainerSignalContext.Builder() .setUser(appSubmitter) .setPid(pid) .setSignal(Signal.TERM) .build()); LOG.info("sleeping for 100ms to let the sleep be killed"); Thread.sleep(100); assertFalse(t.isAlive()); cleanupAppFiles(appSubmitter); }
### Question: LinuxContainerExecutor extends ContainerExecutor { public void mountCgroups(List<String> cgroupKVs, String hierarchy) throws IOException { try { PrivilegedOperation mountCGroupsOp = new PrivilegedOperation( PrivilegedOperation.OperationType.MOUNT_CGROUPS, hierarchy); Configuration conf = super.getConf(); mountCGroupsOp.appendArgs(cgroupKVs); PrivilegedOperationExecutor privilegedOperationExecutor = PrivilegedOperationExecutor.getInstance(conf); privilegedOperationExecutor.executePrivilegedOperation(mountCGroupsOp, false); } catch (PrivilegedOperationException e) { int exitCode = e.getExitCode(); LOG.warn("Exception in LinuxContainerExecutor mountCgroups ", e); throw new IOException("Problem mounting cgroups " + cgroupKVs + "; exit code = " + exitCode + " and output: " + e.getOutput(), e); } } LinuxContainerExecutor(); @VisibleForTesting LinuxContainerExecutor(LinuxContainerRuntime linuxContainerRuntime); @Override void setConf(Configuration conf); @Override void init(); @Override void startLocalizer(LocalizerStartContext ctx); @Override int prepareContainer(ContainerStartContext ctx); @VisibleForTesting void buildMainArgs(List<String> command, String user, String appId, String locId, InetSocketAddress nmAddr, List<String> localDirs); @Override int launchContainer(ContainerStartContext ctx); @Override int reacquireContainer(ContainerReacquisitionContext ctx); @Override boolean signalContainer(ContainerSignalContext ctx); @Override void deleteAsUser(DeletionAsUserContext ctx); @Override boolean isContainerAlive(ContainerLivenessContext ctx); void mountCgroups(List<String> cgroupKVs, String hierarchy); }### Answer: @Test public void testCGroups() throws Exception { Assume.assumeTrue(shouldRun()); String cgroupsMount = System.getProperty("cgroups.mount"); Assume.assumeTrue((cgroupsMount != null) && !cgroupsMount.isEmpty()); assertTrue("Cgroups mount point does not exist", new File( cgroupsMount).exists()); List<String> cgroupKVs = new ArrayList<>(); String hierarchy = "hadoop-yarn"; String[] controllers = { "cpu", "net_cls" }; for (String controller : controllers) { cgroupKVs.add(controller + "=" + cgroupsMount + "/" + controller); assertTrue(new File(cgroupsMount, controller).exists()); } try { exec.mountCgroups(cgroupKVs, hierarchy); for (String controller : controllers) { assertTrue(controller + " cgroup not mounted", new File( cgroupsMount + "/" + controller + "/tasks").exists()); assertTrue(controller + " cgroup hierarchy not created", new File(cgroupsMount + "/" + controller + "/" + hierarchy).exists()); assertTrue(controller + " cgroup hierarchy created incorrectly", new File(cgroupsMount + "/" + controller + "/" + hierarchy + "/tasks").exists()); } } catch (IOException ie) { fail("Couldn't mount cgroups " + ie.toString()); throw ie; } }
### Question: DirectoryCollection { synchronized boolean createNonExistentDirs(FileContext localFs, FsPermission perm) { boolean failed = false; for (final String dir : localDirs) { try { createDir(localFs, new Path(dir), perm); } catch (IOException e) { LOG.warn("Unable to create directory " + dir + " error " + e.getMessage() + ", removing from the list of valid directories."); localDirs.remove(dir); errorDirs.add(dir); numFailures++; failed = true; } } return !failed; } DirectoryCollection(String[] dirs); DirectoryCollection(String[] dirs, float utilizationPercentageCutOff); DirectoryCollection(String[] dirs, long utilizationSpaceCutOff); DirectoryCollection(String[] dirs, float utilizationPercentageCutOff, long utilizationSpaceCutOff); float getDiskUtilizationPercentageCutoff(); void setDiskUtilizationPercentageCutoff( float diskUtilizationPercentageCutoff); long getDiskUtilizationSpaceCutoff(); void setDiskUtilizationSpaceCutoff(long diskUtilizationSpaceCutoff); int getGoodDirsDiskUtilizationPercentage(); }### Answer: @Test public void testCreateDirectories() throws IOException { conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "077"); String dirA = new File(testDir, "dirA").getPath(); String dirB = new File(dirA, "dirB").getPath(); String dirC = new File(testDir, "dirC").getPath(); Path pathC = new Path(dirC); FsPermission permDirC = new FsPermission((short)0710); localFs.mkdir(pathC, null, true); localFs.setPermission(pathC, permDirC); String[] dirs = { dirA, dirB, dirC }; DirectoryCollection dc = new DirectoryCollection(dirs, conf.getFloat( YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE, YarnConfiguration.DEFAULT_NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE)); FsPermission defaultPerm = FsPermission.getDefault() .applyUMask(new FsPermission((short)FsPermission.DEFAULT_UMASK)); boolean createResult = dc.createNonExistentDirs(localFs, defaultPerm); Assert.assertTrue(createResult); FileStatus status = localFs.getFileStatus(new Path(dirA)); Assert.assertEquals("local dir parent not created with proper permissions", defaultPerm, status.getPermission()); status = localFs.getFileStatus(new Path(dirB)); Assert.assertEquals("local dir not created with proper permissions", defaultPerm, status.getPermission()); status = localFs.getFileStatus(pathC); Assert.assertEquals("existing local directory permissions modified", permDirC, status.getPermission()); }
### Question: TrafficControlBandwidthHandlerImpl implements OutboundBandwidthResourceHandler { @Override public List<PrivilegedOperation> bootstrap(Configuration configuration) throws ResourceHandlerException { conf = configuration; cGroupsHandler .mountCGroupController(CGroupsHandler.CGroupController.NET_CLS); device = conf.get(YarnConfiguration.NM_NETWORK_RESOURCE_INTERFACE, YarnConfiguration.DEFAULT_NM_NETWORK_RESOURCE_INTERFACE); strictMode = configuration.getBoolean(YarnConfiguration .NM_LINUX_CONTAINER_CGROUPS_STRICT_RESOURCE_USAGE, YarnConfiguration .DEFAULT_NM_LINUX_CONTAINER_CGROUPS_STRICT_RESOURCE_USAGE); rootBandwidthMbit = conf.getInt(YarnConfiguration .NM_NETWORK_RESOURCE_OUTBOUND_BANDWIDTH_MBIT, YarnConfiguration .DEFAULT_NM_NETWORK_RESOURCE_OUTBOUND_BANDWIDTH_MBIT); yarnBandwidthMbit = conf.getInt(YarnConfiguration .NM_NETWORK_RESOURCE_OUTBOUND_BANDWIDTH_YARN_MBIT, rootBandwidthMbit); int MAX_CONTAINER_COUNT = conf.getInt(YarnConfiguration .NM_NETWORK_RESOURCE_OUTBOUND_MAX_CONTAINER_COUNT, YarnConfiguration .DEFAULT_NM_NETWORK_RESOURCE_OUTBOUND_MAX_CONTAINER_COUNT); containerBandwidthMbit = (int) Math.ceil((double) yarnBandwidthMbit / MAX_CONTAINER_COUNT); StringBuffer logLine = new StringBuffer("strict mode is set to :") .append(strictMode).append(System.lineSeparator()); if (strictMode) { logLine.append("container bandwidth will be capped to soft limit.") .append(System.lineSeparator()); } else { logLine.append( "containers will be allowed to use spare YARN bandwidth.") .append(System.lineSeparator()); } logLine .append("containerBandwidthMbit soft limit (in mbit/sec) is set to : ") .append(containerBandwidthMbit); LOG.info(logLine); trafficController.bootstrap(device, rootBandwidthMbit, yarnBandwidthMbit, containerBandwidthMbit, strictMode); return null; } TrafficControlBandwidthHandlerImpl(PrivilegedOperationExecutor privilegedOperationExecutor, CGroupsHandler cGroupsHandler, TrafficController trafficController); @Override List<PrivilegedOperation> bootstrap(Configuration configuration); @Override List<PrivilegedOperation> preStart(Container container); @Override List<PrivilegedOperation> reacquireContainer(ContainerId containerId); Map<ContainerId, Integer> getBytesSentPerContainer(); @Override List<PrivilegedOperation> postComplete(ContainerId containerId); @Override List<PrivilegedOperation> teardown(); }### Answer: @Test public void testBootstrap() { TrafficControlBandwidthHandlerImpl handlerImpl = new TrafficControlBandwidthHandlerImpl(privilegedOperationExecutorMock, cGroupsHandlerMock, trafficControllerMock); try { handlerImpl.bootstrap(conf); verify(cGroupsHandlerMock).mountCGroupController( eq(CGroupsHandler.CGroupController.NET_CLS)); verifyNoMoreInteractions(cGroupsHandlerMock); verify(trafficControllerMock).bootstrap(eq(device), eq(ROOT_BANDWIDTH_MBIT), eq(YARN_BANDWIDTH_MBIT), eq(CONTAINER_BANDWIDTH_MBIT), eq(false)); verifyNoMoreInteractions(trafficControllerMock); } catch (ResourceHandlerException e) { LOG.error("Unexpected exception: " + e); Assert.fail("Caught unexpected ResourceHandlerException!"); } } @Test public void testLifeCycle() { TrafficController trafficControllerSpy = spy(new TrafficController(conf, privilegedOperationExecutorMock)); TrafficControlBandwidthHandlerImpl handlerImpl = new TrafficControlBandwidthHandlerImpl(privilegedOperationExecutorMock, cGroupsHandlerMock, trafficControllerSpy); try { handlerImpl.bootstrap(conf); testPreStart(trafficControllerSpy, handlerImpl); testPostComplete(trafficControllerSpy, handlerImpl); } catch (ResourceHandlerException e) { LOG.error("Unexpected exception: " + e); Assert.fail("Caught unexpected ResourceHandlerException!"); } }
### Question: TrafficController { public int getClassIdFromFileContents(String input) { String classIdStr = String.format("%08x", Integer.parseInt(input)); if (LOG.isDebugEnabled()) { LOG.debug("ClassId hex string : " + classIdStr); } return Integer.parseInt(classIdStr.substring(4)); } TrafficController(Configuration conf, PrivilegedOperationExecutor exec); void bootstrap(String device, int rootBandwidthMbit, int yarnBandwidthMbit, int containerBandwidthMbit, boolean strictMode); Map<Integer, Integer> readStats(); int getNextClassId(); void releaseClassId(int classId); String getStringForNetClsClassId(int classId); int getClassIdFromFileContents(String input); }### Answer: @Test public void testClassIdFileContentParsing() { conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, false); TrafficController trafficController = new TrafficController(conf, privilegedOperationExecutorMock); int parsedClassId = trafficController.getClassIdFromFileContents (TEST_CLASS_ID_DECIMAL_STR); Assert.assertEquals(TEST_CLASS_ID, parsedClassId); }
### Question: CGroupsHandlerImpl implements CGroupsHandler { @Override public void mountCGroupController(CGroupController controller) throws ResourceHandlerException { if (!enableCGroupMount) { LOG.warn("CGroup mounting is disabled - ignoring mount request for: " + controller.getName()); return; } String path = getControllerPath(controller); if (path == null) { try { rwLock.writeLock().lock(); String hierarchy = cGroupPrefix; StringBuffer controllerPath = new StringBuffer() .append(cGroupMountPath).append('/').append(controller.getName()); StringBuffer cGroupKV = new StringBuffer() .append(controller.getName()).append('=').append(controllerPath); PrivilegedOperation.OperationType opType = PrivilegedOperation .OperationType.MOUNT_CGROUPS; PrivilegedOperation op = new PrivilegedOperation(opType); op.appendArgs(hierarchy, cGroupKV.toString()); LOG.info("Mounting controller " + controller.getName() + " at " + controllerPath); privilegedOperationExecutor.executePrivilegedOperation(op, false); controllerPaths.put(controller, controllerPath.toString()); return; } catch (PrivilegedOperationException e) { LOG.error("Failed to mount controller: " + controller.getName()); throw new ResourceHandlerException("Failed to mount controller: " + controller.getName()); } finally { rwLock.writeLock().unlock(); } } else { LOG.info("CGroup controller already mounted at: " + path); return; } } CGroupsHandlerImpl(Configuration conf, PrivilegedOperationExecutor privilegedOperationExecutor); @Override void mountCGroupController(CGroupController controller); @Override String getRelativePathForCGroup(String cGroupId); @Override String getPathForCGroup(CGroupController controller, String cGroupId); @Override String getPathForCGroupTasks(CGroupController controller, String cGroupId); @Override String getPathForCGroupParam(CGroupController controller, String cGroupId, String param); @Override String createCGroup(CGroupController controller, String cGroupId); @Override void deleteCGroup(CGroupController controller, String cGroupId); @Override void updateCGroupParam(CGroupController controller, String cGroupId, String param, String value); @Override String getCGroupParam(CGroupController controller, String cGroupId, String param); }### Answer: @Test public void testMountController() { CGroupsHandler cGroupsHandler = null; verifyZeroInteractions(privilegedOperationExecutorMock); try { cGroupsHandler = new CGroupsHandlerImpl(conf, privilegedOperationExecutorMock); PrivilegedOperation expectedOp = new PrivilegedOperation (PrivilegedOperation.OperationType.MOUNT_CGROUPS); StringBuffer controllerKV = new StringBuffer(controller.getName()) .append('=').append(tmpPath).append('/').append(controller.getName()); expectedOp.appendArgs(hierarchy, controllerKV.toString()); cGroupsHandler.mountCGroupController(controller); try { ArgumentCaptor<PrivilegedOperation> opCaptor = ArgumentCaptor.forClass (PrivilegedOperation.class); verify(privilegedOperationExecutorMock) .executePrivilegedOperation(opCaptor.capture(), eq(false)); Assert.assertEquals(expectedOp, opCaptor.getValue()); verifyNoMoreInteractions(privilegedOperationExecutorMock); cGroupsHandler.mountCGroupController(controller); verifyNoMoreInteractions(privilegedOperationExecutorMock); } catch (PrivilegedOperationException e) { LOG.error("Caught exception: " + e); Assert.assertTrue("Unexpected PrivilegedOperationException from mock!", false); } } catch (ResourceHandlerException e) { LOG.error("Caught exception: " + e); Assert.assertTrue("Unexpected ResourceHandler Exception!", false); } }
### Question: DockerStopCommand extends DockerCommand { public DockerStopCommand setGracePeriod(int value) { super.addCommandArguments("--time=" + Integer.toString(value)); return this; } DockerStopCommand(String containerName); DockerStopCommand setGracePeriod(int value); }### Answer: @Test public void testSetGracePeriod() throws Exception { dockerStopCommand.setGracePeriod(GRACE_PERIOD); assertEquals("stop foo --time=10", dockerStopCommand.getCommandWithArguments()); }
### Question: DockerInspectCommand extends DockerCommand { public DockerInspectCommand getContainerStatus() { super.addCommandArguments("--format='{{.State.Status}}'"); super.addCommandArguments(containerName); return this; } DockerInspectCommand(String containerName); DockerInspectCommand getContainerStatus(); }### Answer: @Test public void testGetContainerStatus() throws Exception { dockerInspectCommand.getContainerStatus(); assertEquals("inspect --format='{{.State.Status}}' foo", dockerInspectCommand.getCommandWithArguments()); }
### Question: OwnLocalResources { public static Set<String> getLocalResourcesAllTags(){ Set<String> all = new HashSet<>(); all.add(LR_TAG_CENTOS6); all.add(LR_TAG_CENTOS7); all.add(LR_TAG_MACOS10); return all; } OwnLocalResources(String thisNodeTag); OwnLocalResources(); static Set<String> getLocalResourcesAllTags(); static String getThisLocalResourceTag(); Pair<String,Path> splitTagAndBasename(Path path); Map<Path,List<String>> filterLocalResources(Map<Path,List<String>> originLocalResources); static final String LR_PREFIX; static final String LR_TAG_CENTOS6; static final String LR_TAG_CENTOS7; static final String LR_TAG_MACOS10; static final String LR_TAG_DELIM; }### Answer: @Test public void testGetLocalResourcesAllTags() throws Exception { Set<String> all = OwnLocalResources.getLocalResourcesAllTags(); assertTrue(all.contains("centos6")); assertTrue(all.contains("centos7")); assertTrue(all.contains("macos10")); }
### Question: OwnLocalResources { public Pair<String,Path> splitTagAndBasename(Path path){ String name = path.getName(); Path parent = path.getParent(); if(name.startsWith(LR_PREFIX) == false){ return null; } name = name.substring(LR_PREFIX.length()); int underscore = name.indexOf(LR_TAG_DELIM); if(underscore == -1){ return null; } String tag = name.substring(0, underscore); String basename = name.substring(underscore + 1); if(LR_ALL_TAGS.contains(tag) == false){ return null; } return new Pair<>(tag, new Path(parent, basename)); } OwnLocalResources(String thisNodeTag); OwnLocalResources(); static Set<String> getLocalResourcesAllTags(); static String getThisLocalResourceTag(); Pair<String,Path> splitTagAndBasename(Path path); Map<Path,List<String>> filterLocalResources(Map<Path,List<String>> originLocalResources); static final String LR_PREFIX; static final String LR_TAG_CENTOS6; static final String LR_TAG_CENTOS7; static final String LR_TAG_MACOS10; static final String LR_TAG_DELIM; }### Answer: @Test public void testSplitTagAndBasename() throws Exception { OwnLocalResources olr = new OwnLocalResources(); Pair<String,Path> pair = olr.splitTagAndBasename(new Path("hello/_native_centos7_liba.so")); assertEquals("centos7", pair.getFirst()); assertEquals("hello/liba.so", pair.getSecond().toString()); pair = olr.splitTagAndBasename(new Path("hello/_native_centos6_liba.so")); assertEquals("centos6", pair.getFirst()); assertEquals("hello/liba.so", pair.getSecond().toString()); pair = olr.splitTagAndBasename(new Path("a/b/c/d/_native_centos6_liba.so")); assertEquals("centos6", pair.getFirst()); assertEquals("a/b/c/d/liba.so", pair.getSecond().toString()); pair = olr.splitTagAndBasename(new Path("_native_centos6_liba.so")); assertEquals("centos6", pair.getFirst()); assertEquals("liba.so", pair.getSecond().toString()); pair = olr.splitTagAndBasename(new Path("_centos6_liba.so")); assertEquals(null, pair); pair = olr.splitTagAndBasename(new Path("_native_liba.so")); assertEquals(null, pair); pair = olr.splitTagAndBasename(new Path("_native_CENTOS7_liba.so")); assertEquals(null, pair); }
### Question: ContainerLaunch implements Callable<Integer> { @VisibleForTesting public static String expandEnvironment(String var, Path containerLogDir) { var = var.replace(ApplicationConstants.LOG_DIR_EXPANSION_VAR, containerLogDir.toString()); var = var.replace(ApplicationConstants.CLASS_PATH_SEPARATOR, File.pathSeparator); if (Shell.WINDOWS) { var = var.replaceAll("(\\{\\{)|(\\}\\})", "%"); } else { var = var.replace(ApplicationConstants.PARAMETER_EXPANSION_LEFT, "$"); var = var.replace(ApplicationConstants.PARAMETER_EXPANSION_RIGHT, ""); } return var; } ContainerLaunch(Context context, Configuration configuration, Dispatcher dispatcher, ContainerExecutor exec, Application app, Container container, LocalDirsHandlerService dirsHandler, ContainerManagerImpl containerManager); @VisibleForTesting static String expandEnvironment(String var, Path containerLogDir); @Override @SuppressWarnings("unchecked") // dispatcher not typed Integer call(); @SuppressWarnings("unchecked") // dispatcher not typed void cleanupContainer(); static String getRelativeContainerLogDir(String appIdStr, String containerIdStr); void sanitizeEnv(Map<String, String> environment, Path pwd, List<Path> appDirs, List<String> userLocalDirs, List<String> containerLogDirs, Map<Path, List<String>> resources, Path nmPrivateClasspathJarDir); static String getExitCodeFile(String pidFile); static final String CONTAINER_SCRIPT; static final String FINAL_CONTAINER_TOKENS_FILE; }### Answer: @Test(timeout = 10000) public void testEnvExpansion() throws IOException { Path logPath = new Path("/nm/container/logs"); String input = Apps.crossPlatformify("HADOOP_HOME") + "/share/hadoop/common/*" + ApplicationConstants.CLASS_PATH_SEPARATOR + Apps.crossPlatformify("HADOOP_HOME") + "/share/hadoop/common/lib/*" + ApplicationConstants.CLASS_PATH_SEPARATOR + Apps.crossPlatformify("HADOOP_LOG_HOME") + ApplicationConstants.LOG_DIR_EXPANSION_VAR; String res = ContainerLaunch.expandEnvironment(input, logPath); if (Shell.WINDOWS) { Assert.assertEquals("%HADOOP_HOME%/share/hadoop/common/*;" + "%HADOOP_HOME%/share/hadoop/common/lib/*;" + "%HADOOP_LOG_HOME%/nm/container/logs", res); } else { Assert.assertEquals("$HADOOP_HOME/share/hadoop/common/*:" + "$HADOOP_HOME/share/hadoop/common/lib/*:" + "$HADOOP_LOG_HOME/nm/container/logs", res); } System.out.println(res); }
### Question: ProportionalCapacityPreemptionPolicy implements SchedulingEditPolicy { @VisibleForTesting static void sortContainers(List<RMContainer> containers){ Collections.sort(containers, new Comparator<RMContainer>() { @Override public int compare(RMContainer a, RMContainer b) { Comparator<Priority> c = new org.apache.hadoop.yarn.server .resourcemanager.resource.Priority.Comparator(); int priorityComp = c.compare(b.getContainer().getPriority(), a.getContainer().getPriority()); if (priorityComp != 0) { return priorityComp; } return b.getContainerId().compareTo(a.getContainerId()); } }); } ProportionalCapacityPreemptionPolicy(); ProportionalCapacityPreemptionPolicy(Configuration config, EventHandler<ContainerPreemptEvent> dispatcher, CapacityScheduler scheduler); ProportionalCapacityPreemptionPolicy(Configuration config, EventHandler<ContainerPreemptEvent> dispatcher, CapacityScheduler scheduler, Clock clock); void init(Configuration config, EventHandler<ContainerPreemptEvent> disp, PreemptableResourceScheduler sched); @VisibleForTesting ResourceCalculator getResourceCalculator(); @Override void editSchedule(); void setNodeLabels(Map<NodeId, Set<String>> nodelabels); @Override long getMonitoringInterval(); @Override String getPolicyName(); static final String OBSERVE_ONLY; static final String MONITORING_INTERVAL; static final String WAIT_TIME_BEFORE_KILL; static final String TOTAL_PREEMPTION_PER_ROUND; static final String MAX_IGNORED_OVER_CAPACITY; static final String NATURAL_TERMINATION_FACTOR; public EventHandler<ContainerPreemptEvent> dispatcher; }### Answer: @Test public void testContainerOrdering(){ List<RMContainer> containers = new ArrayList<RMContainer>(); ApplicationAttemptId appAttId = ApplicationAttemptId.newInstance( ApplicationId.newInstance(TS, 10), 0); RMContainer rm1 = mockContainer(appAttId, 5, mock(Resource.class), 3); RMContainer rm2 = mockContainer(appAttId, 3, mock(Resource.class), 3); RMContainer rm3 = mockContainer(appAttId, 2, mock(Resource.class), 2); RMContainer rm4 = mockContainer(appAttId, 1, mock(Resource.class), 2); RMContainer rm5 = mockContainer(appAttId, 4, mock(Resource.class), 1); containers.add(rm3); containers.add(rm2); containers.add(rm1); containers.add(rm5); containers.add(rm4); ProportionalCapacityPreemptionPolicy.sortContainers(containers); assert containers.get(0).equals(rm1); assert containers.get(1).equals(rm2); assert containers.get(2).equals(rm3); assert containers.get(3).equals(rm4); assert containers.get(4).equals(rm5); }
### Question: FifoScheduler extends AbstractYarnScheduler<FiCaSchedulerApp, FiCaSchedulerNode> implements Configurable { @Override public QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive) { return DEFAULT_QUEUE.getQueueInfo(false, false); } FifoScheduler(); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override synchronized void setConf(Configuration conf); @Override synchronized Configuration getConf(); @Override int getNumClusterNodes(); @Override synchronized void setRMContext(RMContext rmContext); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override Allocation allocate( ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); @VisibleForTesting synchronized void addApplication(ApplicationId applicationId, String queue, String user, boolean isAppRecovering); @VisibleForTesting synchronized void addApplicationAttempt(ApplicationAttemptId appAttemptId, boolean transferStateFromPreviousAttempt, boolean isAttemptRecovering); @Override void handle(SchedulerEvent event); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override ResourceCalculator getResourceCalculator(); @Override void recover(RMState state); @Override RMContainer getRMContainer(ContainerId containerId); @Override QueueMetrics getRootQueueMetrics(); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); @Override synchronized List<ApplicationAttemptId> getAppsInQueue(String queueName); Resource getUsedResource(); }### Answer: @Test(timeout=5000) public void testFifoSchedulerCapacityWhenNoNMs() { FifoScheduler scheduler = new FifoScheduler(); QueueInfo queueInfo = scheduler.getQueueInfo(null, false, false); Assert.assertEquals(0.0f, queueInfo.getCurrentCapacity(), 0.0f); }
### Question: FifoScheduler extends AbstractYarnScheduler<FiCaSchedulerApp, FiCaSchedulerNode> implements Configurable { @Override public synchronized List<ApplicationAttemptId> getAppsInQueue(String queueName) { if (queueName.equals(DEFAULT_QUEUE.getQueueName())) { List<ApplicationAttemptId> attempts = new ArrayList<ApplicationAttemptId>(applications.size()); for (SchedulerApplication<FiCaSchedulerApp> app : applications.values()) { attempts.add(app.getCurrentAppAttempt().getApplicationAttemptId()); } return attempts; } else { return null; } } FifoScheduler(); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override synchronized void setConf(Configuration conf); @Override synchronized Configuration getConf(); @Override int getNumClusterNodes(); @Override synchronized void setRMContext(RMContext rmContext); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @Override Allocation allocate( ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); @VisibleForTesting synchronized void addApplication(ApplicationId applicationId, String queue, String user, boolean isAppRecovering); @VisibleForTesting synchronized void addApplicationAttempt(ApplicationAttemptId appAttemptId, boolean transferStateFromPreviousAttempt, boolean isAttemptRecovering); @Override void handle(SchedulerEvent event); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override ResourceCalculator getResourceCalculator(); @Override void recover(RMState state); @Override RMContainer getRMContainer(ContainerId containerId); @Override QueueMetrics getRootQueueMetrics(); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); @Override synchronized List<ApplicationAttemptId> getAppsInQueue(String queueName); Resource getUsedResource(); }### Answer: @Test public void testGetAppsInQueue() throws Exception { Application application_0 = new Application("user_0", resourceManager); application_0.submit(); Application application_1 = new Application("user_0", resourceManager); application_1.submit(); ResourceScheduler scheduler = resourceManager.getResourceScheduler(); List<ApplicationAttemptId> appsInDefault = scheduler.getAppsInQueue("default"); assertTrue(appsInDefault.contains(application_0.getApplicationAttemptId())); assertTrue(appsInDefault.contains(application_1.getApplicationAttemptId())); assertEquals(2, appsInDefault.size()); Assert.assertNull(scheduler.getAppsInQueue("someotherqueue")); }
### Question: FairScheduler extends AbstractYarnScheduler<FSAppAttempt, FSSchedulerNode> { @Override public void serviceInit(Configuration conf) throws Exception { initScheduler(conf); super.serviceInit(conf); } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); synchronized RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized ResourceWeights getAppWeight(FSAppAttempt app); Resource getIncrementResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); long getNodeLocalityDelayMs(); long getRackLocalityDelayMs(); boolean isContinuousSchedulingEnabled(); synchronized int getContinuousSchedulingSleepMs(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); FSAppAttempt getSchedulerApp(ApplicationAttemptId appAttemptId); @Override ResourceCalculator getResourceCalculator(); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); synchronized void setRMContext(RMContext rmContext); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); AllocationConfiguration getAllocationConfiguration(); @Override List<ApplicationAttemptId> getAppsInQueue(String queueName); @Override synchronized String moveApplication(ApplicationId appId, String queueName); @Override synchronized void updateNodeResource(RMNode nm, ResourceOption resourceOption); @Override EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes(); @Override Set<String> getPlanQueues(); @Override void setEntitlement(String queueName, QueueEntitlement entitlement); @Override void removeQueue(String queueName); static final Resource CONTAINER_RESERVED; }### Answer: @Test (timeout = 30000) public void testConfValidation() throws Exception { scheduler = new FairScheduler(); Configuration conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 2048); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 1024); try { scheduler.serviceInit(conf); fail("Exception is expected because the min memory allocation is" + " larger than the max memory allocation."); } catch (YarnRuntimeException e) { assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler memory")); } conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_VCORES, 2); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_VCORES, 1); try { scheduler.serviceInit(conf); fail("Exception is expected because the min vcores allocation is" + " larger than the max vcores allocation."); } catch (YarnRuntimeException e) { assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler vcores")); } conf = new YarnConfiguration(); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_GCORES, 2); conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_GCORES, 1); try { scheduler.serviceInit(conf); fail("Exception is expected because the min gcores allocation is" + " larger than the max gcores allocation."); } catch (YarnRuntimeException e) { assertTrue("The thrown exception is not the expected one.", e.getMessage().startsWith( "Invalid resource scheduler gcores")); } }
### Question: FairScheduler extends AbstractYarnScheduler<FSAppAttempt, FSSchedulerNode> { @VisibleForTesting FSLeafQueue assignToQueue(RMApp rmApp, String queueName, String user) { FSLeafQueue queue = null; String appRejectMsg = null; try { QueuePlacementPolicy placementPolicy = allocConf.getPlacementPolicy(); queueName = placementPolicy.assignAppToQueue(queueName, user); if (queueName == null) { appRejectMsg = "Application rejected by queue placement policy"; } else { queue = queueMgr.getLeafQueue(queueName, true); if (queue == null) { appRejectMsg = queueName + " is not a leaf queue"; } } } catch (IOException ioe) { appRejectMsg = "Error assigning app to queue " + queueName; } if (appRejectMsg != null && rmApp != null) { LOG.error(appRejectMsg); rmContext.getDispatcher().getEventHandler().handle( new RMAppRejectedEvent(rmApp.getApplicationId(), appRejectMsg)); return null; } if (rmApp != null) { rmApp.setQueue(queue.getName()); } else { LOG.error("Couldn't find RM app to set queue name on"); } return queue; } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); synchronized RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized ResourceWeights getAppWeight(FSAppAttempt app); Resource getIncrementResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); long getNodeLocalityDelayMs(); long getRackLocalityDelayMs(); boolean isContinuousSchedulingEnabled(); synchronized int getContinuousSchedulingSleepMs(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); FSAppAttempt getSchedulerApp(ApplicationAttemptId appAttemptId); @Override ResourceCalculator getResourceCalculator(); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); synchronized void setRMContext(RMContext rmContext); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); AllocationConfiguration getAllocationConfiguration(); @Override List<ApplicationAttemptId> getAppsInQueue(String queueName); @Override synchronized String moveApplication(ApplicationId appId, String queueName); @Override synchronized void updateNodeResource(RMNode nm, ResourceOption resourceOption); @Override EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes(); @Override Set<String> getPlanQueues(); @Override void setEntitlement(String queueName, QueueEntitlement entitlement); @Override void removeQueue(String queueName); static final Resource CONTAINER_RESERVED; }### Answer: @Test public void testAssignToQueue() throws Exception { conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "true"); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); RMApp rmApp1 = new MockRMApp(0, 0, RMAppState.NEW); RMApp rmApp2 = new MockRMApp(1, 1, RMAppState.NEW); FSLeafQueue queue1 = scheduler.assignToQueue(rmApp1, "default", "asterix"); FSLeafQueue queue2 = scheduler.assignToQueue(rmApp2, "notdefault", "obelix"); assertEquals(rmApp1.getQueue(), queue1.getName()); assertEquals("root.asterix", rmApp1.getQueue()); assertEquals(rmApp2.getQueue(), queue2.getName()); assertEquals("root.notdefault", rmApp2.getQueue()); }
### Question: FairScheduler extends AbstractYarnScheduler<FSAppAttempt, FSSchedulerNode> { @Override public void reinitialize(Configuration conf, RMContext rmContext) throws IOException { try { allocsLoader.reloadAllocations(); } catch (Exception e) { LOG.error("Failed to reload allocations file", e); } } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); synchronized RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized ResourceWeights getAppWeight(FSAppAttempt app); Resource getIncrementResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); long getNodeLocalityDelayMs(); long getRackLocalityDelayMs(); boolean isContinuousSchedulingEnabled(); synchronized int getContinuousSchedulingSleepMs(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); FSAppAttempt getSchedulerApp(ApplicationAttemptId appAttemptId); @Override ResourceCalculator getResourceCalculator(); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); synchronized void setRMContext(RMContext rmContext); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); AllocationConfiguration getAllocationConfiguration(); @Override List<ApplicationAttemptId> getAppsInQueue(String queueName); @Override synchronized String moveApplication(ApplicationId appId, String queueName); @Override synchronized void updateNodeResource(RMNode nm, ResourceOption resourceOption); @Override EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes(); @Override Set<String> getPlanQueues(); @Override void setEntitlement(String queueName, QueueEntitlement entitlement); @Override void removeQueue(String queueName); static final Resource CONTAINER_RESERVED; }### Answer: @Test public void testDefaultRuleInitializesProperlyWhenPolicyNotConfigured() throws IOException { conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE); conf.setBoolean(FairSchedulerConfiguration.ALLOW_UNDECLARED_POOLS, false); PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE)); out.println("<?xml version=\"1.0\"?>"); out.println("<allocations>"); out.println("</allocations>"); out.close(); scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); List<QueuePlacementRule> rules = scheduler.allocConf.placementPolicy .getRules(); for (QueuePlacementRule rule : rules) { if (rule instanceof Default) { Default defaultRule = (Default) rule; assertNotNull(defaultRule.defaultQueueName); } } }
### Question: FairScheduler extends AbstractYarnScheduler<FSAppAttempt, FSSchedulerNode> { @Override public List<ApplicationAttemptId> getAppsInQueue(String queueName) { FSQueue queue = queueMgr.getQueue(queueName); if (queue == null) { return null; } List<ApplicationAttemptId> apps = new ArrayList<ApplicationAttemptId>(); queue.collectSchedulerApplications(apps); return apps; } FairScheduler(); FairSchedulerConfiguration getConf(); QueueManager getQueueManager(); synchronized RMContainerTokenSecretManager getContainerTokenSecretManager(); synchronized ResourceWeights getAppWeight(FSAppAttempt app); Resource getIncrementResourceCapability(); double getNodeLocalityThreshold(); double getRackLocalityThreshold(); long getNodeLocalityDelayMs(); long getRackLocalityDelayMs(); boolean isContinuousSchedulingEnabled(); synchronized int getContinuousSchedulingSleepMs(); Clock getClock(); FairSchedulerEventLog getEventLog(); @Override Allocation allocate(ApplicationAttemptId appAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); FSAppAttempt getSchedulerApp(ApplicationAttemptId appAttemptId); @Override ResourceCalculator getResourceCalculator(); @Override QueueMetrics getRootQueueMetrics(); @Override void handle(SchedulerEvent event); @Override void recover(RMState state); synchronized void setRMContext(RMContext rmContext); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override void reinitialize(Configuration conf, RMContext rmContext); @Override QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override List<QueueUserACLInfo> getQueueUserAclInfo(); @Override int getNumClusterNodes(); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); AllocationConfiguration getAllocationConfiguration(); @Override List<ApplicationAttemptId> getAppsInQueue(String queueName); @Override synchronized String moveApplication(ApplicationId appId, String queueName); @Override synchronized void updateNodeResource(RMNode nm, ResourceOption resourceOption); @Override EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes(); @Override Set<String> getPlanQueues(); @Override void setEntitlement(String queueName, QueueEntitlement entitlement); @Override void removeQueue(String queueName); static final Resource CONTAINER_RESERVED; }### Answer: @Test public void testGetAppsInQueue() throws Exception { scheduler.init(conf); scheduler.start(); scheduler.reinitialize(conf, resourceManager.getRMContext()); ApplicationAttemptId appAttId1 = createSchedulingRequest(1024, 1, 1, "queue1.subqueue1", "user1"); ApplicationAttemptId appAttId2 = createSchedulingRequest(1024, 1, 1, "queue1.subqueue2", "user1"); ApplicationAttemptId appAttId3 = createSchedulingRequest(1024, 1, 1, "default", "user1"); List<ApplicationAttemptId> apps = scheduler.getAppsInQueue("queue1.subqueue1"); assertEquals(1, apps.size()); assertEquals(appAttId1, apps.get(0)); apps = scheduler.getAppsInQueue("root.queue1.subqueue1"); assertEquals(1, apps.size()); assertEquals(appAttId1, apps.get(0)); apps = scheduler.getAppsInQueue("user1"); assertEquals(1, apps.size()); assertEquals(appAttId3, apps.get(0)); apps = scheduler.getAppsInQueue("root.user1"); assertEquals(1, apps.size()); assertEquals(appAttId3, apps.get(0)); apps = scheduler.getAppsInQueue("queue1"); Assert.assertEquals(2, apps.size()); Set<ApplicationAttemptId> appAttIds = Sets.newHashSet(apps.get(0), apps.get(1)); assertTrue(appAttIds.contains(appAttId1)); assertTrue(appAttIds.contains(appAttId2)); }
### Question: QueueMetrics implements MetricsSource { public synchronized static QueueMetrics forQueue(String queueName, Queue parent, boolean enableUserMetrics, Configuration conf) { return forQueue(DefaultMetricsSystem.instance(), queueName, parent, enableUserMetrics, conf); } protected QueueMetrics(MetricsSystem ms, String queueName, Queue parent, boolean enableUserMetrics, Configuration conf); synchronized static QueueMetrics forQueue(String queueName, Queue parent, boolean enableUserMetrics, Configuration conf); @Private synchronized static void clearQueueMetrics(); synchronized static QueueMetrics forQueue(MetricsSystem ms, String queueName, Queue parent, boolean enableUserMetrics, Configuration conf); synchronized QueueMetrics getUserMetrics(String userName); void getMetrics(MetricsCollector collector, boolean all); void submitApp(String user); void submitAppAttempt(String user); void runAppAttempt(ApplicationId appId, String user); void finishAppAttempt( ApplicationId appId, boolean isPending, String user); void finishApp(String user, RMAppState rmAppFinalState); void moveAppFrom(AppSchedulingInfo app); void moveAppTo(AppSchedulingInfo app); void setAvailableResourcesToQueue(Resource limit); void setAvailableResourcesToUser(String user, Resource limit); void incrPendingResources(String user, int containers, Resource res); void decrPendingResources(String user, int containers, Resource res); void allocateResources(String user, int containers, Resource res, boolean decrPending); void releaseResources(String user, int containers, Resource res); void reserveResource(String user, Resource res); void unreserveResource(String user, Resource res); void incrActiveUsers(); void decrActiveUsers(); void activateApp(String user); void deactivateApp(String user); int getAppsSubmitted(); int getAppsRunning(); int getAppsPending(); int getAppsCompleted(); int getAppsKilled(); int getAppsFailed(); Resource getAllocatedResources(); int getAllocatedMB(); int getAllocatedVirtualCores(); int getAllocatedGpuCores(); int getAllocatedContainers(); int getAvailableMB(); int getAvailableVirtualCores(); int getAvailableGpuCores(); int getPendingMB(); int getPendingVirtualCores(); int getPendingGpuCores(); int getPendingContainers(); int getReservedMB(); int getReservedVirtualCores(); int getReservedGpuCores(); int getReservedContainers(); int getActiveUsers(); int getActiveApps(); MetricsSystem getMetricsSystem(); }### Answer: @Test public void testCollectAllMetrics() { String queueName = "single"; QueueMetrics.forQueue(ms, queueName, null, false, conf); MetricsSource queueSource = queueSource(ms, queueName); checkApps(queueSource, 0, 0, 0, 0, 0, 0, true); try { checkApps(queueSource, 0, 0, 0, 0, 0, 0, false); Assert.fail(); } catch (AssertionError e) { Assert.assertTrue(e.getMessage().contains( "Expected exactly one metric for name ")); } checkApps(queueSource, 0, 0, 0, 0, 0, 0, true); }
### Question: CapacityScheduler extends AbstractYarnScheduler<FiCaSchedulerApp, FiCaSchedulerNode> implements PreemptableResourceScheduler, CapacitySchedulerContext, Configurable { @Override public Comparator<FiCaSchedulerApp> getApplicationComparator() { return applicationComparator; } CapacityScheduler(); @Override void setConf(Configuration conf); @Override Configuration getConf(); @VisibleForTesting synchronized String getMappedQueueForTest(String user); @Override QueueMetrics getRootQueueMetrics(); CSQueue getRootQueue(); @Override CapacitySchedulerConfiguration getConfiguration(); @Override synchronized RMContainerTokenSecretManager getContainerTokenSecretManager(); @Override Comparator<FiCaSchedulerApp> getApplicationComparator(); @Override ResourceCalculator getResourceCalculator(); @Override Comparator<CSQueue> getQueueComparator(); @Override int getNumClusterNodes(); @Override synchronized RMContext getRMContext(); @Override synchronized void setRMContext(RMContext rmContext); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @VisibleForTesting static void setQueueAcls(YarnAuthorizationProvider authorizer, Map<String, CSQueue> queues); CSQueue getQueue(String queueName); @Override @Lock(Lock.NoLock.class) Allocation allocate(ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); @Override @Lock(Lock.NoLock.class) QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override @Lock(Lock.NoLock.class) List<QueueUserACLInfo> getQueueUserAclInfo(); @Override void handle(SchedulerEvent event); @Lock(Lock.NoLock.class) @VisibleForTesting @Override FiCaSchedulerApp getApplicationAttempt( ApplicationAttemptId applicationAttemptId); @Lock(Lock.NoLock.class) FiCaSchedulerNode getNode(NodeId nodeId); @Override @Lock(Lock.NoLock.class) void recover(RMState state); @Override void dropContainerReservation(RMContainer container); @Override void preemptContainer(ApplicationAttemptId aid, RMContainer cont); @Override void killContainer(RMContainer cont); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); @Override List<ApplicationAttemptId> getAppsInQueue(String queueName); @Override synchronized void removeQueue(String queueName); @Override synchronized void addQueue(Queue queue); @Override synchronized void setEntitlement(String inQueue, QueueEntitlement entitlement); @Override synchronized String moveApplication(ApplicationId appId, String targetQueueName); @Override EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes(); @Override Resource getMaximumResourceCapability(String queueName); @Override Set<String> getPlanQueues(); @Private static final String ROOT_QUEUE; }### Answer: @Test (timeout = 5000) public void testApplicationComparator() { CapacityScheduler cs = new CapacityScheduler(); Comparator<FiCaSchedulerApp> appComparator= cs.getApplicationComparator(); ApplicationId id1 = ApplicationId.newInstance(1, 1); ApplicationId id2 = ApplicationId.newInstance(1, 2); ApplicationId id3 = ApplicationId.newInstance(2, 1); FiCaSchedulerApp app1 = Mockito.mock(FiCaSchedulerApp.class); when(app1.getApplicationId()).thenReturn(id1); FiCaSchedulerApp app2 = Mockito.mock(FiCaSchedulerApp.class); when(app2.getApplicationId()).thenReturn(id2); FiCaSchedulerApp app3 = Mockito.mock(FiCaSchedulerApp.class); when(app3.getApplicationId()).thenReturn(id3); assertTrue(appComparator.compare(app1, app2) < 0); assertTrue(appComparator.compare(app1, app3) < 0); assertTrue(appComparator.compare(app2, app3) < 0); }
### Question: CapacityScheduler extends AbstractYarnScheduler<FiCaSchedulerApp, FiCaSchedulerNode> implements PreemptableResourceScheduler, CapacitySchedulerContext, Configurable { public CSQueue getQueue(String queueName) { if (queueName == null) { return null; } return queues.get(queueName); } CapacityScheduler(); @Override void setConf(Configuration conf); @Override Configuration getConf(); @VisibleForTesting synchronized String getMappedQueueForTest(String user); @Override QueueMetrics getRootQueueMetrics(); CSQueue getRootQueue(); @Override CapacitySchedulerConfiguration getConfiguration(); @Override synchronized RMContainerTokenSecretManager getContainerTokenSecretManager(); @Override Comparator<FiCaSchedulerApp> getApplicationComparator(); @Override ResourceCalculator getResourceCalculator(); @Override Comparator<CSQueue> getQueueComparator(); @Override int getNumClusterNodes(); @Override synchronized RMContext getRMContext(); @Override synchronized void setRMContext(RMContext rmContext); @Override void serviceInit(Configuration conf); @Override void serviceStart(); @Override void serviceStop(); @Override synchronized void reinitialize(Configuration conf, RMContext rmContext); @VisibleForTesting static void setQueueAcls(YarnAuthorizationProvider authorizer, Map<String, CSQueue> queues); CSQueue getQueue(String queueName); @Override @Lock(Lock.NoLock.class) Allocation allocate(ApplicationAttemptId applicationAttemptId, List<ResourceRequest> ask, List<ContainerId> release, List<String> blacklistAdditions, List<String> blacklistRemovals); @Override @Lock(Lock.NoLock.class) QueueInfo getQueueInfo(String queueName, boolean includeChildQueues, boolean recursive); @Override @Lock(Lock.NoLock.class) List<QueueUserACLInfo> getQueueUserAclInfo(); @Override void handle(SchedulerEvent event); @Lock(Lock.NoLock.class) @VisibleForTesting @Override FiCaSchedulerApp getApplicationAttempt( ApplicationAttemptId applicationAttemptId); @Lock(Lock.NoLock.class) FiCaSchedulerNode getNode(NodeId nodeId); @Override @Lock(Lock.NoLock.class) void recover(RMState state); @Override void dropContainerReservation(RMContainer container); @Override void preemptContainer(ApplicationAttemptId aid, RMContainer cont); @Override void killContainer(RMContainer cont); @Override synchronized boolean checkAccess(UserGroupInformation callerUGI, QueueACL acl, String queueName); @Override List<ApplicationAttemptId> getAppsInQueue(String queueName); @Override synchronized void removeQueue(String queueName); @Override synchronized void addQueue(Queue queue); @Override synchronized void setEntitlement(String inQueue, QueueEntitlement entitlement); @Override synchronized String moveApplication(ApplicationId appId, String targetQueueName); @Override EnumSet<SchedulerResourceTypes> getSchedulingResourceTypes(); @Override Resource getMaximumResourceCapability(String queueName); @Override Set<String> getPlanQueues(); @Private static final String ROOT_QUEUE; }### Answer: @Test public void testAddAndRemoveAppFromCapacityScheduler() throws Exception { CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration(); setupQueueConfiguration(conf); conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class); MockRM rm = new MockRM(conf); @SuppressWarnings("unchecked") AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode> cs = (AbstractYarnScheduler<SchedulerApplicationAttempt, SchedulerNode>) rm .getResourceScheduler(); SchedulerApplication<SchedulerApplicationAttempt> app = TestSchedulerUtils.verifyAppAddedAndRemovedFromScheduler( cs.getSchedulerApplications(), cs, "a1"); Assert.assertEquals("a1", app.getQueue().getQueueName()); }
### Question: ApplicationHistoryClientService extends AbstractService implements ApplicationHistoryProtocol { @Override public GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request) throws YarnException, IOException { ApplicationId applicationId = request.getApplicationId(); try { GetApplicationReportResponse response = GetApplicationReportResponse.newInstance(history .getApplication(applicationId)); return response; } catch (IOException e) { LOG.error(e.getMessage(), e); throw e; } } ApplicationHistoryClientService(ApplicationHistoryManager history); @Private InetSocketAddress getBindAddress(); @Override CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request); @Override GetApplicationAttemptReportResponse getApplicationAttemptReport( GetApplicationAttemptReportRequest request); @Override GetApplicationAttemptsResponse getApplicationAttempts( GetApplicationAttemptsRequest request); @Override GetApplicationReportResponse getApplicationReport( GetApplicationReportRequest request); @Override GetApplicationsResponse getApplications(GetApplicationsRequest request); @Override GetContainerReportResponse getContainerReport( GetContainerReportRequest request); @Override GetContainersResponse getContainers(GetContainersRequest request); @Override GetDelegationTokenResponse getDelegationToken( GetDelegationTokenRequest request); @Override RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request); }### Answer: @Test public void testApplicationReport() throws IOException, YarnException { ApplicationId appId = null; appId = ApplicationId.newInstance(0, 1); GetApplicationReportRequest request = GetApplicationReportRequest.newInstance(appId); GetApplicationReportResponse response = clientService.getApplicationReport(request); ApplicationReport appReport = response.getApplicationReport(); Assert.assertNotNull(appReport); Assert.assertEquals(123, appReport.getApplicationResourceUsageReport() .getMemorySeconds()); Assert.assertEquals(345, appReport.getApplicationResourceUsageReport() .getVcoreSeconds()); Assert.assertEquals(345, appReport.getApplicationResourceUsageReport() .getGcoreSeconds()); Assert.assertEquals("application_0_0001", appReport.getApplicationId() .toString()); Assert.assertEquals("test app type", appReport.getApplicationType().toString()); Assert.assertEquals("test queue", appReport.getQueue().toString()); }
### Question: StringUtils { public static String escapeString(String str) { return escapeString(str, ESCAPE_CHAR, COMMA); } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getStringCollection(String str, String delim); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static Set<String> getTrimmedStrings(Collection<String> strings); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.slf4j.Logger LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String join(char separator, Iterable<?> strings); static String join(CharSequence separator, String[] strings); static String join(char separator, String[] strings); static String camelize(String s); static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements); static String getStackTrace(Thread t); static String popOptionWithArgument(String name, List<String> args); static boolean popOption(String name, List<String> args); static String popFirstNonOption(List<String> args); static String toLowerCase(String str); static String toUpperCase(String str); static boolean equalsIgnoreCase(String s1, String s2); static final int SHUTDOWN_HOOK_PRIORITY; static final Pattern SHELL_ENV_VAR_PATTERN; static final Pattern WIN_ENV_VAR_PATTERN; static final Pattern ENV_VAR_PATTERN; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test (timeout = 30000) public void testEscapeString() throws Exception { assertEquals(NULL_STR, StringUtils.escapeString(NULL_STR)); assertEquals(EMPTY_STR, StringUtils.escapeString(EMPTY_STR)); assertEquals(STR_WO_SPECIAL_CHARS, StringUtils.escapeString(STR_WO_SPECIAL_CHARS)); assertEquals(ESCAPED_STR_WITH_COMMA, StringUtils.escapeString(STR_WITH_COMMA)); assertEquals(ESCAPED_STR_WITH_ESCAPE, StringUtils.escapeString(STR_WITH_ESCAPE)); assertEquals(ESCAPED_STR_WITH_BOTH2, StringUtils.escapeString(STR_WITH_BOTH2)); }
### Question: StringUtils { public static URI[] stringToURI(String[] str){ if (str == null) return null; URI[] uris = new URI[str.length]; for (int i = 0; i < str.length;i++){ try{ uris[i] = new URI(str[i]); }catch(URISyntaxException ur){ throw new IllegalArgumentException( "Failed to create uri for " + str[i], ur); } } return uris; } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getStringCollection(String str, String delim); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static Set<String> getTrimmedStrings(Collection<String> strings); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.slf4j.Logger LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String join(char separator, Iterable<?> strings); static String join(CharSequence separator, String[] strings); static String join(char separator, String[] strings); static String camelize(String s); static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements); static String getStackTrace(Thread t); static String popOptionWithArgument(String name, List<String> args); static boolean popOption(String name, List<String> args); static String popFirstNonOption(List<String> args); static String toLowerCase(String str); static String toUpperCase(String str); static boolean equalsIgnoreCase(String s1, String s2); static final int SHUTDOWN_HOOK_PRIORITY; static final Pattern SHELL_ENV_VAR_PATTERN; static final Pattern WIN_ENV_VAR_PATTERN; static final Pattern ENV_VAR_PATTERN; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test (timeout = 30000) public void testStringToURI() { String[] str = new String[] { "file: try { StringUtils.stringToURI(str); fail("Ignoring URISyntaxException while creating URI from string file: } catch (IllegalArgumentException iae) { assertEquals("Failed to create uri for file: } }
### Question: StringUtils { public static String simpleHostname(String fullHostname) { if (InetAddresses.isInetAddress(fullHostname)) { return fullHostname; } int offset = fullHostname.indexOf('.'); if (offset != -1) { return fullHostname.substring(0, offset); } return fullHostname; } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getStringCollection(String str, String delim); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static Set<String> getTrimmedStrings(Collection<String> strings); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.slf4j.Logger LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String join(char separator, Iterable<?> strings); static String join(CharSequence separator, String[] strings); static String join(char separator, String[] strings); static String camelize(String s); static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements); static String getStackTrace(Thread t); static String popOptionWithArgument(String name, List<String> args); static boolean popOption(String name, List<String> args); static String popFirstNonOption(List<String> args); static String toLowerCase(String str); static String toUpperCase(String str); static boolean equalsIgnoreCase(String s1, String s2); static final int SHUTDOWN_HOOK_PRIORITY; static final Pattern SHELL_ENV_VAR_PATTERN; static final Pattern WIN_ENV_VAR_PATTERN; static final Pattern ENV_VAR_PATTERN; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test (timeout = 30000) public void testSimpleHostName() { assertEquals("Should return hostname when FQDN is specified", "hadoop01", StringUtils.simpleHostname("hadoop01.domain.com")); assertEquals("Should return hostname when only hostname is specified", "hadoop01", StringUtils.simpleHostname("hadoop01")); assertEquals("Should not truncate when IP address is passed", "10.10.5.68", StringUtils.simpleHostname("10.10.5.68")); }
### Question: StringUtils { public static Collection<String> getTrimmedStringCollection(String str){ Set<String> set = new LinkedHashSet<String>( Arrays.asList(getTrimmedStrings(str))); set.remove(""); return set; } static String stringifyException(Throwable e); static String simpleHostname(String fullHostname); @Deprecated static String humanReadableInt(long number); static String format(final String format, final Object... objects); static String formatPercent(double fraction, int decimalPlaces); static String arrayToString(String[] strs); static String byteToHexString(byte[] bytes, int start, int end); static String byteToHexString(byte bytes[]); static byte[] hexStringToByte(String hex); static String uriToString(URI[] uris); static URI[] stringToURI(String[] str); static Path[] stringToPath(String[] str); static String formatTimeDiff(long finishTime, long startTime); static String formatTime(long timeDiff); static String getFormattedTimeWithDiff(DateFormat dateFormat, long finishTime, long startTime); static String[] getStrings(String str); static Collection<String> getStringCollection(String str); static Collection<String> getStringCollection(String str, String delim); static Collection<String> getTrimmedStringCollection(String str); static String[] getTrimmedStrings(String str); static Set<String> getTrimmedStrings(Collection<String> strings); static String[] split(String str); static String[] split( String str, char escapeChar, char separator); static String[] split( String str, char separator); static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split); static String escapeString(String str); static String escapeString( String str, char escapeChar, char charToEscape); static String escapeString(String str, char escapeChar, char[] charsToEscape); static String unEscapeString(String str); static String unEscapeString( String str, char escapeChar, char charToEscape); static String unEscapeString(String str, char escapeChar, char[] charsToEscape); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.apache.commons.logging.Log LOG); static void startupShutdownMessage(Class<?> clazz, String[] args, final org.slf4j.Logger LOG); static String escapeHTML(String string); static String byteDesc(long len); @Deprecated static String limitDecimalTo2(double d); static String join(CharSequence separator, Iterable<?> strings); static String join(char separator, Iterable<?> strings); static String join(CharSequence separator, String[] strings); static String join(char separator, String[] strings); static String camelize(String s); static String replaceTokens(String template, Pattern pattern, Map<String, String> replacements); static String getStackTrace(Thread t); static String popOptionWithArgument(String name, List<String> args); static boolean popOption(String name, List<String> args); static String popFirstNonOption(List<String> args); static String toLowerCase(String str); static String toUpperCase(String str); static boolean equalsIgnoreCase(String s1, String s2); static final int SHUTDOWN_HOOK_PRIORITY; static final Pattern SHELL_ENV_VAR_PATTERN; static final Pattern WIN_ENV_VAR_PATTERN; static final Pattern ENV_VAR_PATTERN; final static String[] emptyStringArray; final static char COMMA; final static String COMMA_STR; final static char ESCAPE_CHAR; }### Answer: @Test public void testGetUniqueNonEmptyTrimmedStrings (){ final String TO_SPLIT = ",foo, bar,baz,,blah,blah,bar,"; Collection<String> col = StringUtils.getTrimmedStringCollection(TO_SPLIT); assertEquals(4, col.size()); assertTrue(col.containsAll(Arrays.asList(new String[]{"foo","bar","baz","blah"}))); }
### Question: Count extends FsCommand { @Override protected void processOptions(LinkedList<String> args) { CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, OPTION_QUOTA, OPTION_HUMAN, OPTION_HEADER); cf.parse(args); if (args.isEmpty()) { args.add("."); } showQuotas = cf.getOpt(OPTION_QUOTA); humanReadable = cf.getOpt(OPTION_HUMAN); if (cf.getOpt(OPTION_HEADER)) { out.println(ContentSummary.getHeader(showQuotas) + "PATHNAME"); } } Count(); @Deprecated Count(String[] cmd, int pos, Configuration conf); static void registerCommands(CommandFactory factory); static final String NAME; static final String USAGE; static final String DESCRIPTION; }### Answer: @Test public void processOptionsHeaderNoQuotas() { LinkedList<String> options = new LinkedList<String>(); options.add("-v"); options.add("dummy"); PrintStream out = mock(PrintStream.class); Count count = new Count(); count.out = out; count.processOptions(options); String noQuotasHeader = " DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME"; verify(out).println(noQuotasHeader); verifyNoMoreInteractions(out); } @Test public void processOptionsHeaderWithQuotas() { LinkedList<String> options = new LinkedList<String>(); options.add("-q"); options.add("-v"); options.add("dummy"); PrintStream out = mock(PrintStream.class); Count count = new Count(); count.out = out; count.processOptions(options); String withQuotasHeader = " QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA " + " DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME"; verify(out).println(withQuotasHeader); verifyNoMoreInteractions(out); }
### Question: GroovyWorld extends GroovyObjectSupport { public void registerWorld(Object world) { if (world instanceof GroovyObject) { worlds.add((GroovyObject) world); } else { throw new RuntimeException("Only GroovyObject supported"); } } GroovyWorld(); void registerWorld(Object world); Object getProperty(String property); void setProperty(String property, Object newValue); Object invokeMethod(String name, Object args); }### Answer: @Test(expected = RuntimeException.class) public void should_not_register_pure_java_object() { world.registerWorld("JAVA"); }
### Question: Hooks { public static void Before(Object... args) { addHook(args, true, false); } static void World(Closure body); static void Before(Object... args); static void After(Object... args); static void AfterStep(Object... args); static void BeforeStep(Object... args); }### Answer: @Test public void only_allows_arguments_string_integer_closure() { try { Hooks.Before("TAG", 10D, 100, new MethodClosure(this, "dummyClosureCall"), 0.0); fail("CucumberException was not thrown"); } catch (CucumberException e) { assertEquals("An argument of the type java.lang.Double found, Before only allows the argument types " + "String - Tag, Integer - order, and Closure", e.getMessage()); } } @Test public void only_allows_one_timeout_argument() { try { Hooks.Before(1L, 2L); fail("CucumberException was not thrown"); } catch (CucumberException e) { assertEquals("An argument of the type java.lang.Long found, Before only allows the argument types String - Tag, Integer - order, and Closure", e.getMessage()); } } @Test public void only_allows_one_order_argument() { try { Hooks.Before(1, 2); fail("CucumberException was not thrown"); } catch (CucumberException e) { assertEquals("Two order (Integer) arguments found; 1, and; 2", e.getMessage()); } }
### Question: XQueryRunConfig { public String getMainFile() { return getExpressionValue(mainFileExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnMainFileValue() { String result = config.getMainFile(); assertThat(result, is(MAIN_FILE_NAME)); }
### Question: XQueryRunConfig { public String getHost() { return getExpressionValue(hostExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnHostValue() { String result = config.getHost(); assertThat(result, is(HOST)); }
### Question: XQueryRunConfig { public String getPort() { return getExpressionValue(portExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnPortValue() { String result = config.getPort(); assertThat(result, is(PORT)); }
### Question: XQueryRunConfig { public String getUsername() { return getExpressionValue(usernameExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnUsernameValue() { String result = config.getUsername(); assertThat(result, is(USERNAME)); }
### Question: XQueryRunConfig { public String getPassword() { return getExpressionValue(passwordExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnPasswordValue() { String result = config.getPassword(); assertThat(result, is(PASSWORD)); }
### Question: XQueryRunConfig { public boolean isConfigFileEnabled() { return Boolean.parseBoolean(getExpressionValue(configFileEnabledExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnConfigEnabledValue() { boolean result = config.isConfigFileEnabled(); assertThat(result, is(CONFIG_FILE_ENABLED)); }
### Question: XQueryRunConfig { public String getConfigFile() { return getExpressionValue(configFileExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnConfigFileValue() { String result = config.getConfigFile(); assertThat(result, is(CONFIG_FILE)); }
### Question: XQueryRunConfig { public String getDatabaseName() { return getExpressionValue(databaseNameExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnDatabaseNameValue() { String result = config.getDatabaseName(); assertThat(result, is(DATABASE_NAME)); }
### Question: XQueryRunConfig { public String getContextItemType() { return getExpressionValue(contextItemTypeExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnContextItemTypeValue() { String result = config.getContextItemType(); assertThat(result, is(CONTEXT_ITEM_TYPE)); }
### Question: OutputMethodFactory { public Properties getOutputMethodProperties() { Properties props = new Properties(); props.setProperty(METHOD_PROPERTY_NAME, OUTPUT_TYPE_XML); return props; } OutputMethodFactory(XQueryRunConfig config); Properties getOutputMethodProperties(); static final String METHOD_PROPERTY_NAME; static final String OUTPUT_TYPE_XML; }### Answer: @Test public void shouldAlwaysReturnOutputMethodXml() { OutputMethodFactory outputMethodFactory = new OutputMethodFactory(mock(XQueryRunConfig.class)); Properties result = outputMethodFactory.getOutputMethodProperties(); assertThat(result.keySet().size(), is(1)); assertThat(result.getProperty(METHOD_PROPERTY_NAME), is(OUTPUT_TYPE_XML)); }
### Question: ConnectionFactory { public XQConnection getConnection(XQDataSource dataSource) throws Exception { XQConnection connection; if (config.getDataSourceType().connectionPropertiesAreSupported() && config.getUsername() != null && config.getUsername().length() > 0) { connection = dataSource.getConnection(config.getUsername(), config.getPassword()); } else { connection = dataSource.getConnection(); } return connection; } ConnectionFactory(XQueryRunConfig config); XQConnection getConnection(XQDataSource dataSource); }### Answer: @Test public void shouldInvokeGetConnectionWithoutParametersWhenConnectionPropertiesNotSupported() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SAXON); factory.getConnection(dataSource); verify(dataSource).getConnection(); } @Test public void shouldInvokeGetConnectionWithParametersWhenConnectionPropertiesAreSupportedAndSet() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.MARKLOGIC); given(config.getUsername()).willReturn(USER); given(config.getPassword()).willReturn(PASSWORD); factory.getConnection(dataSource); verify(dataSource).getConnection(USER, PASSWORD); } @Test public void shouldInvokeGetConnectionWithoutParametersWhenConnectionPropertiesAreSupportedAndUsernameNotSet() throws Exception { given(config.getUsername()).willReturn(null); given(config.getDataSourceType()).willReturn(XQueryDataSourceType.MARKLOGIC); factory.getConnection(dataSource); verify(dataSource).getConnection(); } @Test public void shouldInvokeGetConnectionWithoutParametersWhenConnectionPropertiesAreSupportedAndUsernameSetEmpty() throws Exception { given(config.getUsername()).willReturn(""); given(config.getDataSourceType()).willReturn(XQueryDataSourceType.MARKLOGIC); factory.getConnection(dataSource); verify(dataSource).getConnection(); }
### Question: XQueryRunConfig { public boolean isDebugEnabled() { return Boolean.parseBoolean(getExpressionValue(debugExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnDebugEnabledValue() { boolean result = config.isDebugEnabled(); assertThat(result, is(true)); }
### Question: DataSourceFactory { public XQDataSource getDataSource() throws Exception { XQueryDataSourceType dataSourceType = config.getDataSourceType(); XQDataSource dataSource = getXQDataSource(dataSourceType, config); if (dataSourceType.connectionPropertiesAreSupported()) { if (config.getHost() != null && config.getHost().length() > 0) { dataSource.setProperty(SERVER_NAME, config.getHost()); } if (config.getPort() != null && config.getPort().length() > 0) { dataSource.setProperty(PORT, config.getPort()); } if (config.getDatabaseName() != null && config.getDatabaseName().length() > 0) { dataSource.setProperty(DATABASE_NAME, config.getDatabaseName()); } } return dataSource; } DataSourceFactory(XQueryRunConfig config); XQDataSource getDataSource(); static final String SERVER_NAME; static final String PORT; static final String DATABASE_NAME; }### Answer: @Test public void shouldGetDataSourceWithoutSettingProperties() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SAXON); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldSetHostOnDataSourceWhenConnectionPropertiesSupportedAndHostNotEmpty() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getHost()).willReturn(HOST); factory.getDataSource(); verify(dataSource).setProperty(SERVER_NAME, HOST); } @Test public void shouldNotSetHostOnDataSourceWhenConnectionPropertiesSupportedAndHostEmpty() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getHost()).willReturn(""); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldNotSetHostOnDataSourceWhenConnectionPropertiesSupportedAndHostNotSet() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getHost()).willReturn(null); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldSetPortOnDataSourceWhenConnectionPropertiesSupportedAndPortNotEmpty() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getPort()).willReturn(PORT_VALUE); factory.getDataSource(); verify(dataSource).setProperty(PORT, PORT_VALUE); } @Test public void shouldNotSetPortOnDataSourceWhenConnectionPropertiesSupportedAndPortEmpty() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getPort()).willReturn(""); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldNotSetPortOnDataSourceWhenConnectionPropertiesSupportedAndPortNotSet() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getPort()).willReturn(null); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldSetDbNameOnDataSourceWhenConnectionPropertiesSupportedAndDbNameNotEmpty() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getDatabaseName()).willReturn(DB_NAME); factory.getDataSource(); verify(dataSource).setProperty(DATABASE_NAME, DB_NAME); } @Test public void shouldNotSetDbNameOnDataSourceWhenConnectionPropertiesSupportedAndDbNameEmpty() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getDatabaseName()).willReturn(""); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldNotSetDbNameOnDataSourceWhenConnectionPropertiesSupportedAndDbNameNotSet() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getDatabaseName()).willReturn(null); factory.getDataSource(); verifyNoMoreInteractions(dataSource); } @Test public void shouldGetDataSourceBasedOnDataSourceType() throws Exception { factory = new DataSourceFactory(config); given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SEDNA); given(config.getHost()).willReturn("host"); given(config.getPort()).willReturn("123"); XQDataSource result = factory.getDataSource(); assertThat(result, is(not(nullValue()))); }
### Question: XQueryRunConfig { public String getDebugPort() { return getExpressionValue(debugPortExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnDebugPortValue() { String result = config.getDebugPort(); assertThat(result, is("9000")); }
### Question: ExpressionFactory { public XQPreparedExpression getExpression(XQConnection connection) throws Exception { XQPreparedExpression preparedExpression = connection .prepareExpression(contentFactory.getXQueryContentAsStream()); contextItemBinder.bindContextItem(connection, preparedExpression); variablesBinder.bindVariables(connection, preparedExpression); return preparedExpression; } ExpressionFactory(XQueryRunConfig config, XQueryContentFactory contentFactory, VariablesBinder variablesBinder, ContextItemBinder contextItemBinder); XQPreparedExpression getExpression(XQConnection connection); }### Answer: @Test public void shouldPrepareExpressionUsingConnection() throws Exception { InputStream inputStream = mock(InputStream.class); given(contentFactory.getXQueryContentAsStream()).willReturn(inputStream); factory.getExpression(connection); verify(contentFactory).getXQueryContentAsStream(); verify(connection).prepareExpression(inputStream); } @Test public void shouldBindContextItem() throws Exception { factory.getExpression(connection); verify(contextItemBinder).bindContextItem(connection, expression); } @Test public void shouldBindVariables() throws Exception { factory.getExpression(connection); verify(variablesBinder).bindVariables(connection, expression); }
### Question: AttributeBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindNode(name, createAttributeNode(value), getType(connection)); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type); XQItemType getType(XQConnection connection); }### Answer: @Test public void shouldCreateAttributeType() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(connection).createAttributeType(null, XQItemType.XQBASETYPE_ANYSIMPLETYPE); } @Test public void shouldBindNode() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindNode(eq(qName), isA(Node.class), eq(xqItemType)); }
### Question: AtomicValueBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindAtomicValue(name, value, getType(connection, type)); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type); }### Answer: @Test public void shouldCreateAtomicTypeUsingConnection() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(connection).createAtomicType(anyInt()); } @Test public void shouldBindAtomicValue() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindAtomicValue(qName, VALUE, xqItemType); }
### Question: XQueryRunConfig { public boolean isContextItemEnabled() { return Boolean.parseBoolean(getExpressionValue(contextItemEnabledExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnContextItemEnabledValue() { boolean result = config.isContextItemEnabled(); assertThat(result, is(CONTEXT_ITEM_ENABLED)); }
### Question: TextBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindNode(name, createTextNode(value), getType(connection)); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type); XQItemType getType(XQConnection connection); }### Answer: @Test public void shouldCreateDocumentTypeUsingConnection() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(connection).createTextType(); } @Test public void shouldBindNode() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindNode(eq(qName), isA(Node.class), eq(xqItemType)); }
### Question: DocumentBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindDocument(name, value, null, null); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type); }### Answer: @Test public void shouldBindDocument() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindDocument(qName, VALUE, null, null); }
### Question: NameExtractor { public QName getName(String name, String namespace) { String[] parts = name.split(":"); if (parts.length < 1 || parts.length > 2) { throw new RuntimeException("Variable name '" + name + "' is invalid"); } String namespacePrefix = null; String localPart = parts[parts.length - 1]; if (parts.length == 2) { namespacePrefix = parts[0]; } if (namespace != null && namespace.length() > 0) { if (namespacePrefix != null) { return new QName(namespace, localPart, namespacePrefix); } else { return new QName(namespace, localPart); } } if (namespacePrefix != null) { return new QName(DEFAULT_NS_PREFIX, localPart, namespacePrefix); } else { return new QName(localPart); } } QName getName(String name, String namespace); }### Answer: @Test(expected = RuntimeException.class) public void shouldThrowExceptionForInvalidNameWithNotEnoughDetails() { extractor.getName(SEPARATOR, ""); } @Test(expected = RuntimeException.class) public void shouldThrowExceptionForInvalidNameWithTooManyColons() { extractor.getName("a:b:c", ""); } @Test public void shouldReturnQNameWithLocalPartOnly() { QName result = extractor.getName(LOCAL_PART, null); assertThat(result.getLocalPart(), is(LOCAL_PART)); assertThat(result.getNamespaceURI(), is(DEFAULT_NS_PREFIX)); assertThat(result.getPrefix(), is(DEFAULT_NS_PREFIX)); } @Test public void shouldReturnQNameWithLocalPartAndPrefix() { QName result = extractor.getName(PREFIX + SEPARATOR + LOCAL_PART, null); assertThat(result.getLocalPart(), is(LOCAL_PART)); assertThat(result.getNamespaceURI(), is(DEFAULT_NS_PREFIX)); assertThat(result.getPrefix(), is(PREFIX)); } @Test public void shouldReturnQNameWithLocalPartAndEmptyNamespace() { QName result = extractor.getName(LOCAL_PART, DEFAULT_NS_PREFIX); assertThat(result.getLocalPart(), is(LOCAL_PART)); assertThat(result.getNamespaceURI(), is(DEFAULT_NS_PREFIX)); assertThat(result.getPrefix(), is(DEFAULT_NS_PREFIX)); } @Test public void shouldReturnQNameWithLocalPartAndPrefixAndEmptyNamespace() { QName result = extractor.getName(PREFIX + SEPARATOR + LOCAL_PART, DEFAULT_NS_PREFIX); assertThat(result.getLocalPart(), is(LOCAL_PART)); assertThat(result.getNamespaceURI(), is(DEFAULT_NS_PREFIX)); assertThat(result.getPrefix(), is(PREFIX)); } @Test public void shouldReturnQNameWithLocalPartAndNamespace() { QName result = extractor.getName(LOCAL_PART, NAMESPACE); assertThat(result.getLocalPart(), is(LOCAL_PART)); assertThat(result.getNamespaceURI(), is(NAMESPACE)); assertThat(result.getPrefix(), is(DEFAULT_NS_PREFIX)); } @Test public void shouldReturnQNameWithLocalPartAndPrefixAndNamespace() { QName result = extractor.getName(PREFIX + SEPARATOR + LOCAL_PART, NAMESPACE); assertThat(result.getLocalPart(), is(LOCAL_PART)); assertThat(result.getNamespaceURI(), is(NAMESPACE)); assertThat(result.getPrefix(), is(PREFIX)); }
### Question: XQueryRunConfig { public boolean isContextItemFromEditorEnabled() { return Boolean.parseBoolean(getExpressionValue(contextItemFromEditorEnabledExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnContextItemFromEditorEnabledValue() { boolean result = config.isContextItemFromEditorEnabled(); assertThat(result, is(CONTEXT_ITEM_FROM_EDITOR_ENABLED)); }
### Question: XQueryRunConfig { public String getContextItemFile() { return getExpressionValue(contextItemFileExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnContextItemFileValue() { String result = config.getContextItemFile(); assertThat(result, is(CONTEXT_ITEM_FILE_NAME)); }
### Question: XQueryRunConfig { public String getContextItemText() { return getExpressionValue(contextItemTextExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnContextItemTextValue() { String result = config.getContextItemText(); assertThat(result, is(INNER_XML)); }
### Question: XQueryRunConfig { public List<XQueryRunnerVariable> getVariables() { String count = getExpressionValue(numberOfVariablesExpression); int numberOfVariables = Integer.valueOf(count); List<XQueryRunnerVariable> result = new ArrayList<XQueryRunnerVariable>(numberOfVariables); for (int i = 1; i <= numberOfVariables; i++) { String baseXPath = "/run/variables/list/variable[" + i + "]/"; XQueryRunnerVariable variable = new XQueryRunnerVariable(); variable.ACTIVE = Boolean.parseBoolean(getExpressionValue(getExpression(baseXPath + "@active"))); variable.NAME = getExpressionValue(getExpression(baseXPath + "@name")); variable.NAMESPACE = getExpressionValue(getExpression(baseXPath + "@namespace")); variable.TYPE = getExpressionValue(getExpression(baseXPath + "@type")); variable.VALUE = getExpressionValue(getExpression("string(" + baseXPath + "text())")); result.add(variable); } return result; } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnZeroVariables() throws Exception { config = new XQueryRunConfig("<run/>"); List<XQueryRunnerVariable> result = config.getVariables(); assertThat(result.size(), is(0)); } @Test public void shouldReturnVariables() { List<XQueryRunnerVariable> result = config.getVariables(); assertThat(result.get(0).ACTIVE, is(VARIABLE_ACTIVE)); assertThat(result.get(0).NAME, is(VARIABLE_NAME)); assertThat(result.get(0).NAMESPACE, is(VARIABLE_NAMESPACE)); assertThat(result.get(0).TYPE, is(VARIABLE_TYPE)); assertThat(result.get(0).VALUE, is(INNER_XML)); }
### Question: XQueryRunConfig { public XQueryDataSourceType getDataSourceType() { return XQueryDataSourceType.getForName(getExpressionValue(dataSourceTypeExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer: @Test public void shouldReturnDataSourceType() { XQueryDataSourceType result = config.getDataSourceType(); assertThat(result, is(DATA_SOURCE_TYPE)); }
### Question: TaskChain { public void doInvoke() { if (taskItemList.isEmpty()) { return; } for(TaskItem item : taskItemList) { BusinessWrapper<String> result = item.runTask(); callback.doNotify(result); if (!result.isSuccess()) { logger.warn("run task={} failure, result={}", item.getTaskName(), result.getMsg()); break; } else { logger.info("run task={} success, result={}", item.getTaskName(), result.getBody()); } } } TaskChain(String chainName, TaskCallback callback, List<TaskItem> taskItemList); void doInvoke(); }### Answer: @Test public void test() { TaskCallback callback = new TaskCallback() { @Override public void doNotify(Object notify) { System.err.println(JSON.toJSONString(notify)); } }; List list = new ArrayList(); TaskItem taskItem = new TaskItem("asas") { @Override public BusinessWrapper<String> runTask() { return null; } }; list.add(taskItem); TaskChain taskChain = new TaskChain("initSystem", callback, list); taskChain.doInvoke(); }
### Question: EmailService { public boolean doSendNewTodo(UserDO userDO, TodoDailyVO dailyVO, UserDO sponsorUser) { logger.info("send new todo email to:" + userDO.getUsername() + " for id:" + dailyVO.getId()); try { HtmlEmail email = buildHtmlEmail(userDO.getMail(), userDO.getDisplayName()); email.setHtmlMsg(TplUtils.doNewTodoNotify(sponsorUser, dailyVO, userDO.getDisplayName())); email.send(); return true; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } boolean doSendNewTodo(UserDO userDO, TodoDailyVO dailyVO, UserDO sponsorUser); boolean doSendUpdateTodo(UserDO userDO, TodoDailyVO dailyVO, UserDO sponsorUser); boolean doSendAcceptFeedbackTodo(UserDO userDO, TodoDailyVO dailyVO, UserDO sponsorUser); boolean doSendInitFeedbackTodo(UserDO userDO, TodoDailyVO dailyVO, UserDO sponsorUser); boolean doFinishTodo(UserDO userDO, TodoDailyVO dailyVO, UserDO sponsorUser); HtmlEmail buildHtmlEmail(String emailAddress, String displayName); boolean doSendSubmitTodo(TodoDetailVO todoDetailVO); boolean doSendCompleteTodo(TodoDetailVO todoDetailVO); }### Answer: @Test public void testdoSendNewTodo() { UserDO sponsorUser = new UserDO(); sponsorUser.setDisplayName("飞雪"); UserDO userDO = new UserDO(); userDO.setMail("xiaozh@net"); userDO.setDisplayName("飞雪"); TodoDailyDO dailyDO = new TodoDailyDO(); TodoConfigDO levelOne = new TodoConfigDO(); levelOne.setConfigName("测试一级类目"); TodoConfigDO levelTwo = new TodoConfigDO(); levelTwo.setConfigName("测试二级类目"); TodoDailyVO dailyVO = new TodoDailyVO(dailyDO, levelOne, levelTwo); FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss"); dailyVO.setGmtCreate(dateFormat.format(new Date())); dailyVO.setGmtModify(dateFormat.format(new Date())); emailService.doSendUpdateTodo(userDO, dailyVO, sponsorUser); } @Test public void testdoSendNewTodo2() { UserDO sponsorUser = new UserDO(); sponsorUser.setDisplayName("梁荐"); UserDO userDO = new UserDO(); userDO.setMail("@net"); userDO.setDisplayName("梁荐"); TodoDailyDO dailyDO = new TodoDailyDO(); TodoConfigDO levelOne = new TodoConfigDO(); levelOne.setConfigName("测试一级类目"); TodoConfigDO levelTwo = new TodoConfigDO(); levelTwo.setConfigName("测试二级类目"); TodoDailyVO dailyVO = new TodoDailyVO(dailyDO, levelOne, levelTwo); emailService.doSendNewTodo(userDO, dailyVO, sponsorUser); }
### Question: AliyunLogManageServiceImpl implements AliyunLogManageService { private List<Project> queryListProject(String project) { Client client = aliyunLogService.acqClient(); int offset = 0; int size = 100; String logStoreSubName = ""; ListProjectRequest req = new ListProjectRequest(project, offset, size); List<Project> projects = new ArrayList<>(); try { projects = client.ListProject(req).getProjects(); } catch (LogException lg) { } return projects; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer: @Test public void testQuerListProject() { List<String> projects = aliyunLogManageServiceImpl.queryListProject(); System.err.println("Projects:" + projects.toString() + "\n"); }
### Question: AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public List<String> queryListLogStores(String project) { Client client = aliyunLogService.acqClient(); int offset = 0; int size = 100; String logStoreSubName = ""; ListLogStoresRequest req = new ListLogStoresRequest(project, offset, size, logStoreSubName); ArrayList<String> logStores = new ArrayList<>(); try { logStores = client.ListLogStores(req).GetLogStores(); } catch (LogException lg) { } return logStores; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer: @Test public void testQuerListLogStores() { List<String> logStores = aliyunLogManageServiceImpl.queryListLogStores("collect-web-service-logs"); System.err.println("ListLogs:" + logStores.toString() + "\n"); }
### Question: AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public List<String> queryListMachineGroup(String project, String groupName) { Client client = aliyunLogService.acqClient(); int offset = 0; int size = 50; ListMachineGroupRequest req = new ListMachineGroupRequest(project, groupName, offset, size); List<String> machineGroups = new ArrayList<>(); try { machineGroups = client.ListMachineGroup(req).GetMachineGroups(); } catch (LogException lg) { } return machineGroups; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer: @Test public void testQueryListLogs() { List<String> list = aliyunLogManageServiceImpl.queryListMachineGroup("collect-web-service-logs",""); System.err.println("MachineGroups:" + list.toString() + "\n"); }
### Question: AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public MachineGroup getMachineGroup(String project, String groupName) { Client client = aliyunLogService.acqClient(); GetMachineGroupRequest req = new GetMachineGroupRequest(project, groupName); MachineGroup machineGroup = new MachineGroup(); try { machineGroup = client.GetMachineGroup(req).GetMachineGroup(); } catch (LogException lg) { } return machineGroup; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer: @Test public void testGetMachineGroup() { MachineGroup mg = aliyunLogManageServiceImpl.getMachineGroup("collect-web-service-logs","group_trade"); System.err.println("MachineGroup:" + mg.toString() + "\n"); }
### Question: AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO) { if (StringUtils.isEmpty(cfgVO.getTopic())) cfgVO.setTopic(cfgVO.getServerGroupDO().getName()); if (StringUtils.isEmpty(cfgVO.getServerGroupName())) cfgVO.setServerGroupName(cfgVO.getServerGroupDO().getName()); if (cfgVO.getServerGroupId() == 0) cfgVO.setServerGroupId(cfgVO.getServerGroupDO().getId()); if (!saveMachineGroup(cfgVO)) return new BusinessWrapper<>(false); try { if (cfgVO.getId() == 0) { logServiceDao.addLogServiceServerGroupCfg(cfgVO); } else { logServiceDao.updateLogServiceServerGroupCfg(cfgVO); } } catch (Exception e) { e.printStackTrace(); return new BusinessWrapper<>(false); } return new BusinessWrapper<>(true); } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer: @Test public void testSaveServerGroupCfg() { ServerGroupDO serverGroupDO = serverGroupDao.queryServerGroupByName("group_member"); LogServiceServerGroupCfgVO cfgVO = new LogServiceServerGroupCfgVO(serverGroupDO); cfgVO.setProject("collect-web-service-logs"); cfgVO.setLogstore("logstore_apps"); System.err.println(aliyunLogManageServiceImpl.saveServerGroupCfg(cfgVO)); }
### Question: IP { public String getIPSection(){ if(ip==null) return null; if(netmask == null || netmask.equals("32")){ return ip; } else{ return ip+"/"+netmask; } } IP(String ip); IP(String ip, String netmask); IP(String ip, String netmask, String getway); String getIp(); Boolean isPublicIP(); String toString(); String getIPSection(); }### Answer: @Test public void test() { IP ip=new IP("10.100.1.0"); System.err.println(ip.getIPSection()); IP ip2=new IP("10.100.1.0/32"); System.err.println(ip2.getIPSection()); IP ip3=new IP("10.100.1.0/255.255.255.250"); System.err.println(ip3.getIPSection()); IP ip4=new IP("10.100.1.a"); System.err.println(ip4.getIPSection()); }
### Question: AliyunLogServiceImpl implements AliyunLogService { public void readLog(String project, String logstore) { Client client = acqClient(); int shard_id = 0; long curTimeInSec = System.currentTimeMillis() / 1000; try { GetCursorResponse cursorRes = client.GetCursor(project, logstore, shard_id, curTimeInSec - 3600); String beginCursor = cursorRes.GetCursor(); cursorRes = client.GetCursor(project, logstore, shard_id, Consts.CursorMode.END); String endCursor = cursorRes.GetCursor(); String curCursor = beginCursor; while (curCursor.equals(endCursor) == false) { int loggroup_count = 2; BatchGetLogResponse logDataRes = client.BatchGetLog(project, logstore, shard_id, loggroup_count, curCursor, endCursor); List<LogGroupData> logGroups = logDataRes.GetLogGroups(); for (LogGroupData logGroupData : logGroups) { Logs.LogGroup log_group_pb = logGroupData.GetLogGroup(); for (Logs.Log log_pb : log_group_pb.getLogsList()) { for (Logs.Log.Content content : log_pb.getContentsList()) { } } } String next_cursor = logDataRes.GetNextCursor(); curCursor = next_cursor; } } catch (Exception e) { e.printStackTrace(); } } @Override TableVO<List<LogServiceCfgDO>> getLogServiceCfgPage(int page, int length, String serverName); @Override LogServiceVO queryLog(LogServiceQuery logServiceQuery); GetHistogramsResponse queryHistograms(String project, String logstore, String topic, int from, int to, String query); @Override TableVO<List<LogServicePathDO>> getLogServicePathPage(int page, int length, String tagPath, long serverGroupId); @Override TableVO<List<LogFormatDefault>> queryDefaultLog(LogHistogramsVO logHistogramsVO); @Override TableVO<List<LogFormatKa>> queryKaLog(LogHistogramsVO logHistogramsVO); void readLog(String project, String logstore); void init(); @Override Client acqClient(); @Override TableVO<List<LogHistogramsVO>> getLogHistogramsPage(long logServiceId, int page, int length); @Override TableVO<List<LogServiceServerGroupCfgVO>> queryServerGroupPage(int page, int length, String name, boolean isUsername, int useType); static final String PROJECT_JAVA_LOG; }### Answer: @Test public void testReadLog() { aliyunLogServiceImpl.readLog("collect-nginx-logs","ka-www"); }
### Question: ExplainServiceImpl implements ExplainService { @Override public Set<String> doScanRepo(ExplainDTO explainDTO) { try { Git git = GitProcessor.cloneRepository(localPath + "/explain/" + explainDTO.getId() + "/", explainDTO.getRepo(), username, pwd, Collections.EMPTY_LIST); Set<String> refSet = GitProcessor.getRefList(git.getRepository()); refSet.remove("HEAD"); refSet.remove("head"); return refSet; } catch (Exception e) { logger.error(e.getMessage(), e); } return Collections.EMPTY_SET; } @Override void addRepoExplainSub(ExplainDTO explainDTO); @Override void delRepoExplainSub(long id); @Override TableVO<List<ExplainDTO>> queryRepoExplainSubList(String repo, int page, int length); @Override Set<String> doScanRepo(ExplainDTO explainDTO); @Override TableVO<List<String>> queryRepoList(String repo, int page, int length); @Override ExplainDTO getRepoSubById(long id); @Override TableVO<List<ExplainJob>> queryJobs(ExplainJob explainJob, int page, int length); @Override boolean subJob(ExplainJob explainJob); @Override boolean unsubJob(ExplainJob explainJob); }### Answer: @Test public void testdoScanRepoAndTransRemote() { ExplainInfo explainInfo = new ExplainInfo(); explainInfo.setRepo("http: explainInfo.setScanPath(JSON.toJSONString(Arrays.asList("cmdb/cmdb-service/src/main/resources/sql"))); explainInfo.setNotifyEmails(JSON.toJSONString(Arrays.asList("xiaozhenxing@net"))); ExplainDTO explainDTO = new ExplainDTO(explainInfo); explainService.doScanRepo(explainDTO); }
### Question: TodoServiceImpl implements TodoService { public List<TodoDetailVO> queryMyTodoJob(String username) { List<UserDO> users = authService.queryUsersByRoleName(TodoDO.TodoTypeEnum.devops.getDesc()); boolean isDevops = false; List<TodoDetailDO> todoDetailList = new ArrayList<>(); for (UserDO userDO : users) { if (userDO.getUsername().equals(username)) { todoDetailList = todoDao.queryAllTodoJob(); isDevops = true; break; } } if (!isDevops) todoDetailList = todoDao.queryMyTodoJob(username); return acqTodoJob(todoDetailList); } @Override BusinessWrapper<Boolean> saveTodoConfig(TodoConfigDO todoConfigDO); @Override BusinessWrapper<Boolean> delTodoConfig(long itemId); @Override TableVO<List<TodoConfigVO>> queryConfigPage(String queryName, long parent, int valid, int page, int length); @Override List<TodoConfigDO> queryChildrenById(long parentId); @Override TableVO<List<TodoDailyVO>> queryTodoPage(TodoDailyQueryDO queryDO, int page, int length); @Override BusinessWrapper<Boolean> saveTodoItem(TodoDailyDO dailyDO); @Override TableVO<List<TodoDailyVO>> queryTodoProcessPage(TodoDailyQueryDO queryDO, int page, int length); @Override TodoDailyVO queryTodoById(long id); @Override List<TodoGroupVO> queryTodoGroup(); @Override TodoDetailVO queryTodoDetail(long id); @Override TodoDetailVO establishTodo(long todoId); @Override BusinessWrapper<Boolean> saveKeyboxDetail(TodoKeyboxDetailDO todoKeyboxDetailDO); @Override BusinessWrapper<Boolean> saveCiUserGroupDetail(TodoCiUserGroupDetailDO ciUserGroupDetailDO); @Override BusinessWrapper<Boolean> submitTodoDetail(long id); @Override BusinessWrapper<Boolean> delKeyboxDetail(long todoKeyboxDetailId); @Override BusinessWrapper<Boolean> delCiUserGroupDetail(long todoCiUserGroupDetailId); @Override BusinessWrapper<Boolean> setTodoSystemAuth(long todoSystemAuthDetailId); List<TodoDetailVO> queryMyTodoJob(String username); @Override List<TodoDetailVO> queryMyTodoJob(); @Override BusinessWrapper<Boolean> revokeTodoDetail(long id); @Override BusinessWrapper<Boolean> processingTodoDetail(long id); @Override List<TodoDetailVO> queryCompleteTodoJob(); List<TodoDetailVO> queryCompleteTodoJob(String username); void invokeTodoDetailVO(TodoDetailVO todoDetailVO); }### Answer: @Test public void test() { List<TodoDetailVO> list = todoServiceImpl.queryMyTodoJob("by"); }
### Question: IptablesRule { public String getRule() { buildRuleByType(); return getDesc() + getRuleHead() + ruleBody; } IptablesRule(String port, List<IP> ips, int ruleType, String desc); IptablesRule(String port, List<IP> ips, String desc); IptablesRule(String port, String desc); IptablesRule(List<IP> ips, String desc); String getDesc(); void setDesc(String desc); String getRule(); final static int ruleTypeAllowIP4Port; final static int ruleTypeOpenPort; final static int ruleTypeAllowIP; }### Answer: @Test public void test() { IptablesRule ir = new IptablesRule("80", "HTTP/NGINX"); System.err.println(ir.getRule()); List<IP> ipList = new ArrayList<IP>(); ipList.add(new IP("10.17.0.0/8")); IptablesRule ir2 = new IptablesRule(ipList, "内网"); System.err.println(ir2.getRule()); ipList.add(new IP("192.168.0.0/16")); ipList.add(new IP("10.0.0.0/8")); IptablesRule ir3 = new IptablesRule(ipList, "多个内网"); System.err.println(ir3.getRule()); IptablesRule ir4 = new IptablesRule("8080",ipList,"HTTP/TOMCAT"); System.err.println(ir4.getRule()); IptablesRule ir5 = new IptablesRule("8080:8090",ipList,"HTTP/TOMCAT"); System.err.println(ir5.getRule()); }
### Question: ZabbixHistoryServiceImpl implements ZabbixHistoryService { @Override public JSONObject queryCpuUser(ServerDO serverDO, int limit) { return historyGet(serverDO, null, ZabbixHistoryItemEnum.CPU_USER.getItemKey(), historyTypeNumericFloat, limit); } @Override String acqResultValue(JSONObject response); @Override JSONObject queryCpuUser(ServerDO serverDO, int limit); @Override JSONObject queryCpuIowait(ServerDO serverDO, int limit); @Override JSONObject queryPerCpuAvg1(ServerDO serverDO, int limit); @Override JSONObject queryPerCpuAvg5(ServerDO serverDO, int limit); @Override JSONObject queryPerCpuAvg15(ServerDO serverDO, int limit); @Override JSONObject queryMemoryTotal(ServerDO serverDO, int limit); @Override JSONObject queryMemoryAvailable(ServerDO serverDO, int limit); @Override JSONObject queryFreeDiskSpaceOnSys(ServerDO serverDO, int limit); @Override JSONObject queryFreeDiskSpaceOnData(ServerDO serverDO, int limit); JSONObject queryTotalDiskSpaceOnData(ServerDO serverDO, int limit); JSONObject queryUsedDiskSpaceOnData(ServerDO serverDO, int limit); @Override JSONObject queryDiskReadBps(ServerDO serverDO, String volume, int limit); @Override JSONObject queryDiskWriteBps(ServerDO serverDO, String volume, int limit); @Override JSONObject queryDiskReadIops(ServerDO serverDO, String volume, int limit); @Override JSONObject queryDiskWriteIops(ServerDO serverDO, String volume, int limit); @Override JSONObject queryDiskReadMs(ServerDO serverDO, String volume, int limit); @Override JSONObject queryDiskWriteMs(ServerDO serverDO, String volume, int limit); @Override List<Map<String, Object>> queryHistory(ServerGroupDO serverGroupDO); @Override HashMap<Long, HashMap<Integer, String>> queryZabbixMoniter(ServerGroupDO serverGroupDO); final int zabbix_result_array; final int zabbix_result_object; static final int historyTypeNumericFloat; static final int historyTypeCharacter; static final int historyTypeLog; static final int historyTypeNumericUnsigned; static final int historyTypeText; }### Answer: @Test public void testQueryCpuUser() { ServerDO serverDO = serverDao.getServerInfoById(31); JSONObject response=zabbixHistoryService.queryCpuUser(serverDO, 1); String value=zabbixHistoryService.acqResultValue(response); System.err.println(value); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public int usergroupCreate(ServerGroupDO serverGroupDO) { String usergrpName = serverGroupDO.getName().replace("group_", "users_"); int id = usergroupGet(usergrpName); if (id != 0) return id; ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("usergroup.create").build(); request.putParam("name", usergrpName); JSONObject rights = new JSONObject(); rights.put("permission", 2); rights.put("id", hostgroupGet(serverGroupDO.getName())); request.putParam("rights", rights); JSONObject getResponse = call(request); int usrgrpids = getResultId(getResponse, "usrgrpids"); actionCreate(serverGroupDO); if (usrgrpids != 0) { logger.info("Zabbix : usergroup " + usergrpName + " create"); return usrgrpids; } else { logger.error("Zabbix : usergroup " + usergrpName + " create"); return 0; } } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testUsergroupCreate() { ServerGroupDO serverGroupDO = serverGroupDao.queryServerGroupByName("group_baoherp"); System.err.println(zabbixServiceImpl.usergroupCreate(serverGroupDO)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public BusinessWrapper<Boolean> userCreate(UserDO userDO) { if (userDO == null) return new BusinessWrapper<>(ErrorCode.userNotExist.getCode(), ErrorCode.userNotExist.getMsg()); ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("user.create").build(); request.putParam("alias", userDO.getUsername()); request.putParam("name", userDO.getDisplayName()); request.putParam("passwd", ""); request.putParam("usrgrps", acqUsergrps(userDO)); JSONArray userMedias = new JSONArray(); userMedias.add(acqUserMedias(1, userDO.getMail())); if (userDO.getMobile() != null && !userDO.getMobile().isEmpty()) { userMedias.add(acqUserMedias(3, userDO.getMobile())); } request.putParam("user_medias", userMedias); JSONObject getResponse = call(request); int userids = getResultId(getResponse, "userids"); if (userids != 0) { userDO.setZabbixAuthed(UserDO.ZabbixAuthType.authed.getCode()); userDao.updateUserZabbixAuthed(userDO); return new BusinessWrapper<>(true); } userDO.setZabbixAuthed(UserDO.ZabbixAuthType.noAuth.getCode()); userDao.updateUserZabbixAuthed(userDO); return new BusinessWrapper<>(ErrorCode.zabbixUserCreate.getCode(), ErrorCode.zabbixUserCreate.getMsg()); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testUserCreate() { UserDO userDO = userDao.getUserByName("zhonghongsheng"); System.err.println(userDO); System.err.println(zabbixServiceImpl.userCreate(userDO)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public BusinessWrapper<Boolean> userDelete(UserDO userDO) { if (userDO == null) return new BusinessWrapper<>(ErrorCode.userNotExist.getCode(), ErrorCode.userNotExist.getMsg()); int userid = this.userGet(userDO); if (userid == 0) return new BusinessWrapper<>(true); ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("user.delete").paramEntry("params", new int[]{ userid }).build(); JSONObject getResponse = call(request); int userids = getResultId(getResponse, "userids"); if (userids == 0) return new BusinessWrapper<>(ErrorCode.zabbixUserDelete.getCode(), ErrorCode.zabbixUserDelete.getMsg()); userDO.setZabbixAuthed(UserDO.ZabbixAuthType.noAuth.getCode()); userDao.updateUserZabbixAuthed(userDO); return new BusinessWrapper<>(true); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testUserDelete() { UserDO userDO = userDao.getUserByName("chenyuyu"); System.err.println(userDO); System.err.println(zabbixServiceImpl.userDelete(userDO)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public BusinessWrapper<Boolean> syncUser() { List<UserDO> listUserDO = userDao.getAllUser(); for (UserDO userDO : listUserDO) { if (userDO.getAuthed() == UserDO.AuthType.noAuth.getCode()) continue; if (userGet(userDO) != 0) { userDO.setZabbixAuthed(UserDO.AuthType.authed.getCode()); userDao.updateUserZabbixAuthed(userDO); continue; } userCreate(userDO); logger.info("Zabbix : add user " + userDO.getUsername()); } cleanZabbixUser(); return new BusinessWrapper<>(true); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testSyncUser() { zabbixServiceImpl.syncUser(); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public BusinessWrapper<Boolean> userUpdate(UserDO userDO) { if (userDO == null) return new BusinessWrapper<>(ErrorCode.userNotExist.getCode(), ErrorCode.userNotExist.getMsg()); ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("user.update").build(); request.putParam("userid", userGet(userDO)); request.putParam("name", userDO.getDisplayName()); request.putParam("usrgrps", acqUsergrps(userDO)); JSONArray userMedias = new JSONArray(); userMedias.add(acqUserMedias(1, userDO.getMail())); if (userDO.getMobile() != null && !userDO.getMobile().isEmpty()) { userMedias.add(acqUserMedias(3, userDO.getMobile())); } request.putParam("user_medias", userMedias); JSONObject getResponse = call(request); int userids = getResultId(getResponse, "userids"); if (userids != 0) { userDO.setZabbixAuthed(UserDO.ZabbixAuthType.authed.getCode()); userDao.updateUserZabbixAuthed(userDO); return new BusinessWrapper<>(true); } userDO.setZabbixAuthed(UserDO.ZabbixAuthType.noAuth.getCode()); userDao.updateUserZabbixAuthed(userDO); return new BusinessWrapper<>(ErrorCode.zabbixUserCreate.getCode(), ErrorCode.zabbixUserCreate.getMsg()); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testUserUpdate() { UserDO userDO = userDao.getUserByName("chenyuyu"); zabbixServiceImpl.userUpdate(userDO); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { private int actionGet(ServerGroupDO serverGroupDO) { if (serverGroupDO == null) return 0; String usergrpName = serverGroupDO.getName().replace("group_", "users_"); ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("action.get").build(); request.putParam("output", "extend"); request.putParam("selectOperations", "extend"); JSONObject filter = new JSONObject(); filter.put("name", "Report problems to " + usergrpName); request.putParam("filter", filter); JSONObject getResponse = call(request); return getResultId(getResponse, "actionid"); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testActionGet() { }
### Question: Iptables { public String toBody() { body = getInfo(); body = body + getDesc(); for (IptablesRule ir : irList) { body = body + ir.getRule() +"\n"; } return body; } Iptables(List<IptablesRule> irList, String desc); Iptables(IptablesRule ir, String desc); String toBody(); }### Answer: @Test public void test() { Iptables i = new Iptables(buildRules(),"测试规则"); System.err.println(i.toBody()); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { private boolean hostDelete(ServerDO serverDO) { if (serverDO == null) return false; int hostid = hostGet(serverDO); if (hostid == 0) return true; ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("host.delete").paramEntry("params", new int[]{ hostid }).build(); JSONObject getResponse = call(request); int hostids = getResultId(getResponse, "hostids"); if (hostids == 0) return false; return true; } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testHostDelete() { System.err.println("hostCreate : " + zabbixServiceImpl.delMonitor(336)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { private boolean hostCreate(ServerDO serverDO) { if (hostExists(serverDO)) return true; if (!hostgroupCreate(serverDO)) return false; ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("host.create").build(); request.putParam("host", acqZabbixServerName(serverDO)); request.putParam("interfaces", acqInterfaces(serverDO)); request.putParam("groups", acqGroup(serverDO)); request.putParam("templates", acqTemplate(serverDO)); request.putParam("macros", acqMacros(serverDO)); int proxyid = proxyGet(serverDO); if (proxyid != 0) { request.putParam("proxy_hostid", proxyid); } JSONObject getResponse = call(request); int hostids = getResultId(getResponse, "hostids"); if (hostids == 0) return false; return true; } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testHostCreate() { System.err.println("hostCreate : " + zabbixServiceImpl.addMonitor(510)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public boolean hostExists(ServerDO serverDO) { if (hostGet(serverDO) == 0) return false; return true; } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testHostExists() { ServerDO serverDO = serverDao.getServerInfoById(336); System.err.println("hostExists : " + zabbixServiceImpl.hostExists(serverDO)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { @Override public int hostGetStatus(ServerDO serverDO) { if (serverDO == null) return 0; JSONObject filter = new JSONObject(); filter.put("ip", acqServerMonitorIp(serverDO)); JSONObject getResponse = call(ZabbixRequestBuilder.newBuilder() .method("host.get").paramEntry("filter", filter) .build()); return getResultId(getResponse, "status"); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testHostGetStatus() { ServerDO serverDO = serverDao.getServerInfoById(336); System.err.println("hostGetStatus : " + zabbixServiceImpl.hostGetStatus(serverDO)); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { public int itemGet(ServerDO serverDO, String itemName, String itemKey) { if (serverDO == null) return 0; ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("item.get").build(); request.putParam("output", "extend"); request.putParam("hostids", hostGet(serverDO)); if (itemName != null) { JSONObject name = new JSONObject(); name.put("name", itemName); request.putParam("search", name); } if (itemKey != null) { JSONObject key = new JSONObject(); key.put("key_", itemKey); request.putParam("search", key); } request.putParam("sortfield", "name"); JSONObject getResponse = call(request); return getResultId(getResponse, "itemid"); } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testItems() { ServerDO serverDO = serverDao.getServerInfoById(31); System.err.println("itemGet : " + zabbixServiceImpl.itemGet(serverDO,"CPU", "system.cpu.util[,user]")); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { public void api(int statusType, String key, String project, String group, String env) { if (!apiCheckKey(key)) return; ServerGroupDO serverGroupDO = serverGroupDao.queryServerGroupByName("group_" + project); if (serverGroupDO == null) return; List<ServerDO> servers = serverDao.acqServersByGroupId(serverGroupDO.getId()); if (servers == null || servers.get(0) == null) return; for (ServerDO serverDO : servers) { if (!ServerDO.EnvTypeEnum.getEnvTypeName(serverDO.getEnvType()).equals(env)) continue; this.hostUpdateStatus(serverDO, statusType); } } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testApi() { zabbixServiceImpl.api(0, "7ab6ed9458b3cb477ecee026d85e5b42", "trade", "trade-gray", "gray"); }
### Question: ZabbixServiceImpl implements ZabbixService, InitializingBean { public int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO) { int userid = this.userGet(userDO); if (userid == 0) return 2; String usergrpName = serverGroupDO.getName().replace("group_", "users_"); int usrgrpid = usergroupGet(usergrpName); if (usrgrpid == 0) return 3; ZabbixRequest request = ZabbixRequestBuilder.newBuilder() .method("user.get").paramEntry("userids", new int[]{ userid }).paramEntry("usrgrpids", new int[]{ usrgrpid }) .build(); JSONObject getResponse = call(request); int resultUserid = getResultId(getResponse, "userid"); if (resultUserid == 0) return 0; return 1; } @Override String getApiVersion(); @Override boolean hostExists(ServerDO serverDO); @Override int hostGetStatus(ServerDO serverDO); @Deprecated int hostGetByIP(String ip); @Deprecated int hostGetByName(String name); int proxyGet(String hostname); boolean hostgroupCreate(String name); int templateGet(String name); int usergroupGet(String usergroup); @Override BusinessWrapper<Boolean> userCreate(UserDO userDO); @Override int usergroupCreate(ServerGroupDO serverGroupDO); @Override int userGet(UserDO userDO); @Override BusinessWrapper<Boolean> userDelete(UserDO userDO); @Override BusinessWrapper<Boolean> syncUser(); void cleanZabbixUser(); @Override BusinessWrapper<Boolean> checkUser(); @Override BusinessWrapper<Boolean> userUpdate(UserDO userDO); @Deprecated JSONObject itemGetAll(ServerDO serverDO); int itemGet(ServerDO serverDO, String itemName, String itemKey); @Override int actionCreate(ServerGroupDO serverGroupDO); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, int limit); @Override JSONObject historyGet(ServerDO serverDO, String itemName, String itemKey, int historyType, String timestampFrom, String timestampTill); void api(int statusType, String key, String project, String group, String env); @Override BusinessWrapper<Boolean> refresh(); @Override BusinessWrapper<Boolean> addMonitor(long serverId); @Override BusinessWrapper<Boolean> delMonitor(long serverId); @Override BusinessWrapper<Boolean> disableMonitor(long serverId); @Override BusinessWrapper<Boolean> enableMonitor(long serverId); @Override BusinessWrapper<Boolean> ci(String key, int type, String project, String group, String env, Long deployId, String bambooDeployVersion, int bambooBuildNumber, String bambooDeployProject, boolean bambooDeployRollback, String bambooManualBuildTriggerReasonUserName, int errorCode, String branchName, int deployType); int checkUserInUsergroup(UserDO userDO, ServerGroupDO serverGroupDO); @Override void afterPropertiesSet(); static final String zabbix_host_monitor_public_ip; static final String zabbix_proxy_id; static final String zabbix_proxy_name; static final int hostStatusDisable; static final int hostStatusEnable; static final int isMonitor; static final int noMonitor; }### Answer: @Test public void testUser() { UserDO userDO = new UserDO(); userDO.setUsername("liangjian"); ServerGroupDO serverGroupDO= new ServerGroupDO(); serverGroupDO.setName("group_ci"); System.err.println(zabbixServiceImpl.checkUserInUsergroup(userDO,serverGroupDO)); }
### Question: RemoteInvokeHandler { public static ConnectionSession getSession(ApplicationKeyDO applicationKeyDO, HostSystem hostSystem) { JSch jSch = new JSch(); String passphrase = applicationKeyDO.getPassphrase(); if (StringUtils.isEmpty(passphrase)) { passphrase = ""; } try { jSch.addIdentity(applicationKeyDO.getSessionId() + "", EncryptionUtil.decrypt(applicationKeyDO.getPrivateKey()).getBytes(), applicationKeyDO.getPublicKey().getBytes(), passphrase.getBytes()); Session session = jSch.getSession(hostSystem.getUser(), hostSystem.getHost(), hostSystem.getPort() == null ? 22 : hostSystem.getPort()); session.setConfig("StrictHostKeyChecking", "no"); session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); session.setServerAliveInterval(SERVER_ALIVE_INTERVAL); session.connect(SESSION_TIMEOUT); Channel channel = session.openChannel("shell"); ((ChannelShell) channel).setAgentForwarding(true); ((ChannelShell) channel).setPtyType("xterm"); channel.connect(); ConnectionSession connectionSession = new ConnectionSession(channel, session); return connectionSession; } catch (Exception e) { logger.error(e.getMessage(), e); hostSystem.setErrorMsg(e.getMessage()); if (e.getMessage().toLowerCase().contains("userauth fail")) { hostSystem.setStatusCd(HostSystem.PUBLIC_KEY_FAIL_STATUS); } else if (e.getMessage().toLowerCase().contains("auth fail") || e.getMessage().toLowerCase().contains("auth cancel")) { hostSystem.setStatusCd(HostSystem.AUTH_FAIL_STATUS); } else if (e.getMessage().toLowerCase().contains("unknownhostexception")) { hostSystem.setErrorMsg("DNS Lookup Failed"); hostSystem.setStatusCd(HostSystem.HOST_FAIL_STATUS); } else { hostSystem.setStatusCd(HostSystem.GENERIC_FAIL_STATUS); } } return null; } static ConnectionSession getSession(ApplicationKeyDO applicationKeyDO, HostSystem hostSystem); static final int SERVER_ALIVE_INTERVAL; static final int SESSION_TIMEOUT; }### Answer: @Test public void testRemoteInvoke() { HostSystem hostSystem = new HostSystem(); hostSystem.setInstanceId("1"); hostSystem.setHost("10.17.1.120"); hostSystem.setPort(22); hostSystem.setUser("manage"); for(int i = 0; i < 10; i++) { ConnectionSession connectionSession = RemoteInvokeHandler.getSession(keyboxDao.getApplicationKey(), hostSystem); if (connectionSession != null) { String uniqueKey = "aaa-" + i; connectionSession.registerRead(uniqueKey, new SessionBridge() { @Override public void process(String value) { HttpResult result = new HttpResult(value); System.err.println(JSON.toJSONString(result)); } }); connectionSession.unregisterRead(uniqueKey); connectionSession.close(); } } } @Test public void testRemoteInvoke2() { HostSystem hostSystem = new HostSystem(); hostSystem.setInstanceId("1"); hostSystem.setHost("10.17.1.120"); hostSystem.setPort(22); hostSystem.setUser("manage"); ConnectionSession connectionSession = RemoteInvokeHandler.getSession(keyboxDao.getApplicationKey(), hostSystem); connectionSession.registerRead("aaa", new SessionBridge() { @Override public void process(String value) { HttpResult result = new HttpResult(value); System.err.println(JSON.toJSONString(result)); } }); try { connectionSession.writeToRemote("sudo bash\n"); connectionSession.writeToRemote("prometheus_update\n"); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } }
### Question: Getway { public Getway() { } Getway(); Getway(UserDO userDO, List<ServerGroupDO> serverGroups); Getway(List<ServerGroupDO> serverGroups, Map<String, List<ServerDO>> servers); String getPath(); void addUser(UserDO userDO); void addServerGroup(List<ServerGroupDO> serverGroups); void addServers(Map<String, List<ServerDO>> servers); @Override String toString(); }### Answer: @Test public void testGetway() { List<UserDO> userDOList = authDao.getLoginUsers(); if (userDOList.isEmpty()) { return; } UserDO userDO = userDOList.get(0); ServerGroupDO serverGroupDO = serverGroupService.queryServerGroupByName("group_trade"); ServerGroupDO serverGroupDO2 = serverGroupService.queryServerGroupByName("group_member"); ServerGroupDO serverGroupDO3 = serverGroupService.queryServerGroupByName("group_wms"); List<ServerGroupDO> serverGroups = new ArrayList<>(); serverGroups.add(serverGroupDO); serverGroups.add(serverGroupDO2); serverGroups.add(serverGroupDO3); Map<String, List<ServerDO>> servers = new HashMap<>(); Getway gw = new Getway(userDO, serverGroups); System.err.println("生成用户getway.conf---------------------------------------"); System.err.println(gw.toString()); System.err.println("生成全局列表getway_host.conf---------------------------------------"); Getway gw2 = new Getway(serverGroups ,servers); System.err.println(gw2.toString()); System.err.println("---------------------------------------"); }