method2testcases
stringlengths 118
3.08k
|
---|
### Question:
BootstrapDataRepo implements DomainRepo { @Override public void recycle () { data.clear(); classMap.clear(); } BootstrapDataRepo(); void add(Object item); void add(List<Object> items); List<Object> getData(); List<Object> getData(Class<?> type); Competition getBootstrapCompetition(); Properties getBootState(); @Override void recycle(); void readBootRecord(URL bootUrl); }### Answer:
@Test public void testRecycle () { uut.add("test1"); uut.add("test2"); uut.add(42); uut.add(43); uut.add(44); List<?> result = uut.getData(); assertEquals(5, result.size(), "five"); uut.recycle(); result = uut.getData(); assertEquals(0, result.size(), "zero"); } |
### Question:
Battery extends AbstractCustomer implements CustomerModelAccessor { public double getCapacityKWh () { return capacityKWh; } Battery(); Battery(String name); @Override void initialize(); @Override CustomerInfo getCustomerInfo(); @Override void step(); @Override String getName(); @Override void setName(String name); @ConfigurableValue(valueType = "Double", dump = false, description = "size of battery in kWh") @StateChange void setCapacityKWh(double value); double getCapacityKWh(); @ConfigurableValue(valueType = "Double", dump = false, description = "maximum charge rate") @StateChange void setMaxChargeKW(double value); double getMaxChargeKW(); @ConfigurableValue(valueType = "Double", dump = false, description = "Maximum discharge rate") void setMaxDischargeKW(double value); double getMaxDischargeKW(); @ConfigurableValue(valueType = "Double", dump = false, description = "ratio of charge energy to battery energy") @StateChange void setChargeEfficiency(double value); double getChargeEfficiency(); @ConfigurableValue(valueType = "Double", dump = false, description = "hourly charge lost as proportion of capacity") void setSelfDischargeRate(double value); double getSelfDischargeRate(); @Override double getBrokerSwitchFactor(boolean isSuperseding); @Override double getTariffChoiceSample(); @Override double getInertiaSample(); @Override void evaluateTariffs(List<Tariff> tariffs); @Override double getShiftingInconvenienceFactor(Tariff tariff); @Override CapacityProfile getCapacityProfile(Tariff tariff); }### Answer:
@Test public void testCreate () { Battery battery = new Battery("test"); assertNotNull(battery, "constructed"); assertEquals(50.0, battery.getCapacityKWh(), 1e-6, "correct capacity"); } |
### Question:
Config { public synchronized static Config getInstance () { if (null == instance) { log.error("Unconfigured instance requested"); } return instance; } private Config(ServerConfiguration source); boolean isAllocationDetailsLogging(); boolean isCapacityDetailsLogging(); boolean isUsageChargesLogging(); List<String> getStructureTypes(); void configure(); Map<String, Map<String, StructureInstance>> getStructures(); synchronized static Config getInstance(); synchronized static void initializeInstance(ServerConfiguration configSource); }### Answer:
@Test public void testGetInstance () { Config item = Config.getInstance(); assertNotNull(item, "Config created"); } |
### Question:
MisoBuyer extends Broker { public MisoBuyer (String username) { super(username, true, true); } MisoBuyer(String username); void init(BrokerProxy proxy, int seedId, ContextService service); void generateOrders(Instant now, List<Timeslot> openSlots); double getCoolThreshold(); @ConfigurableValue(valueType = "Double", description = "temperature threshold for cooling") MisoBuyer withCoolThreshold(double value); double getCoolCoef(); @ConfigurableValue(valueType = "Double", description = "Multiplier: cooling MWh / degree-hour") MisoBuyer withCoolCoef(double value); double getHeatThreshold(); @ConfigurableValue(valueType = "Double", description = "temperature threshold for heating") MisoBuyer withHeatThreshold(double value); double getHeatCoef(); @ConfigurableValue(valueType = "Double", description = "multiplier: heating MWh / degree-hour (negative for heating)") MisoBuyer withHeatCoef(double value); double getTempAlpha(); @ConfigurableValue(valueType = "Double", description = "exponential smoothing parameter for temperature") MisoBuyer withTempAlpha(double value); double getScaleFactor(); @ConfigurableValue(valueType = "Double", description = "overall scale factor for demand profile") MisoBuyer withScaleFactor(double value); }### Answer:
@Test public void testMisoBuyer() { assertNotNull(buyer, "created something"); assertEquals(buyer.getUsername(), "Test", "correct name"); } |
### Question:
RegulationCapacity { public RegulationCapacity (TariffSubscription subscription, double upRegulationCapacity, double downRegulationCapacity) { super(); this.subscription = subscription; if (upRegulationCapacity < 0.0) { if (upRegulationCapacity < -epsilon) log.warn("upRegulationCapacity " + upRegulationCapacity + " < 0.0"); upRegulationCapacity = 0.0; } if (downRegulationCapacity > 0.0) { if (downRegulationCapacity > epsilon) log.warn("downRegulationCapacity " + downRegulationCapacity + " > 0.0"); downRegulationCapacity = 0.0; } this.upRegulationCapacity = upRegulationCapacity; this.downRegulationCapacity = downRegulationCapacity; } RegulationCapacity(TariffSubscription subscription,
double upRegulationCapacity,
double downRegulationCapacity); RegulationCapacity(); long getId(); TariffSubscription getSubscription(); double getUpRegulationCapacity(); double getDownRegulationCapacity(); }### Answer:
@Test public void testRegulationCapacity () { RegulationAccumulator rc = new RegulationAccumulator(1.0, -2.0); assertEquals(1.0, rc.getUpRegulationCapacity(),1e-6, "correct up-regulation"); assertEquals(-2.0, rc.getDownRegulationCapacity(), 1e-6, "correct down-regulation"); } |
### Question:
EvSocialClass extends AbstractCustomer { int getMinCount () { return minCount; } EvSocialClass(); EvSocialClass(String name); @Override void initialize(); double getHomeChargerProbability(); @Override void saveBootstrapState(); @Override void evaluateTariffs(List<Tariff> tariffs); @Override void step(); @Override String toString(); }### Answer:
@Test public void testInitialization () { initializeClass(); assertEquals(className, evSocialClass.getName(), "Correct name"); assertEquals(2, evSocialClass.getMinCount(), "correct min count"); } |
### Question:
Config { public synchronized static Config getInstance () { if (null == instance) { instance = new Config(); } return instance; } private Config(); double getEpsilon(); double getLambda(); double getTouFactor(); double getInterruptibilityFactor(); double getVariablePricingFactor(); double getTieredRateFactor(); int getMinDefaultDuration(); int getMaxDefaultDuration(); double getRationalityFactor(); double getNsInertia(); double getBrokerSwitchFactor(); double getWeightInconvenience(); int getTariffCount(); int getProfileLength(); @Deprecated void configure(); void configure(ServerConfiguration configSource); Map<String, Collection<?>> getBeans(); synchronized static Config getInstance(); synchronized static void recycle(); }### Answer:
@Test public void testGetInstance () { Config item = Config.getInstance(); assertNotNull(item, "Config created"); } |
### Question:
RegulationCapacity { public double getUpRegulationCapacity () { return upRegulationCapacity; } RegulationCapacity(TariffSubscription subscription,
double upRegulationCapacity,
double downRegulationCapacity); RegulationCapacity(); long getId(); TariffSubscription getSubscription(); double getUpRegulationCapacity(); double getDownRegulationCapacity(); }### Answer:
@Test public void testSetUp () { RegulationAccumulator rc = new RegulationAccumulator(1.0, -2.0); rc.setUpRegulationCapacity(2.5); assertEquals(2.5, rc.getUpRegulationCapacity(), 1e-6, "successful set"); rc.setUpRegulationCapacity(-3.0); assertEquals(2.5, rc.getUpRegulationCapacity(), 1e-6, "no change"); } |
### Question:
BrokerProxyService implements BrokerProxy { @Override public void sendMessage (Broker broker, Object messageObject) { if (broker.isEnabled()) visualizerProxyService.forwardMessage(messageObject); localSendMessage(broker, messageObject); } BrokerProxyService(); @Override void sendMessage(Broker broker, Object messageObject); @Override void sendMessages(Broker broker, List<?> messageObjects); @Override void broadcastMessage(Object messageObject); @Override void broadcastMessages(List<?> messageObjects); @Override void routeMessage(Object message); @Override void registerBrokerMessageListener(Object listener, Class<?> msgType); @Override void setDeferredBroadcast(boolean b); @Override void broadcastDeferredMessages(); }### Answer:
@Test public void testSendMessage_single() { brokerProxy.sendMessage(stdBroker, message); verify(template, times(0)).send(any(String.class), any(MessageCreator.class)); stdBroker.setEnabled(true); brokerProxy.sendMessage(stdBroker, message); verify(template, times(1)).send(any(String.class), any(MessageCreator.class)); }
@Test public void localBrokerSingleMessage () { brokerProxy.sendMessage(localBroker, message); assertEquals(0, localBroker.messages.size(), "no messages for non-enabled broker"); localBroker.setEnabled(true); brokerProxy.sendMessage(localBroker, message); assertEquals(1, localBroker.messages.size(), "one message for enabled broker"); assertEquals(message, localBroker.messages.get(0), "correct message arrived"); }
@Test public void wholesaleBrokerSingleMessage () { brokerProxy.sendMessage(wholesaleBroker, message); assertEquals(1, wholesaleBroker.messages.size(), "one message for wholesale broker"); assertEquals(message, wholesaleBroker.messages.get(0), "correct message arrived"); } |
### Question:
BrokerProxyService implements BrokerProxy { @Override public void sendMessages (Broker broker, List<?> messageObjects) { for (Object message : messageObjects) { sendMessage(broker, message); } } BrokerProxyService(); @Override void sendMessage(Broker broker, Object messageObject); @Override void sendMessages(Broker broker, List<?> messageObjects); @Override void broadcastMessage(Object messageObject); @Override void broadcastMessages(List<?> messageObjects); @Override void routeMessage(Object message); @Override void registerBrokerMessageListener(Object listener, Class<?> msgType); @Override void setDeferredBroadcast(boolean b); @Override void broadcastDeferredMessages(); }### Answer:
@Test public void testSendMessage_multiple() { List<Object> messageList = new ArrayList<Object>(); messageList.add(message); messageList.add(new CustomerInfo("t2", 22)); messageList.add(new CustomerInfo("t3", 23)); brokerProxy.sendMessages(stdBroker, messageList); verify(template, times(0)).send(any(String.class), any(MessageCreator.class)); stdBroker.setEnabled(true); brokerProxy.sendMessages(stdBroker, messageList); verify(template, times(messageList.size())).send(any(String.class), any(MessageCreator.class)); } |
### Question:
BrokerProxyService implements BrokerProxy { @Override public void routeMessage (Object message) { if (router.route(message)) { if (!(message instanceof TariffSpecification)) { visualizerProxyService.forwardMessage(message); } } } BrokerProxyService(); @Override void sendMessage(Broker broker, Object messageObject); @Override void sendMessages(Broker broker, List<?> messageObjects); @Override void broadcastMessage(Object messageObject); @Override void broadcastMessages(List<?> messageObjects); @Override void routeMessage(Object message); @Override void registerBrokerMessageListener(Object listener, Class<?> msgType); @Override void setDeferredBroadcast(boolean b); @Override void broadcastDeferredMessages(); }### Answer:
@Test public void routeMessageTest() { when(router.route(message)).thenReturn(false); brokerProxy.routeMessage(message); verify(router, times(1)).route(message); verify(visualizer, times(0)).forwardMessage(message); reset(router); reset(visualizer); when(router.route(message)).thenReturn(true); brokerProxy.routeMessage(message); verify(router, times(1)).route(message); verify(visualizer, times(1)).forwardMessage(message); } |
### Question:
RegulationCapacity { public double getDownRegulationCapacity () { return downRegulationCapacity; } RegulationCapacity(TariffSubscription subscription,
double upRegulationCapacity,
double downRegulationCapacity); RegulationCapacity(); long getId(); TariffSubscription getSubscription(); double getUpRegulationCapacity(); double getDownRegulationCapacity(); }### Answer:
@Test public void testSetDown () { RegulationAccumulator rc = new RegulationAccumulator(1.0, -2.0); rc.setDownRegulationCapacity(-2.5); assertEquals(-2.5, rc.getDownRegulationCapacity(), 1e-6, "successful set"); rc.setDownRegulationCapacity(3.0); assertEquals(-2.5, rc.getDownRegulationCapacity(), 1e-6, "no change"); } |
### Question:
JobHistoryFileParserFactory { public static JobHistoryFileParser createJobHistoryFileParser( byte[] historyFileContents, Configuration jobConf) throws IllegalArgumentException { if (historyFileContents == null) { throw new IllegalArgumentException( "Job history contents should not be null"); } HadoopVersion version = getVersion(historyFileContents); switch (version) { case TWO: return new JobHistoryFileParserHadoop2(jobConf); default: throw new IllegalArgumentException( " Unknown format of job history file "); } } static HadoopVersion getVersion(byte[] historyFileContents); static JobHistoryFileParser createJobHistoryFileParser(
byte[] historyFileContents, Configuration jobConf); static HadoopVersion getHistoryFileVersion2(); static final String HADOOP2_VERSION_STRING; }### Answer:
@Test public void testCreateJobHistoryFileParserCorrectCreation() { String jHist2 = "Avro-Json\n" + "{\"type\":\"record\",\"name\":\"Event\", " + "\"namespace\":\"org.apache.hadoop.mapreduce.jobhistory\"," + "\"fields\":[]\""; JobHistoryFileParser historyFileParser = JobHistoryFileParserFactory .createJobHistoryFileParser(jHist2.getBytes(), null); assertNotNull(historyFileParser); assertTrue(historyFileParser instanceof JobHistoryFileParserHadoop2); }
@Test(expected = IllegalArgumentException.class) public void testCreateJobHistoryFileParserNullCreation() { JobHistoryFileParser historyFileParser = JobHistoryFileParserFactory .createJobHistoryFileParser(null, null); assertNull(historyFileParser); } |
### Question:
JobHistoryFileParserBase implements JobHistoryFileParser { public static double calculateJobCost(long mbMillis, double computeTco, long machineMemory) { if ((machineMemory == 0L) || (computeTco == 0.0)) { LOG.error("Unable to calculate job cost since machineMemory " + machineMemory + " or computeTco " + computeTco + " is 0; returning jobCost as 0"); return 0.0; } double jobCost = (mbMillis * computeTco) / (Constants.MILLIS_ONE_DAY * machineMemory); return jobCost; } protected JobHistoryFileParserBase(Configuration conf); Put getHadoopVersionPut(HadoopVersion historyFileVersion, byte[] jobKeyBytes); static long getXmxValue(String javaChildOptsStr); static long getXmxTotal(final long xmx75); static long getSubmitTimeMillisFromJobHistory(byte[] jobHistoryRaw); static double calculateJobCost(long mbMillis, double computeTco, long machineMemory); }### Answer:
@Test public void testCostDefault() { Double jobCost = JobHistoryFileParserBase.calculateJobCost(100L, 0.0, 0L); assertEquals(0.0, jobCost, 0.0001); jobCost = JobHistoryFileParserBase.calculateJobCost(100L, 20.0, 512L); assertEquals(1.413850E-10, jobCost, 0.0001); } |
### Question:
JobHistoryFileParserFactory { public static HadoopVersion getVersion(byte[] historyFileContents) { if(historyFileContents.length > HADOOP2_VERSION_LENGTH) { String version2Part = new String(historyFileContents, 0, HADOOP2_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version2Part, HADOOP2_VERSION_STRING)) { return HadoopVersion.TWO; } } throw new IllegalArgumentException(" Unknown format of job history file: " + historyFileContents); } static HadoopVersion getVersion(byte[] historyFileContents); static JobHistoryFileParser createJobHistoryFileParser(
byte[] historyFileContents, Configuration jobConf); static HadoopVersion getHistoryFileVersion2(); static final String HADOOP2_VERSION_STRING; }### Answer:
@Test public void testGetVersion() { String jHist2 = "Avro-Json\n" + "{\"type\":\"record\",\"name\":\"Event\", " + "\"namespace\":\"org.apache.hadoop.mapreduce.jobhistory\",\"fields\":[]\""; HadoopVersion version2 = JobHistoryFileParserFactory.getVersion(jHist2.getBytes()); assertEquals(JobHistoryFileParserFactory.getHistoryFileVersion2(), version2); }
@Test(expected = IllegalArgumentException.class) public void testGetVersionIncorrect2() { String jHist2 = "Avro-HELLO-Json\n" + "{\"type\":\"record\",\"name\":\"Event\", " + "\"namespace\":\"org.apache.hadoop.mapreduce.jobhistory\",\"fields\":[]\""; JobHistoryFileParserFactory.getVersion(jHist2.getBytes()); }
@Test(expected = IllegalArgumentException.class) public void testGetVersionIncorrect1() { String jHist1 = "Meta HELLO VERSION=\"1\" .\n" + "Job JOBID=\"job_201301010000_12345\""; JobHistoryFileParserFactory.getVersion(jHist1.getBytes()); } |
### Question:
JobDescFactory { public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(JOBTRACKER_KEY); } String cluster = null; if (jobtracker != null) { int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } cluster = Cluster.getIdentifier(jobtracker); } return cluster; } static JobDescFactoryBase getFrameworkSpecificJobDescFactory(Configuration jobConf); static JobDesc createJobDesc(QualifiedJobId qualifiedJobId,
long submitTimeMillis, Configuration jobConf); static Framework getFramework(Configuration jobConf); static String getCluster(Configuration jobConf); static final String JOBTRACKER_KEY; static final String RESOURCE_MANAGER_KEY; }### Answer:
@Test public void testCluster() { Cluster.loadHadoopClustersProps("testhRavenClusters.properties"); Configuration c = new Configuration(false); c.set(JobDescFactory.JOBTRACKER_KEY, "cluster1.identifier1.example.com:8021"); String result = JobDescFactory.getCluster(c); assertEquals("cluster1@identifier1", result); c = new Configuration(false); c.set(JobDescFactory.JOBTRACKER_KEY, "hbase-cluster2.identifier2.example.com:8021"); result = JobDescFactory.getCluster(c); assertEquals("hbase-cluster2@identifier2", result); c = new Configuration(false); c.set(JobDescFactory.RESOURCE_MANAGER_KEY, "cluster2.identifier2.example.com:10020"); result = JobDescFactory.getCluster(c); assertEquals("cluster2@identifier2", result); c = new Configuration(false); c.set(JobDescFactory.JOBTRACKER_KEY, ""); result = JobDescFactory.getCluster(c); assertNull(result); c = new Configuration(false); result = JobDescFactory.getCluster(c); assertNull(result); } |
### Question:
JobDescFactoryBase { public String getAppId(Configuration jobConf) { if (jobConf == null) { return Constants.UNKNOWN; } String appId = jobConf.get(Constants.APP_NAME_CONF_KEY); if (StringUtils.isBlank(appId)) { appId = jobConf.get(Constants.JOB_NAME_CONF_KEY); if (StringUtils.isNotBlank(appId)) { appId = getAppIdFromJobName(appId); } else { appId = jobConf.get(Constants.JOB_NAME_HADOOP2_CONF_KEY); if (StringUtils.isNotBlank(appId)) { appId = getAppIdFromJobName(appId); } } } return cleanAppId(appId); } JobDescFactoryBase(); String getAppId(Configuration jobConf); }### Answer:
@Test public void testgetAppId() { Configuration conf = new Configuration(); conf.set(Constants.APP_NAME_CONF_KEY, UNSAFE_NAME); assertEquals(SAFE_NAME, getAppId(conf)); }
@Test public void testgetAppIdHadoop2() { Configuration conf = new Configuration(); conf.set(Constants.JOB_NAME_CONF_KEY, ""); conf.set(Constants.APP_NAME_CONF_KEY, ""); conf.set(Constants.JOB_NAME_HADOOP2_CONF_KEY, "abc.def.xyz"); assertEquals("abc.def.xyz", getAppId(conf)); } |
### Question:
TaskKey extends JobKey implements Comparable<Object> { public String toString() { return super.toString() + Constants.SEP + getTaskId(); } @JsonCreator TaskKey(@JsonProperty("jobId") JobKey jobKey, @JsonProperty("taskId") String taskId); String getTaskId(); String toString(); @Override int compareTo(Object other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testToString() { JobKey jKey = new JobKey("test@local", "testuser", "app", 1234L, "job_20120101000000_1111"); TaskKey key = new TaskKey(jKey, "m_001"); String expected = jKey.toString() + Constants.SEP + "m_001"; assertEquals(expected, key.toString()); } |
### Question:
ByteArrayWrapper extends ByteArrayInputStream implements PositionedReadable, Seekable, Closeable { public synchronized long getPos() throws IOException { return pos; } ByteArrayWrapper(byte[] buf); synchronized void seek(long position); synchronized long getPos(); boolean seekToNewSource(long targetPos); synchronized int read(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer); }### Answer:
@Test public void testGetPos() throws IOException { ByteArrayWrapper wrapper = createInstance(16); final int length = 4; byte[] buf = new byte[length]; wrapper.read(buf); assertEquals(length, wrapper.getPos()); wrapper.close(); } |
### Question:
ByteArrayWrapper extends ByteArrayInputStream implements PositionedReadable, Seekable, Closeable { public synchronized void seek(long position) throws IOException { if (position < 0 || position >= count) { throw new IOException("cannot seek position " + position + " as it is out of bounds"); } pos = (int) position; } ByteArrayWrapper(byte[] buf); synchronized void seek(long position); synchronized long getPos(); boolean seekToNewSource(long targetPos); synchronized int read(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer); }### Answer:
@Test public void testSeek() throws IOException { ByteArrayWrapper wrapper = createInstance(16); final int position = 4; wrapper.seek(position); assertEquals(4, wrapper.getPos()); wrapper.close(); }
@Test(expected=IOException.class) public void testSeekNegative() throws IOException { ByteArrayWrapper wrapper = createInstance(16); wrapper.seek(-2); wrapper.close(); }
@Test(expected=IOException.class) public void testSeekOutOfBounds() throws IOException { ByteArrayWrapper wrapper = createInstance(16); wrapper.seek(20); wrapper.close(); } |
### Question:
ByteArrayWrapper extends ByteArrayInputStream implements PositionedReadable, Seekable, Closeable { public boolean seekToNewSource(long targetPos) throws IOException { return false; } ByteArrayWrapper(byte[] buf); synchronized void seek(long position); synchronized long getPos(); boolean seekToNewSource(long targetPos); synchronized int read(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer); }### Answer:
@Test public void testSeekToNewSource() throws IOException { ByteArrayWrapper wrapper = createInstance(16); assertFalse(wrapper.seekToNewSource(1234)); wrapper.close(); } |
### Question:
ByteArrayWrapper extends ByteArrayInputStream implements PositionedReadable, Seekable, Closeable { public synchronized int read(long position, byte[] buffer, int offset, int length) throws IOException { long oldPos = getPos(); int nread = -1; try { seek(position); nread = read(buffer, offset, length); } finally { seek(oldPos); } return nread; } ByteArrayWrapper(byte[] buf); synchronized void seek(long position); synchronized long getPos(); boolean seekToNewSource(long targetPos); synchronized int read(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer); }### Answer:
@Test public void testRead() throws IOException { byte[] array = createByteArray(16); ByteArrayWrapper wrapper = new ByteArrayWrapper(array); final long oldPosition = wrapper.getPos(); final long newPosition = 3; final int length = 4; byte[] buffer = new byte[length]; int read = wrapper.read(newPosition, buffer, 0, length); assertEquals(length, read); compareByteArrays(array, buffer, (int) newPosition); assertEquals(oldPosition, wrapper.getPos()); wrapper.close(); } |
### Question:
ByteArrayWrapper extends ByteArrayInputStream implements PositionedReadable, Seekable, Closeable { public synchronized void readFully(long position, byte[] buffer, int offset, int length) throws IOException { int nread = 0; while (nread < length) { int nbytes = read(position + nread, buffer, offset + nread, length - nread); if (nbytes < 0) { throw new EOFException("End of file reached before reading fully."); } nread += nbytes; } } ByteArrayWrapper(byte[] buf); synchronized void seek(long position); synchronized long getPos(); boolean seekToNewSource(long targetPos); synchronized int read(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer, int offset, int length); synchronized void readFully(long position, byte[] buffer); }### Answer:
@Test public void testReadFully() throws IOException { byte[] array = createByteArray(16); ByteArrayWrapper wrapper = new ByteArrayWrapper(array); final long oldPosition = wrapper.getPos(); final long newPosition = 3; final int length = 13; byte[] buffer = new byte[length]; wrapper.readFully(newPosition, buffer); compareByteArrays(array, buffer, (int) newPosition); assertEquals(oldPosition, wrapper.getPos()); wrapper.close(); } |
### Question:
HadoopConfUtil { public static boolean contains(Configuration jobConf, String name) { if (StringUtils.isNotBlank(jobConf.get(name))) { return true; } else { return false; } } static String getUserNameInConf(Configuration jobConf); static boolean contains(Configuration jobConf, String name); static String getQueueName(Configuration jobConf); }### Answer:
@Test public void testContains() throws FileNotFoundException { final String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; Configuration jobConf = new Configuration(); jobConf.addResource(new FileInputStream(JOB_CONF_FILE_NAME)); assertTrue(HadoopConfUtil.contains(jobConf, Constants.USER_CONF_KEY_HADOOP2)); assertFalse(HadoopConfUtil.contains(jobConf, Constants.USER_CONF_KEY)); } |
### Question:
HadoopConfUtil { public static String getUserNameInConf(Configuration jobConf) throws IllegalArgumentException { String userName = jobConf.get(Constants.USER_CONF_KEY_HADOOP2); if (StringUtils.isBlank(userName)) { userName = jobConf.get(Constants.USER_CONF_KEY); if (StringUtils.isBlank(userName)) { throw new IllegalArgumentException(" Found neither " + Constants.USER_CONF_KEY + " nor " + Constants.USER_CONF_KEY_HADOOP2); } } return userName; } static String getUserNameInConf(Configuration jobConf); static boolean contains(Configuration jobConf, String name); static String getQueueName(Configuration jobConf); }### Answer:
@Test public void testGetUserNameInConf() throws FileNotFoundException { final String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; Configuration jobConf = new Configuration(); jobConf.addResource(new FileInputStream(JOB_CONF_FILE_NAME)); String userName = HadoopConfUtil.getUserNameInConf(jobConf); assertEquals(userName, "user"); }
@Test(expected=IllegalArgumentException.class) public void checkUserNameAlwaysSet() throws FileNotFoundException { final String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; Configuration jobConf = new Configuration(); jobConf.addResource(new FileInputStream(JOB_CONF_FILE_NAME)); jobConf.set(Constants.USER_CONF_KEY_HADOOP2, ""); jobConf.set(Constants.USER_CONF_KEY, ""); String hRavenUserName = HadoopConfUtil.getUserNameInConf(jobConf); assertNull(hRavenUserName); } |
### Question:
HadoopConfUtil { public static String getQueueName(Configuration jobConf) { String hRavenQueueName = jobConf.get(Constants.QUEUENAME_HADOOP2); if (StringUtils.isBlank(hRavenQueueName)) { hRavenQueueName = jobConf .get(Constants.FAIR_SCHEDULER_POOLNAME_HADOOP1); if (StringUtils.isBlank(hRavenQueueName)) { hRavenQueueName = jobConf .get(Constants.CAPACITY_SCHEDULER_QUEUENAME_HADOOP1); if (StringUtils.isBlank(hRavenQueueName)) { hRavenQueueName = Constants.DEFAULT_QUEUENAME; LOG.info(" Found neither " + Constants.FAIR_SCHEDULER_POOLNAME_HADOOP1 + " nor " + Constants.QUEUENAME_HADOOP2 + " nor " + Constants.CAPACITY_SCHEDULER_QUEUENAME_HADOOP1 + " hence presuming FIFO scheduler " + " and setting the queuename to " + Constants.DEFAULT_QUEUENAME); } } } return hRavenQueueName; } static String getUserNameInConf(Configuration jobConf); static boolean contains(Configuration jobConf, String name); static String getQueueName(Configuration jobConf); }### Answer:
@Test public void testGetQueueName() throws FileNotFoundException { final String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; Configuration jobConf = new Configuration(); jobConf.addResource(new FileInputStream(JOB_CONF_FILE_NAME)); String queueName = HadoopConfUtil.getQueueName(jobConf); assertEquals(queueName, "default"); } |
### Question:
ByteUtil { public static double getValueAsDouble(byte[] key, NavigableMap<byte[], byte[]> infoValues) { byte[] value = infoValues.get(key); if (value != null) { return Bytes.toDouble(value); } else { return 0.0; } } static byte[][] split(byte[] source, byte[] separator); static byte[][] split(byte[] source, byte[] separator, int limit); static List<Range> splitRanges(byte[] source, byte[] separator); static List<Range> splitRanges(byte[] source, byte[] separator, int limit); static byte[] join(byte[] separator, byte[]... components); static int indexOf(byte[] array, byte[] target, int fromIndex); static byte[] safeCopy(byte[] source, int offset, int length); static long getValueAsLong(final byte[] key,
final Map<byte[], byte[]> taskValues); static String getValueAsString(final byte[] key,
final Map<byte[], byte[]> taskValues); static double getValueAsDouble(byte[] key,
NavigableMap<byte[], byte[]> infoValues); static int getValueAsInt(byte[] key, Map<byte[], byte[]> infoValues); }### Answer:
@Test public void testGetValueAsDouble() { NavigableMap<byte[], byte[]> infoValues = new TreeMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); double value = 34.567; double delta = 0.01; byte[] key = Bytes.toBytes("testingForDouble"); infoValues.put(key, Bytes.toBytes(value)); assertEquals(value, ByteUtil.getValueAsDouble(key, infoValues), delta); double expVal = 0.0; key = Bytes.toBytes("testingForDoubleNonExistent"); assertEquals(expVal, ByteUtil.getValueAsDouble(key, infoValues), delta); } |
### Question:
BatchUtil { public static boolean shouldRetain(int i, int maxRetention, int length) { int retentionCutoff = length - maxRetention; boolean retain = (i >= retentionCutoff) ? true : false; return retain; } static boolean shouldRetain(int i, int maxRetention, int length); static int getBatchCount(int length, int batchSize); static List<Range<E>> getRanges(Collection<E> collection,
int batchSize); }### Answer:
@Test public void testShouldRetain() { assertTrue(BatchUtil.shouldRetain(0, 1, 1)); assertTrue(BatchUtil.shouldRetain(5, 5, 10)); assertFalse(BatchUtil.shouldRetain(0, 1, 2)); assertFalse(BatchUtil.shouldRetain(4, 5, 10)); assertFalse(BatchUtil.shouldRetain(4, 100000, 155690)); } |
### Question:
BatchUtil { public static int getBatchCount(int length, int batchSize) { if ((batchSize < 1) || (length < 1)) { return 0; } int remainder = length % batchSize; return (remainder > 0) ? (length / batchSize) + 1 : (length / batchSize); } static boolean shouldRetain(int i, int maxRetention, int length); static int getBatchCount(int length, int batchSize); static List<Range<E>> getRanges(Collection<E> collection,
int batchSize); }### Answer:
@Test public void testGetBatchCount() { assertEquals(0, BatchUtil.getBatchCount(0,0)); assertEquals(0, BatchUtil.getBatchCount(-1,0)); assertEquals(0, BatchUtil.getBatchCount(-2,4)); assertEquals(0, BatchUtil.getBatchCount(5,-7)); assertEquals(1, BatchUtil.getBatchCount(9,9)); assertEquals(1, BatchUtil.getBatchCount(9,10)); assertEquals(1, BatchUtil.getBatchCount(9,11)); assertEquals(1, BatchUtil.getBatchCount(9,18)); assertEquals(1, BatchUtil.getBatchCount(9,19)); assertEquals(2, BatchUtil.getBatchCount(9,8)); assertEquals(2, BatchUtil.getBatchCount(9,7)); assertEquals(2, BatchUtil.getBatchCount(9,6)); assertEquals(2, BatchUtil.getBatchCount(9,5)); assertEquals(3, BatchUtil.getBatchCount(9,4)); assertEquals(3, BatchUtil.getBatchCount(9,3)); assertEquals(5, BatchUtil.getBatchCount(9,2)); assertEquals(9, BatchUtil.getBatchCount(9,1)); } |
### Question:
PigJobDescFactory extends JobDescFactoryBase { @Override String getAppIdFromJobName(String jobName) { if (jobName == null) { return null; } Matcher matcher = scheduledJobnamePattern.matcher(jobName); if (matcher.matches()) { jobName = SCHEDULED_PREFIX + matcher.group(1); } return jobName; } @Override JobDesc create(QualifiedJobId qualifiedJobId, long submitTimeMillis,
Configuration jobConf); static long getScriptStartTimeFromLogfileName(String pigLogfile); static final String SCHEDULED_PREFIX; }### Answer:
@Test public void testJobNameToBatchDesc() { PigJobDescFactory pigFactory = new PigJobDescFactory(); for (String[] inputOuput : testJobNames) { String input = inputOuput[0]; String expected = inputOuput[1]; String found = pigFactory.getAppIdFromJobName(input); assertEquals("Unexpected result found when parsing jobName=" + input, expected, found); } } |
### Question:
PigJobDescFactory extends JobDescFactoryBase { public static long getScriptStartTimeFromLogfileName(String pigLogfile) { long pigSubmitTimeMillis = 0; if (pigLogfile == null) { return pigSubmitTimeMillis; } Matcher matcher = pigLogfilePattern.matcher(pigLogfile); if (matcher.matches()) { String submitTimeMillisString = matcher.group(1); pigSubmitTimeMillis = Long.parseLong(submitTimeMillisString); } return pigSubmitTimeMillis; } @Override JobDesc create(QualifiedJobId qualifiedJobId, long submitTimeMillis,
Configuration jobConf); static long getScriptStartTimeFromLogfileName(String pigLogfile); static final String SCHEDULED_PREFIX; }### Answer:
@Test public void testLogFileToStartTime() { for (Object[] inputOuput : testLogFileNames) { String input = (String)inputOuput[0]; long expected = (Long)inputOuput[1]; long found = PigJobDescFactory.getScriptStartTimeFromLogfileName(input); assertEquals("Unexpected result found when parsing logFileName=" + input, expected, found); } } |
### Question:
FlowKey extends AppKey implements Comparable<Object> { public String toString() { return super.toString() + Constants.SEP + this.getRunId(); } @JsonCreator FlowKey(@JsonProperty("cluster") String cluster,
@JsonProperty("userName") String userName,
@JsonProperty("appId") String appId,
@JsonProperty("runId") long runId); FlowKey(FlowKey toCopy); long getEncodedRunId(); static long encodeRunId(long timestamp); long getRunId(); String toString(); @Override int compareTo(Object other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testToString() { FlowKey key = new FlowKey("c1@local", "auser", "app", 1345L); String expected = "c1@local" + Constants.SEP + "auser" + Constants.SEP + "app" + Constants.SEP + 1345L; assertEquals(expected, key.toString()); } |
### Question:
HdfsStatsKey implements Comparable<Object> { public static long getRunId(long encodedRunId) { return Long.MAX_VALUE - encodedRunId; } @JsonCreator HdfsStatsKey(@JsonProperty("cluster") String cluster,
@JsonProperty("path") String path,
@JsonProperty("encodedRunId") long encodedRunId); @JsonCreator HdfsStatsKey(@JsonProperty("cluster") String cluster,
@JsonProperty("path") String path,
@JsonProperty("namespace") String namespace,
@JsonProperty("encodedRunId") long encodedRunId); @JsonCreator HdfsStatsKey(@JsonProperty("pathKey") QualifiedPathKey pathKey,
@JsonProperty("encodedRunId") long encodedRunId); HdfsStatsKey(HdfsStatsKey key); static long getRunId(long encodedRunId); long getRunId(); QualifiedPathKey getQualifiedPathKey(); long getEncodedRunId(); boolean hasFederatedNS(); @Override String toString(); @Override int compareTo(Object other); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void testGetRunId() { long ts = 1392217200L; HdfsStatsKey key1 = new HdfsStatsKey(cluster1, path1, (Long.MAX_VALUE - ts)); assertEquals(key1.getRunId(), ts); } |
### Question:
AppKey implements Comparable<Object> { public String toString() { return getCluster() + Constants.SEP + getUserName() + Constants.SEP + getAppId(); } @JsonCreator AppKey(@JsonProperty("cluster") String cluster, @JsonProperty("userName") String userName,
@JsonProperty("appId") String appId); String getCluster(); String getUserName(); String getAppId(); String toString(); @Override int compareTo(Object other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testToString() { AppKey key = new AppKey("c1@local", "auser", "app"); String expected = "c1@local" + Constants.SEP + "auser" + Constants.SEP + "app"; assertEquals(expected, key.toString()); } |
### Question:
ScaldingJobDescFactory extends JobDescFactoryBase { String stripAppId(String origId) { if (origId == null || origId.isEmpty()) { return ""; } Matcher m = stripBracketsPattern.matcher(origId); String cleanedAppId = m.replaceAll(""); Matcher tailMatcher = stripSequencePattern.matcher(cleanedAppId); if (tailMatcher.matches()) { cleanedAppId = tailMatcher.group(1); } return cleanedAppId; } }### Answer:
@Test public void testStripAppId() throws Exception { ScaldingJobDescFactory factory = new ScaldingJobDescFactory(); assertEquals(expectedAppId1, factory.stripAppId(jobName1)); assertEquals(expectedAppId2, factory.stripAppId(jobName2)); assertEquals(expectedAppId3, factory.stripAppId(jobName3)); assertEquals(expectedAppId4, factory.stripAppId(jobName4)); assertEquals(expectedAppId5, factory.stripAppId(jobName5)); } |
### Question:
HdfsStatsService { public static long getEncodedRunId(long now) { long lastHour = now - (now % 3600); return (Long.MAX_VALUE - lastHour); } HdfsStatsService(Configuration hbaseConf, Connection hbaseConnection); static long getEncodedRunId(long now); List<HdfsStats> getAllDirs(String cluster, String pathPrefix,
int limit, long runId); static long getOlderRunId(int i, long runId); List<HdfsStats> getHdfsTimeSeriesStats(String cluster, String path,
int limit, long starttime, long endtime); }### Answer:
@Test public void TestGetLastHourInvertedTimestamp() throws IOException { long ts = 1391896800L; long expectedTop = Long.MAX_VALUE - ts; long actualTop = HdfsStatsService.getEncodedRunId(ts); assertEquals(actualTop, expectedTop); } |
### Question:
AppSummaryService { long getNumberRunsScratch(Map<byte[], byte[]> rawFamily) { long numberRuns = 0L; if (rawFamily != null) { numberRuns = rawFamily.size(); } if (numberRuns == 0L) { LOG.error("Number of runs in scratch column family can't be 0," + " if processing within TTL"); throw new ProcessingException("Number of runs is 0"); } return numberRuns; } AppSummaryService(Connection hbaseConnection); List<AppSummary> getNewApps(JobHistoryService jhs, String cluster,
String user, long startTime, long endTime, int limit); List<AppKey> createNewAppKeysFromResults(Scan scan, long startTime,
long endTime, int maxCount); boolean aggregateJobDetails(JobDetails jobDetails,
AggregationConstants.AGGREGATION_TYPE aggType); List<AppSummary> getAllApps(String cluster, String user,
long startTime, long endTime, int limit); }### Answer:
@Test(expected = ProcessingException.class) public void testGetNumberRuns() throws IOException { Map<byte[], byte[]> r = new HashMap<byte[], byte[]>(); AppSummaryService appSummaryService = new AppSummaryService(hbaseConnection); assertEquals(0, appSummaryService.getNumberRunsScratch(r)); byte[] key = Bytes.toBytes("abc"); byte[] value = Bytes.toBytes(10L); r.put(key, value); key = Bytes.toBytes("xyz"); value = Bytes.toBytes(102L); r.put(key, value); assertEquals(2, appSummaryService.getNumberRunsScratch(r)); } |
### Question:
AppSummaryService { String createQueueListValue(JobDetails jobDetails, String existingQueues) { String queue = jobDetails.getQueue(); queue = queue.concat(Constants.SEP); if (existingQueues == null) { return queue; } if (!existingQueues.contains(queue)) { existingQueues = existingQueues.concat(queue); } return existingQueues; } AppSummaryService(Connection hbaseConnection); List<AppSummary> getNewApps(JobHistoryService jhs, String cluster,
String user, long startTime, long endTime, int limit); List<AppKey> createNewAppKeysFromResults(Scan scan, long startTime,
long endTime, int maxCount); boolean aggregateJobDetails(JobDetails jobDetails,
AggregationConstants.AGGREGATION_TYPE aggType); List<AppSummary> getAllApps(String cluster, String user,
long startTime, long endTime, int limit); }### Answer:
@Test public void testCreateQueueListValue() throws IOException { JobDetails jd = new JobDetails(null); jd.setQueue("queue1"); byte[] qb = Bytes.toBytes("queue2!queue3!"); Cell existingQueuesCell = CellUtil.createCell(Bytes.toBytes("rowkey"), Constants.INFO_FAM_BYTES, Constants.HRAVEN_QUEUE_BYTES, HConstants.LATEST_TIMESTAMP, KeyValue.Type.Put.getCode(), qb); AppSummaryService appSummaryService = new AppSummaryService(hbaseConnection); String qlist = appSummaryService.createQueueListValue(jd, Bytes.toString(CellUtil.cloneValue(existingQueuesCell))); assertNotNull(qlist); String expQlist = "queue2!queue3!queue1!"; assertEquals(expQlist, qlist); jd.setQueue("queue3"); qlist = appSummaryService.createQueueListValue(jd, Bytes.toString(CellUtil.cloneValue(existingQueuesCell))); assertNotNull(qlist); expQlist = "queue2!queue3!"; assertEquals(expQlist, qlist); } |
### Question:
QualifiedPathKey implements Comparable<Object> { public String getNamespace() { return namespace; } QualifiedPathKey(String cluster, String path); QualifiedPathKey(String cluster, String path, String namespace); String getCluster(); String getPath(); String getNamespace(); @Override String toString(); @Override int compareTo(Object other); @Override int hashCode(); @Override boolean equals(Object other); boolean hasFederatedNS(); }### Answer:
@Test public void testConstructor1() throws Exception { QualifiedPathKey key1 = new QualifiedPathKey(cluster1, path1); testKeyComponents(key1); assertNull(key1.getNamespace()); }
@Test public void testConstructor2() throws Exception { QualifiedPathKey key1 = new QualifiedPathKey(cluster1, path1, namespace1); testKeyComponents(key1); assertNotNull(key1.getNamespace()); assertEquals(key1.getNamespace(), namespace1); } |
### Question:
JobHistoryFileParserBase implements JobHistoryFileParser { static String extractXmxValueStr(String javaChildOptsStr) { if (StringUtils.isBlank(javaChildOptsStr)) { LOG.info("Null/empty input argument to get xmxValue, returning " + Constants.DEFAULT_XMX_SETTING_STR); return Constants.DEFAULT_XMX_SETTING_STR; } final String JAVA_XMX_PREFIX = "-Xmx"; String[] xmxStr = javaChildOptsStr.split(JAVA_XMX_PREFIX); if (xmxStr.length >= 2) { String[] valuesStr = xmxStr[1].split(" "); if (valuesStr.length >= 1) { return valuesStr[0]; } else { LOG.info("Strange Xmx setting, returning default " + javaChildOptsStr); return Constants.DEFAULT_XMX_SETTING_STR; } } else { LOG.info("Xmx setting absent, returning default " + javaChildOptsStr); return Constants.DEFAULT_XMX_SETTING_STR; } } protected JobHistoryFileParserBase(Configuration conf); Put getHadoopVersionPut(HadoopVersion historyFileVersion, byte[] jobKeyBytes); static long getXmxValue(String javaChildOptsStr); static long getXmxTotal(final long xmx75); static long getSubmitTimeMillisFromJobHistory(byte[] jobHistoryRaw); static double calculateJobCost(long mbMillis, double computeTco, long machineMemory); }### Answer:
@Test public void testExtractXmxValue() { String jc = " -Xmx1024m -verbose:gc -Xloggc:/tmp/@[email protected]" ; String valStr = JobHistoryFileParserBase.extractXmxValueStr(jc); String expStr = "1024m"; assertEquals(expStr, valStr); }
@Test public void testExtractXmxValueIncorrectInput(){ String jc = " -Xmx" ; String valStr = JobHistoryFileParserBase.extractXmxValueStr(jc); String expStr = Constants.DEFAULT_XMX_SETTING_STR; assertEquals(expStr, valStr); } |
### Question:
QualifiedPathKey implements Comparable<Object> { @Override public int compareTo(Object other) { if (other == null) { return -1; } QualifiedPathKey otherKey = (QualifiedPathKey) other; if (StringUtils.isNotBlank(this.namespace)) { return new CompareToBuilder() .append(this.cluster, otherKey.getCluster()) .append(getPath(), otherKey.getPath()) .append(this.namespace, otherKey.getNamespace()) .toComparison(); } else { return new CompareToBuilder() .append(this.cluster, otherKey.getCluster()) .append(getPath(), otherKey.getPath()) .toComparison(); } } QualifiedPathKey(String cluster, String path); QualifiedPathKey(String cluster, String path, String namespace); String getCluster(); String getPath(); String getNamespace(); @Override String toString(); @Override int compareTo(Object other); @Override int hashCode(); @Override boolean equals(Object other); boolean hasFederatedNS(); }### Answer:
@Test public void testInEqualityWithNamespace() throws Exception { QualifiedPathKey key1 = new QualifiedPathKey(cluster1, path1, namespace1); QualifiedPathKey key2 = new QualifiedPathKey(cluster1, path1, namespace2); assertEquals(key1.compareTo(key2), -1); } |
### Question:
QualifiedPathKey implements Comparable<Object> { @Override public int hashCode() { return new HashCodeBuilder() .append(this.cluster) .append(this.path) .append(this.namespace) .toHashCode(); } QualifiedPathKey(String cluster, String path); QualifiedPathKey(String cluster, String path, String namespace); String getCluster(); String getPath(); String getNamespace(); @Override String toString(); @Override int compareTo(Object other); @Override int hashCode(); @Override boolean equals(Object other); boolean hasFederatedNS(); }### Answer:
@Test public void testNullHashCode() throws Exception { QualifiedPathKey key1 = new QualifiedPathKey(null, null); QualifiedPathKey key2 = new QualifiedPathKey(" ", " "); assertEquals(key1.hashCode(), key2.hashCode()); } |
### Question:
JobKey extends FlowKey implements Comparable<Object> { public String toString() { return super.toString() + Constants.SEP + this.jobId.getJobIdString(); } JobKey(String cluster, String userName, String appId, long runId,
String jobId); @JsonCreator JobKey(@JsonProperty("cluster") String cluster,
@JsonProperty("userName") String userName,
@JsonProperty("appId") String appId,
@JsonProperty("runId") long runId,
@JsonProperty("jobId") JobId jobId); JobKey(QualifiedJobId qualifiedJobId, String userName, String appId,
long runId); JobKey(JobDesc jobDesc); QualifiedJobId getQualifiedJobId(); JobId getJobId(); String toString(); @Override int compareTo(Object other); @Override boolean equals(Object other); @Override int hashCode(); }### Answer:
@Test public void testToString() { JobKey key = new JobKey("c1@local", "auser", "app", 1345L, "job_20120101000000_0001"); String expected = "c1@local" + Constants.SEP + "auser" + Constants.SEP + "app" + Constants.SEP + 1345L + Constants.SEP + "job_20120101000000_0001"; assertEquals(expected, key.toString()); } |
### Question:
PardResultSet implements Serializable { public ResultStatus getStatus() { return resultStatus; } PardResultSet(); PardResultSet(ResultStatus resultStatus); PardResultSet(ResultStatus resultStatus, String msg); PardResultSet(ResultStatus resultStatus, List<Column> schema); PardResultSet(ResultStatus resultStatus, List<Column> schema, int capacity); void addResultSet(PardResultSet resultSet); void addBlock(Block block); List<Row> getRows(); void setJdbcResultSet(ResultSet jdbcResultSet); void setJdbcConnection(Connection connection); ResultStatus getStatus(); void setSchema(List<Column> schema); List<Column> getSchema(); String getTaskId(); void setTaskId(String taskId); boolean add(Row row); Row getNext(); long getExecutionTime(); void setExecutionTime(long executionTime); String getSemanticErrmsg(); void setSemanticErrmsg(String semanticErrmsg); @Override String toString(); static final PardResultSet okResultSet; static final PardResultSet execErrResultSet; static final PardResultSet eorResultSet; }### Answer:
@Test public void testEnum() { PardResultSet r = PardResultSet.okResultSet; if (r.getStatus() == PardResultSet.ResultStatus.OK) { System.out.println("Y"); } else { System.out.println("N"); } } |
### Question:
PardClient { public static void main(String[] args) { if (args.length != 2) { System.out.println("PardClient <host> <port>"); System.exit(-1); } String host = args[0]; int port = Integer.parseInt(args[1]); System.out.println("Connecting to " + host + ":" + port); try { PardClient client = new PardClient(host, port); client.run(); } catch (IOException e) { e.printStackTrace(); } } PardClient(String host, int port); void run(); static void main(String[] args); }### Answer:
@Test public void testClient() { String host = "10.77.40.31"; int port = 11013; String[] args = {host, port + ""}; PardClient.main(args); } |
### Question:
SemanticAnalysis { public Plan analysis(Statement stmt) { return null; } Plan analysis(Statement stmt); }### Answer:
@Test public void analysis() { String sql = "SELECT * FROM test0"; Statement statement = parser.createStatement(sql); if (statement instanceof Query) { Query q = (Query) statement; System.out.println("it is a query"); System.out.println(q.toString()); List<? extends Node> children = q.getChildren(); System.out.println("children:"); for (Node n : children) { System.out.println(n.toString()); } PlanNode node = parseQuery(q); if (q.getOrderBy().isPresent()) { node = parseOrderBy(node, q.getOrderBy().get()); } } System.out.println(statement.toString()); } |
### Question:
Path implements PathLike { @Override public boolean can(Map<String, Object> vars) throws CoreModuleException { if (StringUtils.isBlank(expr)) { return true; } else { try { return MvelUtils.evalToBoolean(expr, vars); } catch (Exception e) { throw new CoreModuleException("未传入context中相应的表达式(expr)!\n" + e.getMessage(), e); } } } Path(String initTo, String expr); @Override boolean can(Map<String, Object> vars); @Override String to(); public String initTo; public String expr; }### Answer:
@Test public void testCan() { Path path = new Path("to", "true"); try { Assert.assertTrue(path.can(null)); } catch (CoreModuleException e) { e.printStackTrace(); } Path path1 = new Path("to", "param == 1"); Map m = new HashMap(); m.put("param", 1); try { Assert.assertTrue(path1.can(m)); } catch (CoreModuleException e) { e.printStackTrace(); } Path path2 = new Path("to", "if (param == \"123\") {true} else {false}"); Map m1 = new HashMap(); m1.put("param", "123"); try { Assert.assertTrue(path2.can(m1)); } catch (CoreModuleException e) { e.printStackTrace(); } Path path3 = new Path("to", null); try { Assert.assertTrue(path3.can(null)); } catch (CoreModuleException e) { e.printStackTrace(); } Path path4 = new Path("to", "null"); try { Assert.assertFalse(path4.can(null)); } catch (CoreModuleException e) { e.printStackTrace(); } } |
### Question:
Parser implements BaseParser { public Document getXML(String processName, @SuppressWarnings("UnusedParameters") int processVersion) { SAXReader reader = new SAXReader(); URL url = this.getClass().getResource("/" + processName.replaceAll("\\.", "/") + ".xml"); Document document; try { document = reader.read(url); } catch (Exception e) { logger.error("xml流程文件读取失败!模板名:" + processName); throw new NullPointerException("xml流程文件读取失败!模板名:" + processName + "\n" + e); } return document; } @Override boolean needRefresh(String processName, int processVersion, Definition oldDefinition); @Override Definition parse(String processName, int processVersion); Definition parser0(String name, int version, Document processXML, boolean status); Document getXML(String processName, @SuppressWarnings("UnusedParameters") int processVersion); static Map<String, StateAround> stateLifeMap; }### Answer:
@Test public void testGetXML() { System.out.println(parser.getXML("process", 0)); } |
### Question:
Parser implements BaseParser { @Override public Definition parse(String processName, int processVersion) { Document processXML = getXML(processName, processVersion); return parser0(processName, 1, processXML, true); } @Override boolean needRefresh(String processName, int processVersion, Definition oldDefinition); @Override Definition parse(String processName, int processVersion); Definition parser0(String name, int version, Document processXML, boolean status); Document getXML(String processName, @SuppressWarnings("UnusedParameters") int processVersion); static Map<String, StateAround> stateLifeMap; }### Answer:
@Test public void testParse() { StateFactory.applyState(Start.class); StateFactory.applyState(State.class); StateFactory.applyState(Event.class); StateFactory.applyState(BizInfo.class); InvokableFactory.applyInvokable(MvelScriptInvokable.class); Definition definition = parser.parse("process", 0); BizInfo bizInfo = definition.getExtNode(BizInfo.class); Assert.assertNotNull(bizInfo); for (BizInfo.BizInfoElement e : bizInfo.getBizInfoList("r")) { Assert.assertEquals("r", e.getAttribute("key")); Assert.assertTrue(e.getAttribute("value").startsWith("r")); System.out.println(e.getAttribute("key") + " -> " + e.getAttribute("value")); } } |
### Question:
CheckerWithException { public int checkValue(final int amount) { if (amount == 0) { throw new IllegalArgumentException("value is 0"); } return 0; } int checkValue(final int amount); }### Answer:
@Test public void checkValueTerseWay() throws Exception { try { checkerWithException.checkValue(0); fail("Expected exception for zero length"); } catch (IllegalArgumentException e) { assertTrue("expected", true); } }
@Test(expected = IllegalArgumentException.class) public void checkValueTerseWay2() throws Exception { checkerWithException.checkValue(0); }
@Test public void checkValueBetterWay() throws Exception { assertThrows(IllegalArgumentException.class, () -> checkerWithException.checkValue(0)); } |
### Question:
ParallelProcessor implements AutoCloseable, BatchIterator<R> { @Override public long skip(long count) { long skipped = 0; while (skipped < count) { try { if (!ensureBuffer()) { return skipped; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new UncheckedInterruptedException(e); } int toSkip = (int) Math.min(count - skipped, _currentResult._length - _currentResultIndex); Arrays.fill(_currentResult._data, _currentResultIndex, _currentResultIndex + toSkip, null); _currentResultIndex += toSkip; skipped += toSkip; } assert skipped == count; return skipped; } ParallelProcessor(Config config); private ParallelProcessor(int readerThreadPriority, int processorThreads, int processorThreadPriority,
int batchSize, int inputBufferSize, int outputBufferSize); R nextInterruptable(); @Override boolean hasNext(); @Override R next(); @Override int next(R[] destination, int offset, int count); @Override long skip(long count); BlockingStatus getBlockingStatus(); @Override long available(); @Override void close(); void start(); }### Answer:
@Test public void skipTest() throws InterruptedException { DummyProcessor dp = new DummyProcessor(false); for (int i = 0; i < 10000; i += 5) { Integer res = dp.nextInterruptable(); assertEquals(i, (int) res); dp.skip(4); } } |
### Question:
VirtualExecutorService extends AbstractExecutorService { @Override public List<Runnable> shutdownNow() { synchronized (_pendingLock) { _stage = STAGE_SHUTDOWN_NOW; for (Thread pending : LinkedNode.values(_pendingThreads)) { pending.interrupt(); } return LinkedNode.values(_pendingRunnables); } } VirtualExecutorService(Executor executor); @Override void shutdown(); @Override List<Runnable> shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit); @Override void execute(Runnable command); }### Answer:
@Test public void shutdownNowTest() throws InterruptedException, ExecutionException { ExecutorService baseExecutor = Executors.newFixedThreadPool(4); VirtualExecutorService virtualExecutor = new VirtualExecutorService(baseExecutor); for (int i = 0; i < 10; i++) { virtualExecutor.submit(Interrupted.unchecked(() -> { while (true) { Thread.sleep(Long.MAX_VALUE); } })); } Thread.sleep(100); List<Runnable> list = virtualExecutor.shutdownNow(); Assert.assertEquals(6, list.size()); virtualExecutor.awaitTermination(10, TimeUnit.SECONDS); Assert.assertTrue(virtualExecutor.isTerminated()); Assert.assertFalse(baseExecutor.isTerminated()); try { virtualExecutor.submit(() -> 5); Assert.fail(); } catch (RejectedExecutionException e) { } catch (Exception e) { Assert.fail(); } Assert.assertEquals((int) (baseExecutor.submit(() -> 8).get()), 8); } |
### Question:
LRUCache { public LRUCache(int capacity) { this.capacity = capacity; map = new HashMap<>(); head = new Node(-1, -1); tail = new Node(-1, -1); head.next = tail; tail.prev = head; } LRUCache(int capacity); Integer lookup(Integer key); Integer insert(Integer key, Integer value); Integer remove(Integer key); }### Answer:
@Test public void lruCache() { final int capacity = 8; final Map<Integer, Integer> map = new HashMap<>(); final List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); final LRUCache cache = new LRUCache(capacity); list.forEach(i -> { cache.insert(i, i); }); assertNull(cache.lookup(1)); assertNull(cache.lookup(2)); assertEquals(list.get(2), cache.lookup(3)); cache.insert(1, 1); assertNull(cache.lookup(4)); cache.remove(1); assertNull(cache.lookup(1)); } |
### Question:
MySimilarity extends DefaultSimilarity { @Override public float lengthNorm(String fieldName, int numTerms) { if (numTerms < 20) { if (numTerms <= 0) return 0; return -0.00606f * numTerms + 0.35f; } return (float) (1.0 / Math.sqrt(numTerms)); } @Override float lengthNorm(String fieldName, int numTerms); }### Answer:
@Test public void testLengthNorm() { MySimilarity s = new MySimilarity(); assertEquals(0, s.lengthNorm("test", 0), 1e-6); assertEquals(0.289400, s.lengthNorm("test", 10), 1e-6); assertEquals(0.234860, s.lengthNorm("test", 19), 1e-6); assertEquals(0.223606, s.lengthNorm("test", 20), 1e-6); } |
### Question:
CircularArraySequence implements Sequence { @Override public Object peekHead() { return backingArray[front]; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testPeekHead() { assertEquals("Peek should return null for empty sequence", null, seq.peekHead()); seq.append("a"); assertEquals("Peeking at head did not return correct value", "a", seq.peekHead()); seq.append("b"); assertEquals("Peeking at head after appending 2 things did not return correct value", "a", seq.peekHead()); seq.prepend("x"); assertEquals("x", seq.peekHead()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Object peekLast() { if (rear==0){ if (backingArray[backingArray.length-1]==null){ return backingArray[rear]; } else{ return backingArray[backingArray.length-1]; } } return backingArray[rear-1]; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testPeekLast() { assertEquals("Peek last should return null if empty", null, seq.peekLast()); seq.append("a"); assertEquals("Peek last returns wrong value for 1 element", "a", seq.peekLast()); seq.append("b"); assertEquals("Peek last returns wrong value for 2 elements", "b", seq.peekLast()); seq.append("x"); assertEquals("Peek last returns wrong value for multiple elements","x", seq.peekLast()); seq.append("z"); seq.prepend("D"); seq.prepend("C"); seq.last(); seq.last(); seq.last(); seq.last(); seq.last(); assertEquals("Peek doesn't wrap past zero", "C", seq.peekLast()); } |
### Question:
CircularArraySequence implements Sequence { @Override public void prepend(Object element) { if (backingArray[front] != null && front == 0){ backingArray[backingArray.length-1] = (T)element; front = backingArray.length-1; fillCount+=1; if (fullCheck()==true){ regrow(); } } else if(backingArray[front] == null){ backingArray[front] = (T)element; fillCount +=1; rear+=1; if (fullCheck()==true){ regrow(); } } else if(backingArray[front] != null){ backingArray[front-1] = (T)element; front-=1; fillCount+=1; if (fullCheck()==true){ regrow(); } } } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testPrepend() { seq.append("x"); seq.prepend("a"); assertEquals("Prepend did not put new item in front", "a", seq.peekHead()); assertEquals("Length of sequence wrong after prepend", 2, seq.length()); seq.prepend("b"); assertEquals("Prepend did not put new item in front on second call", "b", seq.peekHead()); seq.prepend("c"); assertEquals("Prepend did not put new item in front on third call", "c", seq.peekHead()); assertEquals("Length of prepend sequence incorrect", 4, seq.length()); assertEquals("ToString value of sequence incorrect after prepends", "cbax" , seq.toString()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Sequence tail() { CircularArraySequence<T> tempSequence = new CircularArraySequence<T>(this); if (backingArray[front]!=null){ tempSequence.backingArray[front] = null; tempSequence.fillCount-=1; if (front == backingArray.length-1){ tempSequence.front = 0; } else{ tempSequence.front+=1; } } return tempSequence; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testTail() { Sequence<String> seq2 = seq.tail(); assertTrue("empty sequence tail should empty seq", seq2.isEmpty()); seq.append("a"); seq.append("b"); seq.append("c"); seq.append("d"); seq.append("e"); Sequence<String> seq1 = seq.tail(); assertEquals("Length of tail sequence incorrect", 4 , seq1.length()); assertEquals("Head of tail sequence incorrect", "b", seq1.peekHead()); assertEquals("Last element of tail sequence incorrect", "e", seq1.peekLast()); assertEquals("Length of original sequence changed when taking tail", 5, seq.length()); assertEquals("Original sequence head changed when taking tail", "a", seq.peekHead()); assertEquals("Original sequence last changed when taking tail", "e", seq.peekLast()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Iterator<T> iterator() { SequenceIterator<T> iterator = new SequenceIterator<T>(this); return iterator; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testIterator() { Iterator<String> ite = seq.iterator(); assertFalse("Empty sequence iterator not empty", ite.hasNext()); seq.append("a"); seq.append("b"); seq.append("c"); Iterator<String> it = seq.iterator(); assertTrue("Iterator over data thinks it is empty", it.hasNext()); assertEquals("Iterator did not return correct element at first", "a", it.next()); assertEquals("Iterator did not return correct second element", "b", it.next()); assertEquals("Iterator did not return correct third element", "c", it.next()); assertFalse("Iterator should not have anything left, but think it does", it.hasNext()); assertEquals("Original sequence length modified after iterator", 3 , seq.length()); } |
### Question:
CircularArraySequence implements Sequence { @Override public int length() { return fillCount; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testLength() { assertEquals("Length of the new sequence not zero", 0, seq.length()); seq.append("a"); assertEquals("Length after 1 append not 1", 1, seq.length()); seq.prepend("b"); assertEquals("Length after 2 appends not 2", 2, seq.length()); seq.last(); seq.last(); assertEquals("Length after removing 2 things from a 2 element seq not zero", 0, seq.length()); } |
### Question:
CircularArraySequence implements Sequence { public String toString(){ String stringSeq = ""; boolean halt = false; int index = front; while (halt == false){ if (index == backingArray.length){ index = 0; } if (index == rear){ halt = true; } else{ stringSeq = stringSeq + backingArray[index].toString(); index += 1; } } return stringSeq; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testToString() { assertEquals("To string of empty sequence wrong", "",seq.toString()); seq.append("a"); seq.append("b"); seq.append("c"); assertEquals("ToString of 3 element seq wrong", "abc", seq.toString()); seq.prepend("d"); seq.prepend("e"); seq.prepend("f"); assertEquals("toString of 6 element seq wrong", "fedabc", seq.toString()); } |
### Question:
CircularArraySequence implements Sequence { private void regrow(){ T[] tempArray = (T[])new Object[backingArray.length*2]; for (int i=0;i<backingArray.length;i++){ tempArray[i] = backingArray[i]; } int tempfillCount = fillCount; int index = front; int newIndex = 0; while (tempfillCount!=0){ if (index == backingArray.length){ index = 0; } tempArray[newIndex]=backingArray[index]; index += 1; tempfillCount-=1; } front = 0; rear = fillCount; backingArray = tempArray; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testRegrow() { for(int i=0; i < 15 ; i++) seq.append("a"); seq.prepend("e"); seq.append("x"); assertEquals("Error on regrow", 17, seq.length()); assertEquals("Head wrong after regrow", "e", seq.peekHead()); assertEquals("Last wrong after regrow", "x" , seq.peekLast()); assertEquals("String rep wrong on regrow", "eaaaaaaaaaaaaaaax", seq.toString()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public boolean isEmpty() { if (root==null){ return true; } return false; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testIsEmpty() { assertTrue("Empty tree did not return true", tree.isEmpty()); tree.add(20, "S"); avlTree.add(20, "S"); assertFalse("Tree thinks its empty after one insert", tree.isEmpty()); assertFalse("AVL Tree thinks its empty after one insert", avlTree.isEmpty()); tree.add(30, "X"); tree.remove(30); assertFalse("Tree thinks its empty after one remove", tree.isEmpty()); tree.remove(20); assertTrue("Tree thinks it still has something after removal", tree.isEmpty()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public int size() { int size = 0; if (root==null){ return 0; } if (root.getLeft()==null && root.getRight()==null){ return 1; } if (root.getLeft()!=null){ size+= 1+size(root.getLeft()); } if (root.getRight()!=null){ size+= 1+size(root.getRight()); } return size; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testSize() { assertEquals("Size of new tree not 0", 0, tree.size()); tree.add(20, "S"); assertEquals("Size after 1 insert wrong", 1, tree.size()); tree.remove(20); assertEquals("Size after last remove not 0", 0, tree.size()); for (int i = 0; i < 10 ; i++) { tree.add(i + i, "S"); } assertEquals("Size after multiple inserts wrong", 10, tree.size()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public K min() { opsCount++; if (root==null){ return null; } else { return min(root,root.key); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testMin() { assertNull("Empty tree min was not null", tree.min()); tree.add(20, "LD"); assertEquals("One element tree min wrong", (Integer) 20, tree.min()); tree.add(30, "df"); tree.add(15, "kjd"); tree.add(10, "kjdf"); tree.add(5, "kdjf"); tree.add(1, "esd"); assertEquals("Multi-element tree min wrong", (Integer) 1, tree.min()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public K max() { opsCount++; if (root==null){ return null; } else { return max(root,root.key); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testMax() { assertNull("Empty tree max was not null", tree.max()); tree.add(20, "SS"); assertEquals("One element tree max wrong", (Integer) 20, tree.max()); tree.add(30, "SS"); tree.add(35, "LL"); tree.add(40, "JJ"); tree.add(37, "df"); tree.add(36, "wer"); assertEquals("Multi-element tree max wrong", (Integer) 40, tree.max()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public V find(K key) { opsCount++; if (root==null){ return null; } else if (key.compareTo(root.key)==0){ return root.data; } else if (key.compareTo(root.key)<0){ return find(root.getLeft(),key); } else{ return find(root.getRight(),key); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testFind() { assertNull(tree.find(40)); tree.add(20, "s"); tree.add(10, "c"); assertEquals("s", tree.find(20)); assertEquals("c", tree.find(10)); tree.add(30, "x"); assertEquals("x", tree.find(30)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public int height() { if (root==null){ return -1; } else { return root.getHeight(); } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testHeight() { assertEquals("Height of empty tree wrong", -1, tree.height()); tree.add(20, "lk"); assertEquals("Height wrong for 1 entry", 0, tree.height()); tree.add(1, "lkd"); assertEquals("Height wrong for 2 entry", 1, tree.height()); tree.add(5, "ksjdf"); tree.add(28, "skdjf"); tree.add(32, "sd"); tree.add(30, "d"); tree.add(40, "zz"); assertEquals("Height wrong for mult entries", 3, tree.height()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public K root() { if (root==null){ return null; } else{ return root.key; } } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testRoot() { assertNull(tree.root()); tree.add(20, "dd"); assertEquals((Integer) 20, tree.root()); tree.remove(20); assertNull(tree.root()); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> preorderTraversal() { List<K> keyList = new ArrayList<K>(); preorderTraversal(root,keyList); return keyList; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testPreorderTraversal() { List<Integer> list = tree.preorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.preorderTraversal(); System.out.println("Pre: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 13, list.get(0) ); assertEquals((Integer) 9,list.get(1)); assertEquals((Integer) 5 , list.get(2)); assertEquals((Integer) 26, list.get(8)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> postorderTraversal() { List<K> keyList = new ArrayList<K>(); postorderTraversal(root,keyList); return keyList; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testPostorderTraversal() { List<Integer> list = tree.postorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.postorderTraversal(); System.out.println("Post: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 1, list.get(0) ); assertEquals((Integer) 6,list.get(1)); assertEquals((Integer) 5, list.get(2)); assertEquals((Integer) 13, list.get(8)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> inorderTraversal() { List<K> keyList = new ArrayList<K>(); inorderTraversal(root,keyList); return keyList; } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testInorderTraversal() { List<Integer> list = tree.inorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.inorderTraversal(); System.out.println("In: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 1, list.get(0) ); assertEquals((Integer) 5,list.get(1)); assertEquals((Integer) 6, list.get(2)); assertEquals((Integer) 26, list.get(8)); } |
### Question:
AVLTreeImpl implements IAVLBinaryTree<K, V> { @Override public List<K> levelorderTraversal() { List<K> keyList = new ArrayList<K>(); return levelorderTraversal(root,keyList); } AVLTreeImpl(boolean rotate); void resetOpsCount(); int getOpsCount(); @Override boolean isEmpty(); @Override int size(); @Override void add(K key, V data); @Override boolean remove(K key); @Override K min(); @Override K max(); @Override int height(); @Override K root(); @Override BSTNode<K,V> getRootNode(); @Override V find(K key); @Override List<K> preorderTraversal(); @Override List<K> postorderTraversal(); @Override List<K> inorderTraversal(); @Override List<K> levelorderTraversal(); static void main(String[] args); }### Answer:
@Test public void testLevelorderTraversal() { List<Integer> list = tree.levelorderTraversal(); assertTrue(list.isEmpty()); tree.add(13, "sdf"); tree.add(9, "wer"); tree.add(16,"sdxv"); tree.add(5, "wer"); tree.add(10, "sdf"); tree.add(1, "werf"); tree.add(6, "pk"); tree.add(14, "nn"); tree.add(26, "dd"); list = tree.levelorderTraversal(); System.out.println("Level: " + list.toString()); assertEquals("Wrong number of elements", 9 , list.size()); assertEquals("First element wrong", (Integer) 13, list.get(0) ); assertEquals((Integer) 9,list.get(1)); assertEquals((Integer) 16, list.get(2)); assertEquals((Integer) 6, list.get(8)); } |
### Question:
SparseArray2DImpl implements ISparseArray2D<T> { @Override public void putAt(int row, int col, T value) throws ArrayIndexOutOfBoundsException { if (row>this.row || col>column){ throw new ArrayIndexOutOfBoundsException(); } else{ IndexNode rowNode = checkForIndex(rowLinkedList,row); IndexNode colNode = checkForIndex(colLinkedList, col); if (rowNode==null){ rowLinkedList.add(row); rowNode = checkForIndex(rowLinkedList,row); } if (colNode==null){ colLinkedList.add(col); colNode = checkForIndex(colLinkedList, col); } ArrayNode<T> arrayNode = insertInRow(row,col,value,rowNode); insertInCol(row,col,colNode,arrayNode); } } SparseArray2DImpl(int row, int column); @Override void putAt(int row, int col, T value); @Override T removeAt(int row, int col); @Override T getAt(int row, int col); @Override List<T> getRowFor(int row); @Override List<T> getColumnFor(int col); }### Answer:
@Test public void testPutAt() { try { array.putAt(10001, 1, "K"); assertTrue("Failed to detect row out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } try { array.putAt(1, 10001, "K"); assertTrue("Failed to detect col out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } array.putAt(10, 100, "C"); array.putAt(30, 140, "D"); assertEquals("Returned element is wrong", "C", array.getAt(10, 100)); assertEquals("Returned element is wrong", "D", array.getAt(30, 140)); array.putAt(10, 100, "Z"); assertEquals("The overwritten value of a cell is wrong", array.getAt(10, 100), "Z"); } |
### Question:
CircularArraySequence implements Sequence { @Override public Sequence<T> concat(Sequence seq) { CircularArraySequence<T> sequence1 = new CircularArraySequence<T>(this); CircularArraySequence<T> sequence2 = new CircularArraySequence<T>((CircularArraySequence<T>)seq); boolean halt = false; int index = sequence2.front; while (halt == false){ if (index == backingArray.length){ index = 0; } if (index == sequence2.rear){ halt = true; } else{ sequence1.append(sequence2.backingArray[index]); index += 1; } } return sequence1; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testConcat() { seq.append("a"); seq.append("b"); seq.append("c"); Sequence<String> seq2 = new CircularArraySequence<String>(10); seq2.append("x"); seq2.append("y"); Sequence<String> seq3 = seq.concat(seq2); assertEquals(5, seq3.length()); assertEquals("a", seq3.peekHead()); assertEquals("y", seq3.peekLast()); } |
### Question:
CircularArraySequence implements Sequence { @Override public Object head() { CircularArraySequence<T> tempSequence = new CircularArraySequence<T>(this); T firstObj = null; if (front == 0 || backingArray[front]==null){ if (backingArray[front]==null){ firstObj = null; } else{ firstObj = tempSequence.backingArray[front]; backingArray[front] = null; front+=1; fillCount-=1; } } else if (front == backingArray.length-1){ firstObj = tempSequence.backingArray[backingArray.length-1]; backingArray[backingArray.length-1] = null; front = 0; fillCount-=1; } else{ firstObj = tempSequence.backingArray[front]; backingArray[front] = null; front+=1; fillCount-=1; } return firstObj; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testHead() { assertTrue("New sequence not reporting its empty", seq.isEmpty()); assertEquals("Head of the new sequence not null", null, seq.head()); seq.append("a"); assertEquals("Head returned incorrect when one element", "a", seq.head()); assertEquals("Head returned incorrect when no element", null, seq.head()); seq.append("s"); seq.append("r"); seq.append("t"); seq.append("i"); assertEquals("Head returned incorrect value after several appends", "s", seq.head()); seq.last(); assertEquals("After removing last element, the head changed", "r", seq.head()); } |
### Question:
CircularArraySequence implements Sequence { @Override public boolean isEmpty() { if (fillCount>0){ return false; } return true; } CircularArraySequence(int size); CircularArraySequence(CircularArraySequence<T> seq); @Override Object head(); @Override Object last(); @Override Sequence front(); @Override Sequence tail(); @Override Sequence<T> concat(Sequence seq); @Override boolean contains(Sequence subseq); @Override boolean contains(Object element); @Override void append(Object element); @Override void prepend(Object element); @Override boolean isEmpty(); @Override Object peekHead(); @Override Object peekLast(); @Override boolean equals(Sequence seq); @Override int length(); @Override Iterator<T> iterator(); String toString(); }### Answer:
@Test public void testIsEmpty() { assertTrue(seq.isEmpty()); seq.append("A"); assertFalse(seq.isEmpty()); seq.last(); assertTrue(seq.isEmpty()); } |
### Question:
SemiStructureTokenizer extends Tokenizer { private void setStructireInfo(Reader input) { SemistructuredFormulaParser formulaParser = new SemistructuredFormulaParser(input); try { ChemSubStructure structure = formulaParser.parse(); Stack<DFSStackEntry> stack = new Stack<DFSStackEntry>(); stack.push(new DFSStackEntry(structure,1)); while (!stack.isEmpty()) { DFSStackEntry currentEntry = stack.pop(); ChemSubStructure current = currentEntry.subStructure; int multiplier = currentEntry.multiplier; if (current instanceof Element) { mapFragmentsChains(((Element) current).subFormula, multiplier); } else if (current instanceof ElementaryGroup) { mapFragmentsChains(((ElementaryGroup) current).subFormula, multiplier); } else if (current instanceof Group) { ChemSubStructure containedSubStructure = ((Group)current).containedSubStructure; stack.push(new DFSStackEntry(containedSubStructure, multiplier)); } else if (current instanceof Term) { Term asTerm = ((Term)current); stack.push(new DFSStackEntry(asTerm.subStrucure, multiplier * asTerm.multiplier)); } else if (current instanceof Formula) { for (ChemSubStructure subStructure : ((Formula) current).subStructures) { stack.push(new DFSStackEntry(subStructure, multiplier) ); } } } currentIterator = fragmentsCounts.entrySet().iterator(); currentCount = 0; } catch (ParseException e) { throw new RuntimeException(e); } } protected SemiStructureTokenizer(Reader input); protected SemiStructureTokenizer(AttributeFactory factory, Reader input); @Override final boolean incrementToken(); }### Answer:
@Test public void testSetStructireInfo() { Reader reader = new StringReader("C2H5OH"); SemiStructureTokenizer tokenizer = new SemiStructureTokenizer(reader); assertTrue(tokenizer.fragmentsCounts.containsKey("C")); assertTrue(tokenizer.fragmentsCounts.containsKey("C-C")); assertTrue(tokenizer.fragmentsCounts.containsKey("O")); assertEquals(tokenizer.fragmentsCounts.size(),3); } |
### Question:
SemiStructureTokenizer extends Tokenizer { @Override final public boolean incrementToken() throws IOException { if (currentEntry == null) { currentEntry = currentIterator.next(); currentCount = 0; String result = String.format("%s_%d", currentEntry.getKey(), currentCount); termAtt.setEmpty().append(result); return true; } else { if (currentCount < currentEntry.getValue()) { String result = String.format("%s_%d", currentEntry.getKey(), ++currentCount); termAtt.setEmpty().append(result); return true; } else if (currentIterator.hasNext()) { Map.Entry<String, Integer> currentEntry = currentIterator.next(); currentCount = 0; String result = String.format("%s_%d", currentEntry.getKey(), currentCount); termAtt.setEmpty().append(result); return true; } else { return false; } } } protected SemiStructureTokenizer(Reader input); protected SemiStructureTokenizer(AttributeFactory factory, Reader input); @Override final boolean incrementToken(); }### Answer:
@Test public void testIncrementToken() throws Exception { } |
### Question:
OperationJoin { public OperationJoin setOperations(Operation... ops) { if (ops.length == 0) { throw new IllegalArgumentException("At least one operation to join expected"); } if (this.operationIterator != null) { throw new IllegalStateException(ERROR_MSG_OPERATIONS_ALREADY_SET); } for (Operation op : ops) { prepareOperation(op); } this.operationIterator = this.operations.values().iterator(); return this; } private OperationJoin(); static OperationJoin create(); static OperationJoin create(Operation... ops); static OperationJoin create(Collection<Operation> ops); static OperationJoin create(Stream<Operation> ops); OperationJoin setOperations(Operation... ops); OperationJoin setOperations(Collection<Operation> ops); OperationJoin setOperations(Stream<Operation> ops); void sendWith(ServiceRequestSender sender, int batchSize); void sendWith(ServiceRequestSender sender); OperationJoin setCompletion(JoinedCompletionHandler joinedCompletion); boolean isEmpty(); Collection<Operation> getOperations(); Map<Long, Throwable> getFailures(); Operation getOperation(long id); static final String ERROR_MSG_BATCH_LIMIT_VIOLATED; static final String ERROR_MSG_INVALID_BATCH_SIZE; static final String ERROR_MSG_OPERATIONS_ALREADY_SET; }### Answer:
@Test public void testSetOperations() throws Throwable { OperationJoin operationJoin = OperationJoin.create(); Operation op1 = createServiceOperation(this.services.get(0)); Operation op2 = createServiceOperation(this.services.get(1)); Operation op3 = createServiceOperation(this.services.get(2)); host.testStart(1); operationJoin .setOperations(op1, op2, op3) .setCompletion((ops, exs) -> { if (exs != null) { host.failIteration(exs.values().iterator().next()); } else { host.completeIteration(); } }).sendWith(host); host.testWait(); } |
### Question:
OperationProcessingChain { public static OperationProcessingChain create(Filter... filters) { OperationProcessingChain opProcessingChain = new OperationProcessingChain(); for (Filter filter : filters) { filter.init(); opProcessingChain.filters.add(filter); } return opProcessingChain; } private OperationProcessingChain(); OperationProcessingContext createContext(ServiceHost host); OperationProcessingChain setLogLevel(Level logLevel); OperationProcessingChain toggleLogging(boolean loggingEnabled); OperationProcessingChain setLogFilter(Predicate<Operation> logFilter); static OperationProcessingChain create(Filter... filters); void close(); void processRequest(Operation op, OperationProcessingContext context,
Consumer<Operation> operationConsumer); void resumeProcessingRequest(Operation op, OperationProcessingContext context,
FilterReturnCode filterReturnCode, Throwable e); }### Answer:
@Test public void testCounterServiceWithOperationFilters() throws Throwable { Service counterService = createCounterService(); OperationProcessingChain opProcessingChain = OperationProcessingChain.create( new OperationLogger()); counterService.setOperationProcessingChain(opProcessingChain); for (int i = 0; i < COUNT; i++) { incrementCounter(false); } int counter = getCounter(); assertEquals(COUNT, counter); this.host.setOperationTimeOutMicros(TimeUnit.MILLISECONDS.toMicros(250)); opProcessingChain = OperationProcessingChain.create( new OperationLogger(), new OperationPatchDropper()); counterService.setOperationProcessingChain(opProcessingChain); incrementCounter(true); counter = getCounter(); assertEquals(COUNT, counter); }
@Test public void testCounterServiceJumpOperationProcessingStage() throws Throwable { Service counterService = createCounterService(); OperationProcessingChain opProcessingChain = OperationProcessingChain.create( new OperationLogger(), new OperationNextFiltersBypasser(counterService), new OperationPatchDropper()); counterService.setOperationProcessingChain(opProcessingChain); for (int i = 0; i < COUNT; i++) { incrementCounter(false); } int counter = getCounter(); assertEquals(COUNT, counter); } |
### Question:
CommandUtil { public static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName) throws InterruptedException, RemotingConnectException, RemotingTimeoutException, RemotingSendRequestException, MQBrokerException { Set<String> masterSet = new HashSet<String>(); ClusterInfo clusterInfoSerializeWrapper = adminExt.examineBrokerClusterInfo(); Set<String> brokerNameSet = clusterInfoSerializeWrapper.getClusterAddrTable().get(clusterName); if (brokerNameSet != null) { for (String brokerName : brokerNameSet) { BrokerData brokerData = clusterInfoSerializeWrapper.getBrokerAddrTable().get(brokerName); if (brokerData != null) { String addr = brokerData.getBrokerAddrs().get(MixAll.MASTER_ID); if (addr != null) { masterSet.add(addr); } } } } else { System.out .printf("[error] Make sure the specified clusterName exists or the nameserver which connected is correct."); } return masterSet; } static Map<String/*master addr*/, List<String>/*slave addr*/> fetchMasterAndSlaveDistinguish(
final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAndSlaveAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName); static String fetchBrokerNameByAddr(final MQAdminExt adminExt, final String addr); }### Answer:
@Test public void testFetchMasterAddrByClusterName() throws InterruptedException, MQBrokerException, RemotingTimeoutException, RemotingSendRequestException, RemotingConnectException { Set<String> result = CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExtImpl, "default-cluster"); assertThat(result.size()).isEqualTo(0); } |
### Question:
CommandUtil { public static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName) throws Exception { ClusterInfo clusterInfoSerializeWrapper = adminExt.examineBrokerClusterInfo(); Set<String> brokerNameSet = clusterInfoSerializeWrapper.getClusterAddrTable().get(clusterName); if (brokerNameSet.isEmpty()) { throw new Exception( "Make sure the specified clusterName exists or the nameserver which connected is correct."); } return brokerNameSet; } static Map<String/*master addr*/, List<String>/*slave addr*/> fetchMasterAndSlaveDistinguish(
final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchMasterAndSlaveAddrByClusterName(final MQAdminExt adminExt, final String clusterName); static Set<String> fetchBrokerNameByClusterName(final MQAdminExt adminExt, final String clusterName); static String fetchBrokerNameByAddr(final MQAdminExt adminExt, final String addr); }### Answer:
@Test public void testFetchBrokerNameByClusterName() throws Exception { Set<String> result = CommandUtil.fetchBrokerNameByClusterName(defaultMQAdminExtImpl, "default-cluster"); assertThat(result.contains("default-broker")).isTrue(); assertThat(result.contains("default-broker-one")).isTrue(); assertThat(result.size()).isEqualTo(2); } |
### Question:
RouteInfoManager { public byte[] getAllClusterInfo() { ClusterInfo clusterInfoSerializeWrapper = new ClusterInfo(); clusterInfoSerializeWrapper.setBrokerAddrTable(this.brokerAddrTable); clusterInfoSerializeWrapper.setClusterAddrTable(this.clusterAddrTable); return clusterInfoSerializeWrapper.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetAllClusterInfo() { byte[] clusterInfo = routeInfoManager.getAllClusterInfo(); assertThat(clusterInfo).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getAllTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); topicList.getTopicList().addAll(this.topicQueueTable.keySet()); } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetAllTopicList() { byte[] topicInfo = routeInfoManager.getAllTopicList(); Assert.assertTrue(topicInfo != null); assertThat(topicInfo).isNotNull(); } |
### Question:
RouteInfoManager { public int wipeWritePermOfBrokerByLock(final String brokerName) { try { try { this.lock.writeLock().lockInterruptibly(); return wipeWritePermOfBroker(brokerName); } finally { this.lock.writeLock().unlock(); } } catch (Exception e) { log.error("wipeWritePermOfBrokerByLock Exception", e); } return 0; } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testWipeWritePermOfBrokerByLock() { int result = routeInfoManager.wipeWritePermOfBrokerByLock("default-broker"); assertThat(result).isEqualTo(0); } |
### Question:
RouteInfoManager { public byte[] getUnitTopics() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Iterator<Entry<String, List<QueueData>>> topicTableIt = this.topicQueueTable.entrySet().iterator(); while (topicTableIt.hasNext()) { Entry<String, List<QueueData>> topicEntry = topicTableIt.next(); String topic = topicEntry.getKey(); List<QueueData> queueDatas = topicEntry.getValue(); if (queueDatas != null && queueDatas.size() > 0 && TopicSysFlag.hasUnitFlag(queueDatas.get(0).getTopicSynFlag())) { topicList.getTopicList().add(topic); } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetUnitTopics() { byte[] topicList = routeInfoManager.getUnitTopics(); assertThat(topicList).isNotNull(); } |
### Question:
RouteInfoManager { public byte[] getHasUnitSubTopicList() { TopicList topicList = new TopicList(); try { try { this.lock.readLock().lockInterruptibly(); Iterator<Entry<String, List<QueueData>>> topicTableIt = this.topicQueueTable.entrySet().iterator(); while (topicTableIt.hasNext()) { Entry<String, List<QueueData>> topicEntry = topicTableIt.next(); String topic = topicEntry.getKey(); List<QueueData> queueDatas = topicEntry.getValue(); if (queueDatas != null && queueDatas.size() > 0 && TopicSysFlag.hasUnitSubFlag(queueDatas.get(0).getTopicSynFlag())) { topicList.getTopicList().add(topic); } } } finally { this.lock.readLock().unlock(); } } catch (Exception e) { log.error("getAllTopicList Exception", e); } return topicList.encode(); } RouteInfoManager(); byte[] getAllClusterInfo(); void deleteTopic(final String topic); byte[] getAllTopicList(); RegisterBrokerResult registerBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId,
final String haServerAddr,
final TopicConfigSerializeWrapper topicConfigWrapper,
final List<String> filterServerList,
final Channel channel); int wipeWritePermOfBrokerByLock(final String brokerName); void unregisterBroker(
final String clusterName,
final String brokerAddr,
final String brokerName,
final long brokerId); TopicRouteData pickupTopicRouteData(final String topic); void scanNotActiveBroker(); void onChannelDestroy(String remoteAddr, Channel channel); void printAllPeriodically(); byte[] getSystemTopicList(); byte[] getTopicsByCluster(String cluster); byte[] getUnitTopics(); byte[] getHasUnitSubTopicList(); byte[] getHasUnitSubUnUnitTopicList(); }### Answer:
@Test public void testGetHasUnitSubTopicList() { byte[] topicList = routeInfoManager.getHasUnitSubTopicList(); assertThat(topicList).isNotNull(); } |
### Question:
DefaultPromise implements Promise<V> { @Override public boolean isCancelled() { return state.isCancelledState(); } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testIsCancelled() throws Exception { assertThat(promise.isCancelled()).isEqualTo(false); } |
### Question:
DefaultPromise implements Promise<V> { @Override public boolean isDone() { return state.isDoneState(); } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testIsDone() throws Exception { assertThat(promise.isDone()).isEqualTo(false); promise.set("Done"); assertThat(promise.isDone()).isEqualTo(true); } |
### Question:
DefaultPromise implements Promise<V> { @Override public V get() { return result; } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testGet() throws Exception { promise.set("Done"); assertThat(promise.get()).isEqualTo("Done"); }
@Test public void testGet_WithTimeout() throws Exception { try { promise.get(100); failBecauseExceptionWasNotThrown(OMSRuntimeException.class); } catch (OMSRuntimeException e) { assertThat(e).hasMessageContaining("Get request result is timeout or interrupted"); } } |
### Question:
DefaultPromise implements Promise<V> { @Override public void addListener(final PromiseListener<V> listener) { if (listener == null) { throw new NullPointerException("FutureListener is null"); } boolean notifyNow = false; synchronized (lock) { if (!isDoing()) { notifyNow = true; } else { if (promiseListenerList == null) { promiseListenerList = new ArrayList<>(); } promiseListenerList.add(listener); } } if (notifyNow) { notifyListener(listener); } } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void testAddListener() throws Exception { promise.addListener(new PromiseListener<String>() { @Override public void operationCompleted(final Promise<String> promise) { assertThat(promise.get()).isEqualTo("Done"); } @Override public void operationFailed(final Promise<String> promise) { } }); promise.set("Done"); } |
### Question:
DefaultPromise implements Promise<V> { @Override public Throwable getThrowable() { return exception; } DefaultPromise(); @Override boolean cancel(final boolean mayInterruptIfRunning); @Override boolean isCancelled(); @Override boolean isDone(); @Override V get(); @Override V get(final long timeout); @Override boolean set(final V value); @Override boolean setFailure(final Throwable cause); @Override void addListener(final PromiseListener<V> listener); @Override Throwable getThrowable(); }### Answer:
@Test public void getThrowable() throws Exception { assertThat(promise.getThrowable()).isNull(); Throwable exception = new OMSRuntimeException("-1", "Test Error"); promise.setFailure(exception); assertThat(promise.getThrowable()).isEqualTo(exception); } |
### Question:
PushConsumerImpl implements PushConsumer { @Override public PushConsumer attachQueue(final String queueName, final MessageListener listener) { this.subscribeTable.put(queueName, listener); try { this.rocketmqPushConsumer.subscribe(queueName, "*"); } catch (MQClientException e) { throw new OMSRuntimeException("-1", String.format("RocketMQ push consumer can't attach to %s.", queueName)); } return this; } PushConsumerImpl(final KeyValue properties); @Override KeyValue properties(); @Override void resume(); @Override void suspend(); @Override boolean isSuspended(); @Override PushConsumer attachQueue(final String queueName, final MessageListener listener); @Override synchronized void startup(); @Override synchronized void shutdown(); }### Answer:
@Test public void testConsumeMessage() { final byte[] testBody = new byte[] {'a', 'b'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(testBody); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic("HELLO_QUEUE"); consumer.attachQueue("HELLO_QUEUE", new MessageListener() { @Override public void onMessage(final Message message, final ReceivedMessageContext context) { assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("NewMsgId"); assertThat(((BytesMessage) message).getBody()).isEqualTo(testBody); context.ack(); } }); ((MessageListenerConcurrently) rocketmqPushConsumer .getMessageListener()).consumeMessage(Collections.singletonList(consumedMsg), null); } |
### Question:
LocalMessageCache implements ServiceLifecycle { long nextPullOffset(MessageQueue remoteQueue) { if (!pullOffsetTable.containsKey(remoteQueue)) { try { pullOffsetTable.putIfAbsent(remoteQueue, rocketmqPullConsumer.fetchConsumeOffset(remoteQueue, false)); } catch (MQClientException e) { log.error("A error occurred in fetch consume offset process.", e); } } return pullOffsetTable.get(remoteQueue); } LocalMessageCache(final DefaultMQPullConsumer rocketmqPullConsumer, final ClientConfig clientConfig); @Override void startup(); @Override void shutdown(); }### Answer:
@Test public void testNextPullOffset() throws Exception { MessageQueue messageQueue = new MessageQueue(); when(rocketmqPullConsume.fetchConsumeOffset(any(MessageQueue.class), anyBoolean())) .thenReturn(123L); assertThat(localMessageCache.nextPullOffset(new MessageQueue())).isEqualTo(123L); } |
### Question:
LocalMessageCache implements ServiceLifecycle { void submitConsumeRequest(ConsumeRequest consumeRequest) { try { consumeRequestCache.put(consumeRequest); } catch (InterruptedException ignore) { } } LocalMessageCache(final DefaultMQPullConsumer rocketmqPullConsumer, final ClientConfig clientConfig); @Override void startup(); @Override void shutdown(); }### Answer:
@Test public void testSubmitConsumeRequest() throws Exception { byte [] body = new byte[]{'1', '2', '3'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(body); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic("HELLO_QUEUE"); when(consumeRequest.getMessageExt()).thenReturn(consumedMsg); localMessageCache.submitConsumeRequest(consumeRequest); assertThat(localMessageCache.poll()).isEqualTo(consumedMsg); }
@Test public void testSubmitConsumeRequest() throws Exception { byte[] body = new byte[] {'1', '2', '3'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(body); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic("HELLO_QUEUE"); when(consumeRequest.getMessageExt()).thenReturn(consumedMsg); localMessageCache.submitConsumeRequest(consumeRequest); assertThat(localMessageCache.poll()).isEqualTo(consumedMsg); } |
### Question:
PullConsumerImpl implements PullConsumer { @Override public Message poll() { MessageExt rmqMsg = localMessageCache.poll(); return rmqMsg == null ? null : OMSUtil.msgConvert(rmqMsg); } PullConsumerImpl(final String queueName, final KeyValue properties); @Override KeyValue properties(); @Override Message poll(); @Override Message poll(final KeyValue properties); @Override void ack(final String messageId); @Override void ack(final String messageId, final KeyValue properties); @Override synchronized void startup(); @Override synchronized void shutdown(); }### Answer:
@Test public void testPoll() { final byte[] testBody = new byte[] {'a', 'b'}; MessageExt consumedMsg = new MessageExt(); consumedMsg.setMsgId("NewMsgId"); consumedMsg.setBody(testBody); consumedMsg.putUserProperty(NonStandardKeys.MESSAGE_DESTINATION, "TOPIC"); consumedMsg.setTopic(queueName); when(localMessageCache.poll()).thenReturn(consumedMsg); Message message = consumer.poll(); assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo("NewMsgId"); assertThat(((BytesMessage) message).getBody()).isEqualTo(testBody); }
@Test public void testPoll_WithTimeout() { Message message = consumer.poll(); assertThat(message).isNull(); message = consumer.poll(OMS.newKeyValue().put(PropertyKeys.OPERATION_TIMEOUT, 100)); assertThat(message).isNull(); } |
### Question:
SequenceProducerImpl extends AbstractOMSProducer implements SequenceProducer { @Override public synchronized void rollback() { msgCacheQueue.clear(); } SequenceProducerImpl(final KeyValue properties); @Override KeyValue properties(); @Override void send(final Message message); @Override void send(final Message message, final KeyValue properties); @Override synchronized void commit(); @Override synchronized void rollback(); }### Answer:
@Test public void testRollback() { when(rocketmqProducer.getMaxMessageSize()).thenReturn(1024); final BytesMessage message = producer.createBytesMessageToTopic("HELLO_TOPIC", new byte[] {'a'}); producer.send(message); producer.rollback(); producer.commit(); assertThat(message.headers().getString(MessageHeader.MESSAGE_ID)).isEqualTo(null); } |
### Question:
SendMsgStatusCommand implements SubCommand { @Override public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException { final DefaultMQProducer producer = new DefaultMQProducer("PID_SMSC", rpcHook); producer.setInstanceName("PID_SMSC_" + System.currentTimeMillis()); try { producer.start(); String brokerName = commandLine.getOptionValue('b').trim(); int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s')) : 128; int count = commandLine.hasOption('c') ? Integer.parseInt(commandLine.getOptionValue('c')) : 50; producer.send(buildMessage(brokerName, 16)); for (int i = 0; i < count; i++) { long begin = System.currentTimeMillis(); SendResult result = producer.send(buildMessage(brokerName, messageSize)); System.out.printf("rt:" + (System.currentTimeMillis() - begin) + "ms, SendResult=" + result); } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { producer.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(Options options); @Override void execute(CommandLine commandLine, Options options, RPCHook rpcHook); }### Answer:
@Test public void testExecute() { SendMsgStatusCommand cmd = new SendMsgStatusCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {"-b 127.0.0.1:10911", "-s 1024 -c 10"}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); } |
### Question:
GetNamesrvConfigCommand implements SubCommand { @Override public void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook) throws SubCommandException { DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook); defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis())); try { String servers = commandLine.getOptionValue('n'); List<String> serverList = null; if (servers != null && servers.length() > 0) { String[] serverArray = servers.trim().split(";"); if (serverArray.length > 0) { serverList = Arrays.asList(serverArray); } } defaultMQAdminExt.start(); Map<String, Properties> nameServerConfigs = defaultMQAdminExt.getNameServerConfig(serverList); for (String server : nameServerConfigs.keySet()) { System.out.printf("============%s============\n", server); for (Object key : nameServerConfigs.get(server).keySet()) { System.out.printf("%-50s= %s\n", key, nameServerConfigs.get(server).get(key)); } } } catch (Exception e) { throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e); } finally { defaultMQAdminExt.shutdown(); } } @Override String commandName(); @Override String commandDesc(); @Override Options buildCommandlineOptions(final Options options); @Override void execute(final CommandLine commandLine, final Options options, final RPCHook rpcHook); }### Answer:
@Test public void testExecute() throws SubCommandException { GetNamesrvConfigCommand cmd = new GetNamesrvConfigCommand(); Options options = ServerUtil.buildCommandlineOptions(new Options()); String[] subargs = new String[] {}; final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser()); cmd.execute(commandLine, options, null); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.