method2testcases
stringlengths
118
6.63k
### Question: CpGenco extends Broker { @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange public CpGenco withMinQuantity (double qty) { this.minQuantity = qty; return this; } CpGenco(String username); void init(BrokerProxy proxy, int seedId, RandomSeedRepo randomSeedRepo, TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer: @Test public void testWithMinQuantity () { init(); assertEquals(120.0, genco.getMinQuantity(), 1e-6, "correct initial"); genco.withMinQuantity(150.0); assertEquals(150.0, genco.getMinQuantity(), 1e-6, "correct post"); }
### 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: EvCustomer { public void doActivities (int day, int hour) { TimeslotData timeslotData = todayMap[hour]; double intendedDistance = timeslotData.getIntendedDistance(); double neededCapacity = getNeededCapacity(intendedDistance); if (intendedDistance < distanceEpsilon) { return; } if (neededCapacity > currentCapacity) { log.warn("Customer {} out of juice!", getName()); return; } try { double before = currentCapacity; discharge(neededCapacity); log.info("{} {} at {}, {} kms {} kWh from {} to {}", name, timeslotData.getActivity().get().getName(), dtf.print(service.getTimeService().getCurrentDateTime()), intendedDistance, neededCapacity, before, currentCapacity); driving = true; } catch (ChargeException ce) { log.error(ce); } } EvCustomer(String name); String getName(); long getId(); CustomerInfo initialize(SocialGroup socialGroup, String gender, Map<Integer, Activity> activities, List<GroupActivity> groupActivities, CarType car, EvSocialClass esc, CustomerServiceAccessor service, Config config); void evaluateTariffs(List<Tariff> tariffs); void step(Timeslot timeslot); void doActivities(int day, int hour); double getDominantLoad(); double[] getLoads(int day, int hour); double getCurrentCapacity(); @StateChange void setCurrentCapacity(double currentCapacity); void discharge(double kwh); void charge(double kwh); double getNeededCapacity(double distance); double getDischargingCapacity(); }### Answer: @Test public void testDoActivities () { mockSeed.setIntSeed(new int[]{0, 0}); initialize("male"); evCustomer.makeDayPlanning(0, 1); assertEquals(50, evCustomer.getCurrentCapacity(), 1E-06); evCustomer.doActivities(0, 5); assertFalse(evCustomer.isDriving()); evCustomer.doActivities(0, 6); assertTrue(evCustomer.isDriving()); assertEquals(45.0, evCustomer.getCurrentCapacity(), 1E-06); }
### 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: Activity { public Optional<double[]> getDailyProfileOptional () { return Optional.ofNullable(dailyProfile); } Activity(); Activity(String name); double getDayWeight(int day); int getId(); String getName(); double getChargerProbability(); void setChargerProbability(double prob); int getInterval(); double getWeekdayWeight(); double getWeekendWeight(); @ConfigurableValue(valueType = "List", dump = false, description = "When this activity might start") void setWeeklyProfile(List<String> value); List<String> getWeeklyProfile(); Optional<double[]> getWeeklyProfileOptional(); @ConfigurableValue(valueType = "List", dump = false, description = "When this activity might start") void setDailyProfile(List<String> value); List<String> getDailyProfile(); Optional<double[]> getDailyProfileOptional(); double getDayProbability(int dayOfWeek); double getProbabilityForTimeslot(int slot); void setInterval(int value); void setId(int value); }### Answer: @Test public void dailyProfileNormalizedGT0 () { TreeMap<String, String> map = new TreeMap<String, String>(); map.put("evcustomer.beans.activity.instances", "commuting,visit"); map.put("evcustomer.beans.activity.commuting.dailyProfile", "0,0,0,0,0,0,0,0.8,1.0,0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0"); map.put("evcustomer.beans.activity.visit.weekdayWeight", "0.2"); map.put("evcustomer.beans.activity.visit.weekendWeight", "0.6"); config = new MapConfiguration(map); Configurator configurator = new Configurator(); configurator.setConfiguration(config); Collection<?> instances = configurator.configureInstances(Activity.class); Map<String, Activity> acts = mapNames(instances); Activity commuting = acts.get("commuting"); assertNotNull(commuting); assertTrue(commuting.getDailyProfileOptional().isPresent()); double[] daily = commuting.getDailyProfileOptional().get(); assertNotNull(daily); assertEquals(0.0, daily[3], 1e-6, "zero at 3:00"); assertEquals(0.4, daily[7], 1e-6, ".4 at 7:00"); assertEquals(0.5, daily[8], 1e-6, ".5 at 8:00"); assertEquals(0.1, daily[9], 1e-6, ".1 at 9:00"); }
### Question: Activity { public double getProbabilityForTimeslot (int slot) { double result = 1.0; if (slot < 0 || slot > 23) { log.error("bad slot {} in probabilityForTimeslot", slot); result = 0.0; } else if (getDailyProfileOptional().isPresent()) { result = getDailyProfileOptional().get()[slot]; } else { result = 1.0; } return result; } Activity(); Activity(String name); double getDayWeight(int day); int getId(); String getName(); double getChargerProbability(); void setChargerProbability(double prob); int getInterval(); double getWeekdayWeight(); double getWeekendWeight(); @ConfigurableValue(valueType = "List", dump = false, description = "When this activity might start") void setWeeklyProfile(List<String> value); List<String> getWeeklyProfile(); Optional<double[]> getWeeklyProfileOptional(); @ConfigurableValue(valueType = "List", dump = false, description = "When this activity might start") void setDailyProfile(List<String> value); List<String> getDailyProfile(); Optional<double[]> getDailyProfileOptional(); double getDayProbability(int dayOfWeek); double getProbabilityForTimeslot(int slot); void setInterval(int value); void setId(int value); }### Answer: @Test public void probabilityForTimeslot () { TreeMap<String, String> map = new TreeMap<String, String>(); map.put("evcustomer.beans.activity.instances", "min,daily"); map.put("evcustomer.beans.activity.daily.dailyProfile", "0,0,0,0,0,0,0.8,1.0,0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"); config = new MapConfiguration(map); Configurator configurator = new Configurator(); configurator.setConfiguration(config); Collection<?> instances = configurator.configureInstances(Activity.class); Map<String, Activity> acts = mapNames(instances); assertEquals(2, acts.size(), "two activities"); Activity min = acts.get("min"); assertEquals(1.0, min.getProbabilityForTimeslot(1)); assertEquals(1.0, min.getProbabilityForTimeslot(1)); assertEquals(1.0, min.getProbabilityForTimeslot(23)); assertEquals(1.0, min.getProbabilityForTimeslot(2)); assertEquals(1.0, min.getProbabilityForTimeslot(2)); assertEquals(0.0, min.getProbabilityForTimeslot(-1)); assertEquals(0.0, min.getProbabilityForTimeslot(24)); Activity daily = acts.get("daily"); assertEquals(0.0, daily.getProbabilityForTimeslot(0), 1e-6); assertEquals(0.0, daily.getProbabilityForTimeslot(5), 1e-6); assertEquals(0.4, daily.getProbabilityForTimeslot(6), 1e-6); assertEquals(0.5, daily.getProbabilityForTimeslot(7), 1e-6); assertEquals(0.1, daily.getProbabilityForTimeslot(8), 1e-6); assertEquals(0.0, daily.getProbabilityForTimeslot(9), 1e-6); assertEquals(0.5, daily.getProbabilityForTimeslot(7), 1e-6); }
### 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: CapacityControlService extends TimeslotPhaseProcessor implements CapacityControl, InitializationService { @Override public void postEconomicControl (EconomicControlEvent event) { int tsIndex = event.getTimeslotIndex(); int current = timeslotRepo.currentTimeslot().getSerialNumber(); if (tsIndex < current) { log.warn("attempt to save old economic control for ts " + tsIndex + " during timeslot " + current); return; } List<EconomicControlEvent> tsList = pendingEconomicControls.get(tsIndex); if (null == tsList) { tsList = new ArrayList<EconomicControlEvent>(); pendingEconomicControls.put(tsIndex, tsList); } tsList.add(event); } @Override String initialize(Competition competition, List<String> completedInits); @Override void exerciseBalancingControl(BalancingOrder order, double kwh, double payment); @Override void postEconomicControl(EconomicControlEvent event); @Override RegulationAccumulator getRegulationCapacity(BalancingOrder order); @Override void activate(Instant time, int phaseNumber); }### Answer: @Test public void testPostEconomicControl () { EconomicControlEvent ece1 = new EconomicControlEvent(spec, 0.20, 0); EconomicControlEvent ece3 = new EconomicControlEvent(spec, 0.22, 2); EconomicControlEvent ece4 = new EconomicControlEvent(spec, 0.23, 3); assertNull(capacityControl.getControlsForTimeslot(0), "no controls ts 0"); assertNull(capacityControl.getControlsForTimeslot(1), "no controls ts 1"); capacityControl.postEconomicControl(ece1); List<EconomicControlEvent> controls = capacityControl.getControlsForTimeslot(0); assertNotNull(controls, "some controls ts 0"); assertEquals(1, controls.size(), "one control"); assertEquals(ece1, controls.get(0), "correct control"); assertNull(capacityControl.getControlsForTimeslot(2), "no controls ts 2"); capacityControl.postEconomicControl(ece3); capacityControl.postEconomicControl(ece4); controls = capacityControl.getControlsForTimeslot(0); assertNotNull(controls, "some controls ts 0"); assertEquals(1, controls.size(), "one control"); assertEquals(ece1, controls.get(0), "correct control"); controls = capacityControl.getControlsForTimeslot(2); assertNotNull(controls, "some controls ts 2"); assertEquals(1, controls.size(), "one control"); assertEquals(ece3, controls.get(0), "correct control"); controls = capacityControl.getControlsForTimeslot(3); assertNotNull(controls, "some controls ts 3"); assertEquals(1, controls.size(), "one control"); assertEquals(ece4, controls.get(0), "correct control"); }
### 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 long getSubmitTimeMillisFromJobHistory(byte[] jobHistoryRaw) { long submitTimeMillis = 0; if (null == jobHistoryRaw) { return submitTimeMillis; } HadoopVersion hv = JobHistoryFileParserFactory.getVersion(jobHistoryRaw); switch (hv) { case TWO: int startIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.JOB_SUBMIT_EVENT_BYTES, 0); if (startIndex != -1) { int secondQuoteIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.SUBMIT_TIME_PREFIX_HADOOP2_BYTES, startIndex); if (secondQuoteIndex != -1) { String submitTimeMillisString = Bytes.toString(jobHistoryRaw, secondQuoteIndex + Constants.EPOCH_TIMESTAMP_STRING_LENGTH, Constants.EPOCH_TIMESTAMP_STRING_LENGTH); try { submitTimeMillis = Long.parseLong(submitTimeMillisString); } catch (NumberFormatException nfe) { LOG.error(" caught NFE during conversion of submit time " + submitTimeMillisString + " " + nfe.getMessage()); submitTimeMillis = 0; } } } break; case ONE: default: startIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.SUBMIT_TIME_PREFIX_BYTES, 0); if (startIndex != -1) { int prefixEndIndex = startIndex + Constants.SUBMIT_TIME_PREFIX_BYTES.length; int secondQuoteIndex = ByteUtil.indexOf(jobHistoryRaw, Constants.QUOTE_BYTES, prefixEndIndex); if (secondQuoteIndex != -1) { int numberLength = secondQuoteIndex - prefixEndIndex; String submitTimeMillisString = Bytes.toString(jobHistoryRaw, prefixEndIndex, numberLength); try { submitTimeMillis = Long.parseLong(submitTimeMillisString); } catch (NumberFormatException nfe) { LOG.error(" caught NFE during conversion of submit time " + submitTimeMillisString + " " + nfe.getMessage()); submitTimeMillis = 0; } } } break; } return submitTimeMillis; } 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 testGetSubmitTimeMillisFromJobHistory2() throws IOException { String JOB_HISTORY_FILE_NAME = "src/test/resources/job_1329348432655_0001-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist"; File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME); byte[] contents = Files.toByteArray(jobHistoryfile); long actualts = JobHistoryFileParserBase.getSubmitTimeMillisFromJobHistory(contents); long expts = 1329348443227L; assertEquals(expts, actualts); JOB_HISTORY_FILE_NAME = "src/test/resources/job_1329348432999_0003-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist"; jobHistoryfile = new File(JOB_HISTORY_FILE_NAME); contents = Files.toByteArray(jobHistoryfile); actualts = JobHistoryFileParserBase.getSubmitTimeMillisFromJobHistory(contents); expts = 1328218696000L; assertEquals(expts, actualts); } @Test(expected=IllegalArgumentException.class) public void testIncorrectSubmitTime() { byte[] jobHistoryBytes = Bytes.toBytes(""); JobHistoryFileParserBase.getSubmitTimeMillisFromJobHistory(jobHistoryBytes); }
### 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: FileLister { static String getJobIdFromPath(Path aPath) { String fileName = aPath.getName(); JobFile jf = new JobFile(fileName); String jobId = jf.getJobid(); if(jobId == null) { throw new ProcessingException("job id is null for " + aPath.toUri()); } return jobId; } FileLister(); static FileStatus[] listFiles(boolean recurse, FileSystem hdfs, Path inputPath, JobFileModifiedRangePathFilter jobFileModifiedRangePathFilter); static FileStatus[] getListFilesToProcess(long maxFileSize, boolean recurse, FileSystem hdfs, Path inputPath, JobFileModifiedRangePathFilter pathFilter); }### Answer: @Test public void testGetJobIdFromPath() { String JOB_HISTORY_FILE_NAME = "src/test/resources/job_1329348432655_0001-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist"; File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME); Path srcPath = new Path(jobHistoryfile.toURI()); String jobId = FileLister.getJobIdFromPath(srcPath); String expJobId = "job_1329348432655_0001"; assertEquals(expJobId, jobId); String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; File jobConfFile = new File(JOB_CONF_FILE_NAME); srcPath = new Path(jobConfFile.toURI()); jobId = FileLister.getJobIdFromPath(srcPath); assertEquals(expJobId, jobId); jobConfFile = new File("job_201311192236_3583_1386370578196_user1_Sleep+job"); srcPath = new Path(jobConfFile.toURI()); jobId = FileLister.getJobIdFromPath(srcPath); expJobId = "job_201311192236_3583"; assertEquals(expJobId, jobId); } @Test(expected=ProcessingException.class) public void testGetJobIdFromIncorrectPath() { final String JOB_HISTORY_FILE_NAME = "abcd.jhist"; File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME); Path srcPath = new Path(jobHistoryfile.toURI()); FileLister.getJobIdFromPath(srcPath); }
### 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: JobHistoryFileParserHadoop2 extends JobHistoryFileParserBase { byte[] getValue(String key, int value) { byte[] valueBytes = null; Class<?> clazz = JobHistoryKeys.KEY_TYPES.get(JobHistoryKeys.valueOf(key)); if (clazz == null) { throw new IllegalArgumentException(" unknown key " + key + " encountered while parsing " + this.jobKey); } if (Long.class.equals(clazz)) { valueBytes = (value != 0L) ? Bytes.toBytes(new Long(value)) : Constants.ZERO_LONG_BYTES; } else { valueBytes = (value != 0) ? Bytes.toBytes(value) : Constants.ZERO_INT_BYTES; } return valueBytes; } JobHistoryFileParserHadoop2(Configuration conf); @Override void parse(byte[] historyFileContents, JobKey jobKey); byte[] getTaskKey(String prefix, String jobNumber, String fullId); byte[] getAMKey(String prefix, String fullId); @Override List<Put> getJobPuts(); @Override List<Put> getTaskPuts(); void printAllPuts(List<Put> p); @Override Long getMegaByteMillis(); @Override JobDetails getJobDetails(); long getMapMbMillis(); void setMapMbMillis(long mapMbMillis); long getReduceMbMillis(); void setReduceMbMillis(long reduceMbMillis); static final String JOB_STATUS_SUCCEEDED; }### Answer: @Test public void testLongExpGetValuesIntBytes() { String[] keysToBeChecked = {"totalMaps", "totalReduces", "finishedMaps", "finishedReduces", "failedMaps", "failedReduces"}; byte[] byteValue = null; int intValue10 = 10; long longValue10 = 10L; JobHistoryFileParserHadoop2 jh = new JobHistoryFileParserHadoop2(null); for(String key: keysToBeChecked) { byteValue = jh.getValue(JobHistoryKeys.HADOOP2_TO_HADOOP1_MAPPING.get(key), intValue10); assertEquals(Bytes.toLong(byteValue), longValue10); } } @Test public void testIntExpGetValuesIntBytes() { String[] keysToBeChecked = {"httpPort"}; byte[] byteValue = null; int intValue10 = 10; JobHistoryFileParserHadoop2 jh = new JobHistoryFileParserHadoop2(null); for(String key: keysToBeChecked) { byteValue = jh.getValue(JobHistoryKeys.HADOOP2_TO_HADOOP1_MAPPING.get(key), intValue10); assertEquals(Bytes.toInt(byteValue), intValue10); } }
### Question: CounterMap implements Iterable<Counter> { @Override public Iterator<Counter> iterator() { return new Iterator<Counter>() { private Iterator<Map.Entry<String,Map<String,Counter>>> groupIter = internalMap.entrySet().iterator(); private Iterator<Map.Entry<String,Counter>> currentGroupIter = null; @Override public boolean hasNext() { if ((currentGroupIter == null || !currentGroupIter.hasNext()) && groupIter.hasNext()) { currentGroupIter = groupIter.next().getValue().entrySet().iterator(); } return currentGroupIter != null && currentGroupIter.hasNext(); } @Override public Counter next() { if (!hasNext()) { throw new NoSuchElementException("No more elements in iterator"); } return currentGroupIter.next().getValue(); } @Override public void remove() { throw new UnsupportedOperationException("remove() is not supported by CounterMap"); } }; } Set<String> getGroups(); Map<String,Counter> getGroup(String group); Counter getCounter(String group, String name); Counter add(Counter counter); void addAll(Iterable<Counter> counters); @Override Iterator<Counter> iterator(); }### Answer: @Test public void testIterator() { Counter g1k1 = new Counter("group1", "key1", 10); Counter g1k2 = new Counter("group1", "key2", 20); Counter g2k1 = new Counter("group2", "key1", 100); Counter g3k1 = new Counter("group3", "key1", 200); CounterMap base = new CounterMap(); base.add(g1k1); base.add(g1k2); base.add(g2k1); base.add(g3k1); CounterMap copy = new CounterMap(); copy.addAll(base); Counter c = copy.getCounter("group1", "key1"); assertNotNull(c); assertEquals(g1k1, c); c = copy.getCounter("group1", "key2"); assertNotNull(c); assertEquals(g1k2, c); c = copy.getCounter("group2", "key1"); assertNotNull(c); assertEquals(g2k1, c); c = copy.getCounter("group3", "key1"); assertNotNull(c); assertEquals(g3k1, c); }
### 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: JobDetails implements Comparable<JobDetails> { Long getCounterValueAsLong(final CounterMap counters, final String counterGroupName, final String counterName) { Counter c1 = counters.getCounter(counterGroupName, counterName); if (c1 != null) { return c1.getValue(); } else { return 0L; } } @JsonCreator JobDetails(@JsonProperty("jobKey") JobKey key); @Override boolean equals(Object other); @Override int compareTo(JobDetails otherJob); @Override int hashCode(); JobKey getJobKey(); String getJobId(); void setJobId(String jobId); String getJobName(); void setJobName(String jobName); String getUser(); void setUser(String user); String getPriority(); void setPriority(String priority); String getStatus(); void setStatus(String status); String getVersion(); void setVersion(String version); HadoopVersion getHadoopVersion(); void setHadoopVersion(String hadoopVersion); long getSubmitTime(); void setSubmitTime(long submitTime); Date getSubmitDate(); long getLaunchTime(); void setLaunchTime(long launchTime); Date getLaunchDate(); long getFinishTime(); void setFinishTime(long finishTime); Date getFinishDate(); long getRunTime(); long getTotalMaps(); void setTotalMaps(long totalMaps); long getTotalReduces(); void setTotalReduces(long totalReduces); long getFinishedMaps(); void setFinishedMaps(long finishedMaps); long getFinishedReduces(); void setFinishedReduces(long finishedReduces); long getFailedMaps(); void setFailedMaps(long failedMaps); long getFailedReduces(); void setFailedReduces(long failedReduces); long getMapFileBytesRead(); void setMapFileBytesRead(long mapFileBytesRead); long getMapFileBytesWritten(); void setMapFileBytesWritten(long mapBytesWritten); long getHdfsBytesRead(); long getMapSlotMillis(); void setMapSlotMillis(long mapSlotMillis); long getReduceSlotMillis(); void setReduceSlotMillis(long reduceSlotMillis); long getReduceShuffleBytes(); void setReduceShuffleBytes(long reduceShuffleBytes); long getReduceFileBytesRead(); void setReduceFileBytesRead(long reduceFileBytesRead); long getHdfsBytesWritten(); void setHdfsBytesWritten(long hdfsBytesWritten); void setHdfsBytesRead(long hdfsBytesRead); long getMegabyteMillis(); void setMegabyteMillis(long megabyteMillis); double getCost(); void setCost(double cost); void addTask(TaskDetails task); void addTasks(List<TaskDetails> tasks); List<TaskDetails> getTasks(); String getQueue(); void setQueue(String queue); Configuration getConfiguration(); CounterMap getCounters(); CounterMap getMapCounters(); CounterMap getReduceCounters(); @Deprecated void setTasks(List<TaskDetails> newTasks); void populate(Result result); }### Answer: @Test public void testGetCounterValueAsLong() { CounterMap cm = new CounterMap(); String cg = Constants.FILESYSTEM_COUNTERS; String cname = Constants.FILES_BYTES_READ; Long expValue = 1234L; Counter c1 = new Counter(cg, cname, expValue); cm.add(c1); JobDetails jd = new JobDetails(null); assertEquals(expValue, jd.getCounterValueAsLong(cm, cg, cname)); Long zeroValue = 0L; assertEquals(zeroValue, jd.getCounterValueAsLong(cm, Constants.JOB_COUNTER_HADOOP2, Constants.SLOTS_MILLIS_MAPS)); }
### 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 getTaskId() { return this.taskId; } @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 testSerialization() { TaskKeyConverter conv = new TaskKeyConverter(); TaskKey key1 = new TaskKey( new JobKey("test@local", "testuser", "app", 1234L, "job_20120101000000_1111"), "m_001"); assertEquals("test@local", key1.getCluster()); assertEquals("testuser", key1.getUserName()); assertEquals("app", key1.getAppId()); assertEquals(1234L, key1.getRunId()); assertEquals("job_20120101000000_1111", key1.getJobId().getJobIdString()); assertEquals("m_001", key1.getTaskId()); byte[] key1Bytes = conv.toBytes(key1); TaskKey key2 = conv.fromBytes(key1Bytes); assertKey(key1, key2); TaskKey key3 = conv.fromBytes( conv.toBytes(key2) ); assertKey(key1, key3); long now = System.currentTimeMillis(); byte[] encoded = Bytes.toBytes(Long.MAX_VALUE - now); Bytes.putBytes(encoded, encoded.length-Constants.SEP_BYTES.length, Constants.SEP_BYTES, 0, Constants.SEP_BYTES.length); long badId = Long.MAX_VALUE - Bytes.toLong(encoded); LOG.info("Bad run ID is " + badId); TaskKey badKey1 = new TaskKey( new JobKey(key1.getQualifiedJobId(), key1.getUserName(), key1.getAppId(), badId), key1.getTaskId()); byte[] badKeyBytes = conv.toBytes(badKey1); TaskKey badKey2 = conv.fromBytes(badKeyBytes); assertKey(badKey1, badKey2); }
### 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 byte[][] split(byte[] source, byte[] separator) { return split(source, separator, -1); } 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 testSplit() { byte[][] expected1 = Bytes .toByteArrays(new String[] { "abc", "bcd", "cde" }); byte[][] splitresult = ByteUtil.split(source1, sep1); assertSplitResult(expected1, splitresult); byte[][] expected2 = Bytes.toByteArrays(new String[] { "random", "stuff", "" }); splitresult = ByteUtil.split(source2, sep2); assertSplitResult(expected2, splitresult); byte[][] expected3 = Bytes.toByteArrays(new String[] { "", "more", "stuff", "" }); splitresult = ByteUtil.split(source3, sep3); assertSplitResult(expected3, splitresult); byte[][] expected4 = Bytes.toByteArrays(new String[] { "singlesource" }); splitresult = ByteUtil.split(source4, sep4); assertSplitResult(expected4, splitresult); byte[][] expected5 = Bytes.toByteArrays(new String[]{ "abc", "", "bcd"}); splitresult = ByteUtil.split(source5, sep5); assertSplitResult(expected5, splitresult); byte[][] expected6 = new byte[][] {source6}; splitresult = ByteUtil.split(source6, sep6); assertSplitResult(expected6, splitresult); } @Test public void testSplitWithLimit() { byte[][] expectedResult = Bytes.toByteArrays(new String[] {"random", "stuff::"}); byte[][] splitResult = ByteUtil.split(source2, sep2, 2); assertSplitResult(expectedResult, splitResult); expectedResult = Bytes.toByteArrays(new String[] {"random", "stuff", ""}); splitResult = ByteUtil.split(source2, sep2, 100); assertSplitResult(expectedResult, splitResult); expectedResult = new byte[][] {source2}; splitResult = ByteUtil.split(source2, sep2, 1); assertSplitResult(expectedResult, splitResult); }
### Question: ByteUtil { public static List<Range> splitRanges(byte[] source, byte[] separator) { return splitRanges(source, separator, -1); } 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 testSplitRanges() { try { new ByteUtil.Range(-1, 1); fail("Should have failed with start < 0"); } catch (IllegalArgumentException expected) { } try { new ByteUtil.Range(2, 1); fail("Should have failed with end < start"); } catch (IllegalArgumentException expected) { } List<ByteUtil.Range> ranges1 = ByteUtil.splitRanges(source1, sep1); assertEquals("source1 should have 3 segments", 3, ranges1.size()); assertEquals(0, ranges1.get(0).start()); assertEquals(3, ranges1.get(0).length()); assertEquals(4, ranges1.get(1).start()); assertEquals(3, ranges1.get(1).length()); assertEquals(8, ranges1.get(2).start()); assertEquals(3, ranges1.get(2).length()); List<ByteUtil.Range> ranges4 = ByteUtil.splitRanges(source4, sep4); assertEquals("source4 should be a single segment", 1, ranges4.size()); assertEquals(0, ranges4.get(0).start()); assertEquals(source4.length, ranges4.get(0).length()); List<ByteUtil.Range> ranges5 = ByteUtil.splitRanges(source5, sep5); assertEquals(3, ranges5.size()); assertEquals(0, ranges5.get(0).start()); assertEquals(3, ranges5.get(0).end()); assertEquals(4, ranges5.get(1).start()); assertEquals(4, ranges5.get(1).end()); assertEquals(5, ranges5.get(2).start()); assertEquals(8, ranges5.get(2).end()); }
### Question: ByteUtil { public static byte[] join(byte[] separator, byte[]... components) { if (components == null || components.length == 0) { return Constants.EMPTY_BYTES; } int finalSize = 0; if (separator != null) { finalSize = separator.length * (components.length - 1); } for (byte[] comp : components) { finalSize += comp.length; } byte[] buf = new byte[finalSize]; int offset = 0; for (int i=0; i < components.length; i++) { System.arraycopy(components[i], 0, buf, offset, components[i].length); offset += components[i].length; if (i < (components.length-1) && separator != null && separator.length > 0) { System.arraycopy(separator, 0, buf, offset, separator.length); offset += separator.length; } } return buf; } 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 testJoin() { byte[] comp1 = Bytes.toBytes("abc"); byte[] comp2 = Bytes.toBytes("def"); byte[] comp3 = Bytes.toBytes("ghi"); byte[] joined = ByteUtil.join(Constants.SEP_BYTES); assertNotNull(joined); assertEquals(0, joined.length); joined = ByteUtil.join(null, comp1, comp2, comp3); assertNotNull(joined); assertArrayEquals(Bytes.toBytes("abcdefghi"), joined); joined = ByteUtil.join(Constants.SEP_BYTES, comp1, comp2, comp3); assertNotNull(joined); assertArrayEquals( Bytes.toBytes("abc"+Constants.SEP+"def"+Constants.SEP+"ghi"), joined); }
### Question: ByteUtil { public static int indexOf(byte[] array, byte[] target, int fromIndex) { if (array == null || target == null) { return -1; } if (fromIndex < 0 || (fromIndex > (array.length - target.length))) { return -1; } if (target.length == 0) { return fromIndex; } firstbyte: for (int i = fromIndex; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue firstbyte; } } return i; } return -1; } 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 testIndexOf() { byte[] array = Bytes.toBytes("quackattack"); byte[] a = Bytes.toBytes("a"); byte[] ack = Bytes.toBytes("ack"); byte[] empty = Bytes.toBytes(""); int index = ByteUtil.indexOf(array, null, 0); assertEquals(-1, index); index = ByteUtil.indexOf(null, ack, 0); assertEquals(-1, index); index = ByteUtil.indexOf(null, ack, 1); assertEquals(-1, index); index = ByteUtil.indexOf(array, ack, 100); assertEquals(-1, index); index = ByteUtil.indexOf(array, ack, 100); assertEquals(-1, index); index = ByteUtil.indexOf(array, a, array.length + 1); assertEquals(-1, index); index = ByteUtil.indexOf(array, ack, array.length + 1); assertEquals(-1, index); index = ByteUtil.indexOf(array, empty, array.length + 1); assertEquals(-1, index); index = ByteUtil.indexOf(array, empty, 100); assertEquals(-1, index); index = ByteUtil.indexOf(array, ack, -3); assertEquals(-1, index); index = ByteUtil.indexOf(array, empty, -3); assertEquals(-1, index); index = ByteUtil.indexOf(array, empty, 0); assertEquals(0, index); index = ByteUtil.indexOf(array, empty, 4); assertEquals(4, index); assertIndexOf(0, array, empty, 0); assertIndexOf(1, array, empty, 1); assertIndexOf(3, array, empty, 3); assertIndexOf(5, array, empty, 5); assertIndexOf(11, array, empty, 11); assertIndexOf(2, array, a, 0); assertIndexOf(2, array, a, 1); assertIndexOf(2, array, a, 2); assertIndexOf(5, array, a, 3); assertIndexOf(5, array, a, 4); assertIndexOf(2, array, ack, 0); assertIndexOf(2, array, ack, 1); assertIndexOf(2, array, ack, 2); assertIndexOf(8, array, ack, 3); assertIndexOf(8, array, ack, 4); assertIndexOf(8, array, ack, 8); }
### Question: ByteUtil { public static long getValueAsLong(final byte[] key, final Map<byte[], byte[]> taskValues) { byte[] value = taskValues.get(key); if (value != null) { try { long retValue = Bytes.toLong(value); return retValue; } catch (NumberFormatException nfe) { LOG.error("Caught NFE while converting to long ", nfe); return 0L; } catch (IllegalArgumentException iae ) { LOG.error("Caught IAE while converting to long ", iae); return 0L; } } else { return 0L; } } 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 testGetValueAsLong() { NavigableMap<byte[], byte[]> infoValues = new TreeMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); infoValues.put(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.TOTAL_MAPS), Bytes.toBytes(JobDetailsValues.totalMaps)); long expVal = JobDetailsValues.totalMaps; assertEquals(expVal, ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.TOTAL_MAPS), infoValues)); expVal = 0L; assertEquals(expVal, ByteUtil.getValueAsLong(JobHistoryKeys.KEYS_TO_BYTES .get(JobHistoryKeys.TOTAL_REDUCES), infoValues)); infoValues.put(Constants.MEGABYTEMILLIS_BYTES, Bytes.toBytes(JobDetailsValues.megabytemillis)); expVal = JobDetailsValues.megabytemillis; assertEquals(expVal, ByteUtil.getValueAsLong(Constants.MEGABYTEMILLIS_BYTES, infoValues)); expVal = 0L; assertEquals(expVal, ByteUtil.getValueAsLong(Constants.HRAVEN_QUEUE_BYTES, infoValues)); infoValues = new TreeMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); infoValues.put(Bytes.toBytes("checking_iae"), Bytes.toBytes("abc")); assertEquals(expVal, ByteUtil.getValueAsLong(Bytes.toBytes("checking_iae"), infoValues)); }
### Question: ByteUtil { public static String getValueAsString(final byte[] key, final Map<byte[], byte[]> taskValues) { byte[] value = taskValues.get(key); if (value != null) { return Bytes.toString(value); } else { return ""; } } 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 testGetValueAsString() { NavigableMap<byte[], byte[]> infoValues = new TreeMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); infoValues.put(JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOBNAME), Bytes.toBytes(JobDetailsValues.jobName)); assertEquals(JobDetailsValues.jobName, ByteUtil.getValueAsString( JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOBNAME), infoValues)); assertEquals("", ByteUtil.getValueAsString( JobHistoryKeys.KEYS_TO_BYTES.get(JobHistoryKeys.JOB_QUEUE), infoValues)); } @Test public void testGetValueAsString2() { NavigableMap<byte[], byte[]> infoValues = new TreeMap<byte[], byte[]>(Bytes.BYTES_COMPARATOR); infoValues.put(Constants.VERSION_COLUMN_BYTES, Bytes.toBytes(JobDetailsValues.version)); assertEquals(JobDetailsValues.version, ByteUtil.getValueAsString(Constants.VERSION_COLUMN_BYTES, infoValues)); assertEquals("", ByteUtil.getValueAsString(Constants.HRAVEN_QUEUE_BYTES, infoValues)); }
### 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: BatchUtil { public static <E extends Comparable<E>> List<Range<E>> getRanges(Collection<E> collection, int batchSize) { List<Range<E>> rangeList = new LinkedList<Range<E>>(); E currentMin = null; if ((collection != null) && (collection.size() > 0) && (batchSize > 0)) { int index = 1; for (E element : collection) { if (currentMin == null) { currentMin = element; } int mod = index % batchSize; if ((mod == 0) || (index == collection.size())) { Range<E> range = new Range<E>(currentMin, element); rangeList.add(range); currentMin = null; } index++; } } return rangeList; } 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 testGetRanges() { List<Integer> list = Arrays.asList(1,2,3); List<Range<Integer>> rangeList = BatchUtil.getRanges(list, 1); assertEquals(3, rangeList.size()); assertEquals(Integer.valueOf(1), rangeList.get(0).getMin()); assertEquals(Integer.valueOf(1), rangeList.get(0).getMax()); assertEquals(Integer.valueOf(2), rangeList.get(1).getMin()); assertEquals(Integer.valueOf(2), rangeList.get(1).getMax()); assertEquals(Integer.valueOf(3), rangeList.get(2).getMin()); assertEquals(Integer.valueOf(3), rangeList.get(2).getMax()); list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); rangeList = BatchUtil.getRanges(list, 3); assertEquals(4, rangeList.size()); assertEquals(Integer.valueOf(1), rangeList.get(0).getMin()); assertEquals(Integer.valueOf(3), rangeList.get(0).getMax()); assertEquals(Integer.valueOf(4), rangeList.get(1).getMin()); assertEquals(Integer.valueOf(6), rangeList.get(1).getMax()); assertEquals(Integer.valueOf(7), rangeList.get(2).getMin()); assertEquals(Integer.valueOf(9), rangeList.get(2).getMax()); assertEquals(Integer.valueOf(10), rangeList.get(3).getMin()); assertEquals(Integer.valueOf(10), rangeList.get(3).getMax()); rangeList = BatchUtil.getRanges(list, 17); assertEquals(1, rangeList.size()); assertEquals(Integer.valueOf(1), rangeList.get(0).getMin()); assertEquals(Integer.valueOf(10), rangeList.get(0).getMax()); }
### Question: MRJobDescFactory extends JobDescFactoryBase { @Override JobDesc create(QualifiedJobId qualifiedJobId, long submitTimeMillis, Configuration jobConf) { String appId = getAppId(jobConf); long appSubmitTimeMillis = jobConf.getLong(Constants.MR_RUN_CONF_KEY, submitTimeMillis); return create(qualifiedJobId, jobConf, appId, Constants.UNKNOWN, Framework.NONE, appSubmitTimeMillis); } }### Answer: @Test public void testCreate() { MRJobDescFactory mrFac = new MRJobDescFactory(); Configuration conf = new Configuration(); conf.set(Constants.USER_CONF_KEY, "testuser"); QualifiedJobId qid = new QualifiedJobId("clusterId", "job_211212010355_45240"); JobDesc jd = null; jd = mrFac.create(qid, 1354772953639L, conf); Assert.assertEquals(jd.getAppId(), Constants.UNKNOWN); String name = "Crazy Job name! : test 1 2 3!"; String processedName = "Crazy_Job_name__:_test_1_2_3_"; conf.set("mapred.job.name", name); jd = mrFac.create(qid, 1354772953639L, conf); Assert.assertEquals(jd.getAppId(), processedName); name = "Other Crazy Job name! : test 1 2 3!"; processedName = "Other_Crazy_Job_name__:_test_1_2_3_"; conf.set("batch.desc", name); jd = mrFac.create(qid, 1354772953639L, conf); Assert.assertEquals(jd.getAppId(), processedName); conf = new Configuration(); conf.set(Constants.USER_CONF_KEY, "testuser"); name = "Third Crazy Job name! : test 1 2 3!"; processedName = "Third_Crazy_Job_name__:_test_1_2_3_"; conf.set("batch.desc", name); jd = mrFac.create(qid, 1354772953639L, conf); Assert.assertEquals(jd.getAppId(), processedName); }
### 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 QualifiedPathKey getQualifiedPathKey() { return pathKey; } @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 testConstructor1() throws Exception { HdfsStatsKey key1 = new HdfsStatsKey(cluster1, path1, now1); testKeyComponents(key1); assertEquals(key1.getQualifiedPathKey(), new QualifiedPathKey(cluster1, path1)); assertNull(key1.getQualifiedPathKey().getNamespace()); } @Test public void testConstructorFederatedNS() throws Exception { HdfsStatsKey key1 = new HdfsStatsKey(cluster1, path1, namespace1, now1); testKeyComponents(key1); assertEquals(key1.getQualifiedPathKey(), new QualifiedPathKey(cluster1, path1, namespace1)); assertEquals(key1.getQualifiedPathKey().getNamespace(), namespace1); } @Test public void testConstructor2() throws Exception { QualifiedPathKey qk = new QualifiedPathKey(cluster1, path1); HdfsStatsKey key1 = new HdfsStatsKey(qk, now1); testKeyComponents(key1); assertEquals(key1.getQualifiedPathKey(), qk); }
### 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: HdfsStatsKey implements Comparable<Object> { @Override public int compareTo(Object other) { if (other == null) { return -1; } HdfsStatsKey otherKey = (HdfsStatsKey) other; return new CompareToBuilder() .append(this.pathKey, otherKey.getQualifiedPathKey()) .append(this.encodedRunId, otherKey.getEncodedRunId()) .toComparison(); } @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 testCompareTo() { long ts = 1392217200L; HdfsStatsKey key1 = new HdfsStatsKey(cluster1, path1, (Long.MAX_VALUE - ts)); HdfsStatsKey key2 = new HdfsStatsKey(cluster1, path1, (Long.MAX_VALUE - ts - 10000)); assertTrue(key1.compareTo(key2) > 0); key2 = new HdfsStatsKey(cluster1, path1, (Long.MAX_VALUE - ts + 10000)); assertTrue(key1.compareTo(key2) < 0); key2 = new HdfsStatsKey(cluster1, path1, (Long.MAX_VALUE - ts)); assertTrue(key1.compareTo(key2) == 0); key1 = new HdfsStatsKey(cluster1, path1, namespace1, (Long.MAX_VALUE - ts)); key2 = new HdfsStatsKey(cluster1, path1, namespace1, (Long.MAX_VALUE - ts - 10000)); assertTrue(key1.compareTo(key2) > 0); }
### 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: JobId implements Comparable<JobId> { @Override public int compareTo(JobId o) { if (o == null) { return -1; } return new CompareToBuilder() .append(this.jobEpoch, o.getJobEpoch()) .append(this.jobSequence, o.getJobSequence()) .toComparison(); } @JsonCreator JobId(@JsonProperty("jobIdString") String jobId); JobId(long epoch, long seq); JobId(JobId idToCopy); long getJobEpoch(); long getJobSequence(); String getJobIdString(); String toString(); @Override int compareTo(JobId o); @Override boolean equals(Object other); @Override int hashCode(); }### Answer: @Test public void testJobIdOrdering() { String job1 = "job_20120101000000_0001"; String job2 = "job_20120101000000_1111"; String job3 = "job_20120101000000_2222"; String job4 = "job_20120101000000_11111"; String job5 = "job_20120201000000_0001"; JobId jobId1 = new JobId(job1); JobId jobId2 = new JobId(job2); JobId jobId3 = new JobId(job3); JobId jobId4 = new JobId(job4); JobId jobId5 = new JobId(job5); JobIdConverter conv = new JobIdConverter(); byte[] job1Bytes = conv.toBytes(jobId1); byte[] job2Bytes = conv.toBytes(jobId2); byte[] job3Bytes = conv.toBytes(jobId3); byte[] job4Bytes = conv.toBytes(jobId4); byte[] job5Bytes = conv.toBytes(jobId5); assertTrue(Bytes.compareTo(job1Bytes, job2Bytes) < 0); assertTrue(Bytes.compareTo(job2Bytes, job3Bytes) < 0); assertTrue(Bytes.compareTo(job3Bytes, job4Bytes) < 0); assertTrue(Bytes.compareTo(job4Bytes, job5Bytes) < 0); }
### Question: ScaldingJobDescFactory extends JobDescFactoryBase { @Override JobDesc create(QualifiedJobId qualifiedJobId, long submitTimeMillis, Configuration jobConf) { String appId = getAppId(jobConf); if (Constants.UNKNOWN.equals(appId)) { appId = cleanAppId(jobConf.get(Constants.CASCADING_APP_ID_CONF_KEY)); } String version = jobConf.get(Constants.CASCADING_VERSION_CONF_KEY); long scaldingSubmitTimeMillis = getFlowSubmitTimeMillis(jobConf, submitTimeMillis); return create(qualifiedJobId, jobConf, appId, version, Framework.SCALDING, scaldingSubmitTimeMillis); } }### Answer: @Test public void testAppIdParsing() throws Exception { String username = "testuser"; Configuration c = new Configuration(); c.set("mapred.job.name", jobName1); c.set("user.name", username); c.set("cascading.app.id", "93543E9B29A4CD14E0556849A93E171B"); c.set("cascading.flow.id", "0A2CEB3C5DFB905802EB96D1AE0C04D5"); ScaldingJobDescFactory factory = new ScaldingJobDescFactory(); QualifiedJobId jobId = new QualifiedJobId("test@local", "job_201206010000_0001"); long now = System.currentTimeMillis(); JobDesc desc = factory.create(jobId, now, c); assertJobDesc(desc, jobId, username, "93543E9B29A4CD14E0556849A93E171B"); c.set("mapred.job.name", jobName2); desc = factory.create(jobId, now, c); assertJobDesc(desc, jobId, username, expectedAppId2); c.set("mapred.job.name", jobName3); desc = factory.create(jobId, now, c); assertJobDesc(desc, jobId, username, expectedAppId3); c.set("mapred.job.name", jobName4); desc = factory.create(jobId, now, c); assertJobDesc(desc, jobId, username, expectedAppId4); c.set("mapred.job.name", jobName5); desc = factory.create(jobId, now, c); assertJobDesc(desc, jobId, username, expectedAppId5); } @Test public void testRunIdParsing() throws Exception { Configuration c = new Configuration(); c.set("mapred.job.name", jobName1); c.set("cascading.app.id", "93543E9B29A4CD14E0556849A93E171B"); c.set("cascading.flow.id", "0A2CEB3C5DFB905802EB96D1AE0C04D5"); c.set("user.name", "testuser"); ScaldingJobDescFactory factory = new ScaldingJobDescFactory(); QualifiedJobId jobId = new QualifiedJobId("test@local", "job_201206010000_0001"); long now = System.currentTimeMillis(); LOG.info("Using "+now+" as submit time"); long expectedMonthStart = DateUtil.getMonthStart(now); LOG.info("Month start set to "+expectedMonthStart); JobDesc desc = factory.create(jobId, now, c); LOG.info("Set runId to "+desc.getRunId()); assertTrue(expectedMonthStart <= desc.getRunId()); long monthEnd = expectedMonthStart + DateUtil.MONTH_IN_MILLIS; assertTrue("runId should be less than "+monthEnd, monthEnd > desc.getRunId()); Configuration c2 = new Configuration(c); c2.set(Constants.CASCADING_RUN_CONF_KEY, Long.toString(now)); desc = factory.create(jobId, now, c2); assertEquals(now, desc.getRunId()); }
### 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: HdfsStatsService { public static long getOlderRunId(int i, long runId) { int randomizedHourInSeconds = (int) (Math.random() * 23) * 3600; if (i >= HdfsConstants.ageMult.length) { throw new ProcessingException("Can't look back in time that far " + i + ", only upto " + HdfsConstants.ageMult.length); } long newTs = runId - (HdfsConstants.ageMult[i] * HdfsConstants.NUM_SECONDS_IN_A_DAY + randomizedHourInSeconds); LOG.info(" Getting older runId for " + runId + ", returning " + newTs + " since ageMult[" + i + "]=" + HdfsConstants.ageMult[i] + " randomizedHourInSeconds=" + randomizedHourInSeconds); return newTs; } 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 TestGetOlderRunId() { long ts = 1392123600L; int retryCount = 0; for (int i = 0; i < HdfsConstants.ageMult.length; i++) { long oldts = HdfsStatsService.getOlderRunId(retryCount, ts); long diff = (ts - oldts) / HdfsConstants.NUM_SECONDS_IN_A_DAY; assertTrue(diff <= HdfsConstants.ageMult[retryCount]); retryCount++; } } @Test(expected = ProcessingException.class) public void testGetOlderRunIdsException() { int i = HdfsConstants.ageMult.length + 10; HdfsStatsService.getOlderRunId(i, System.currentTimeMillis() / 1000); }
### Question: HdfsStatsService { public List<HdfsStats> getHdfsTimeSeriesStats(String cluster, String path, int limit, long starttime, long endtime) throws IOException { Scan scan = GenerateScanFuzzy(starttime, endtime, cluster, path); return createFromScanResults(cluster, path, scan, limit, Boolean.TRUE, starttime, endtime); } 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 testFuzzy() throws IOException { final long startts = 1392217200L; String cluster1 = "cluster1_timeseries"; String pathPrefix = "/dir_timeseries/dir12345"; String pathhello = "/hello1/hello2"; int numberStatsExpected = 5; loadTimeSeries(cluster1, pathPrefix, numberStatsExpected, startts); loadTimeSeries(cluster1, pathhello, numberStatsExpected, startts); String cluster4 = "yet_another_one"; String pathPrefix4 = "/dir_timeseries/dir12345"; int numberStatsExpected4 = 5; loadTimeSeries(cluster4, pathPrefix4, numberStatsExpected4, startts); String cluster3 = "abc_something_else"; String pathPrefix3 = "/dir_timeseries/dir12345"; int numberStatsExpected3 = 5; long endts3 = loadTimeSeries(cluster3, pathPrefix3, numberStatsExpected3, startts); HdfsStatsService hs = null; hs = new HdfsStatsService(UTIL.getConfiguration(), hbaseConnection); List<HdfsStats> h3 = hs.getHdfsTimeSeriesStats(cluster1, pathPrefix, Integer.MAX_VALUE, startts + 7200 * 3 + 1, startts - 3600); assertEquals(4, h3.size()); HdfsStatsService hs2 = new HdfsStatsService(UTIL.getConfiguration(), hbaseConnection); List<HdfsStats> h5 = hs2.getHdfsTimeSeriesStats(cluster3, pathPrefix3, Integer.MAX_VALUE, endts3, startts - 3600); assertEquals(numberStatsExpected3, h5.size()); }
### Question: JobHistoryService { public JobDetails getJobByJobID(String cluster, String jobId) throws IOException { return getJobByJobID(cluster, jobId, false); } JobHistoryService(Configuration hbaseConf, Connection hbaseConnection); Flow getLatestFlow(String cluster, String user, String appId); Flow getLatestFlow(String cluster, String user, String appId, boolean populateTasks); List<Flow> getFlowSeries(String cluster, String user, String appId, int limit); Flow getFlow(String cluster, String user, String appId, long runId, boolean populateTasks); Flow getFlowByJobID(String cluster, String jobId, boolean populateTasks); List<Flow> getFlowSeries(String cluster, String user, String appId, String version, boolean populateTasks, int limit); List<Flow> getFlowSeries(String cluster, String user, String appId, String version, boolean populateTasks, long startTime, long endTime, int limit); List<Flow> getFlowTimeSeriesStats(String cluster, String user, String appId, String version, long startTime, long endTime, int limit, byte[] startRow); JobDetails getJobByJobID(String cluster, String jobId); JobDetails getJobByJobID(String cluster, String jobId, boolean populateTasks); JobDetails getJobByJobID(QualifiedJobId jobId, boolean populateTasks); static Configuration parseConfiguration( Map<byte[], byte[]> keyValues); static CounterMap parseCounters(byte[] prefix, Map<byte[], byte[]> keyValues); static List<Put> getHbasePuts(JobDesc jobDesc, Configuration jobConf); int removeJob(JobKey key); }### Answer: @Test public void testGetJobByJobID() throws Exception { flowDataGen.loadFlow("c1@local", "buser", "getJobByJobID", 1234, "a", 3, 10, idService, historyTable); JobHistoryService service = null; service = new JobHistoryService(UTIL.getConfiguration(), hbaseConnection); Flow flow = service.getLatestFlow("c1@local", "buser", "getJobByJobID"); assertNotNull(flow); assertEquals(3, flow.getJobs().size()); for (JobDetails j : flow.getJobs()) { JobKey key = j.getJobKey(); JobDetails j2 = service.getJobByJobID(key.getQualifiedJobId(), false); assertJob(j, j2); } }
### Question: AppSummaryService { long getTimestamp(long runId, AggregationConstants.AGGREGATION_TYPE aggType) { if (AggregationConstants.AGGREGATION_TYPE.DAILY.equals(aggType)) { long dayTimestamp = runId - (runId % Constants.MILLIS_ONE_DAY); return dayTimestamp; } else if (AggregationConstants.AGGREGATION_TYPE.WEEKLY.equals(aggType)) { Calendar c = Calendar.getInstance(); c.setTimeInMillis(runId); int d = c.get(Calendar.DAY_OF_WEEK); long weekTimestamp = runId - (d - 1) * Constants.MILLIS_ONE_DAY; weekTimestamp = weekTimestamp - weekTimestamp % Constants.MILLIS_ONE_DAY; return weekTimestamp; } return 0L; } 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 testGetDayTimestamp() throws IOException { long ts = 1402698420000L; long expectedTop = 1402617600000L; AppSummaryService appSummaryService = new AppSummaryService(hbaseConnection); assertEquals((Long) expectedTop, (Long) appSummaryService.getTimestamp(ts, AggregationConstants.AGGREGATION_TYPE.DAILY)); } @Test public void testGetWeekTimestamp() throws IOException { long ts = 1402698420000L; long expectedTop = 1402185600000L; AppSummaryService appSummaryService = new AppSummaryService(hbaseConnection); assertEquals((Long) expectedTop, (Long) appSummaryService.getTimestamp(ts, AggregationConstants.AGGREGATION_TYPE.WEEKLY)); }
### 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: AppVersionService { public List<VersionInfo> getDistinctVersions(String cluster, String user, String appId) throws IOException { Get get = new Get(getRowKey(cluster, user, appId)); List<VersionInfo> versions = Lists.newArrayList(); Long ts = 0L; Table versionsTable = null; try { versionsTable = hbaseConnection .getTable(TableName.valueOf(Constants.HISTORY_APP_VERSION_TABLE)); Result r = versionsTable.get(get); if (r != null && !r.isEmpty()) { for (Cell c : r.listCells()) { ts = 0L; try { ts = Bytes.toLong(CellUtil.cloneValue(c)); versions.add(new VersionInfo( Bytes.toString(CellUtil.cloneQualifier(c)), ts)); } catch (IllegalArgumentException e1) { LOG.error( "Caught conversion error while converting timestamp to long value " + e1.getMessage()); throw e1; } } } if (versions.size() > 0) { Collections.sort(versions); } } finally { if (versionsTable != null) { versionsTable.close(); } } return versions; } AppVersionService(Connection hbaseConnection); String getLatestVersion(String cluster, String user, String appId); List<VersionInfo> getDistinctVersions(String cluster, String user, String appId); boolean addVersion(String cluster, String user, String appId, String version, long timestamp); }### Answer: @Test public void testGetDistinctVersions() throws Exception { Configuration c = UTIL.getConfiguration(); { String appId = "getDistinctVersions"; AppVersionService service = null; service = new AppVersionService(hbaseConnection); List<VersionInfo> latest = service.getDistinctVersions(cluster, user, appId); assertEquals(latest.size(), 0); } { String appId = "getDistinctVersions"; AppVersionService service = null; service = new AppVersionService(hbaseConnection); service.addVersion(cluster, user, appId, "v1", 10); service.addVersion(cluster, user, appId, "v2", 30); service.addVersion(cluster, user, appId, "v1", 8390); service.addVersion(cluster, user, appId, "v1", 90); service.addVersion(cluster, user, appId, "v1", 80); List<VersionInfo> latest = service.getDistinctVersions(cluster, user, appId); assertEquals(latest.size(), 2); HashSet<String> expVersions = new HashSet<String>(); expVersions.add("v1"); expVersions.add("v2"); for (int i = 0; i < latest.size(); i++) { assertTrue(expVersions.contains(latest.get(i).getVersion())); } } }
### Question: JobHistoryRawService { public long getApproxSubmitTime(Result value) throws MissingColumnInResultException { if (value == null) { throw new IllegalArgumentException( "Cannot get last modification time from " + "a null hbase result"); } Cell cell = value.getColumnLatestCell(Constants.INFO_FAM_BYTES, Constants.JOBHISTORY_LAST_MODIFIED_COL_BYTES); if (cell == null) { throw new MissingColumnInResultException(Constants.INFO_FAM_BYTES, Constants.JOBHISTORY_LAST_MODIFIED_COL_BYTES); } byte[] lastModTimeBytes = CellUtil.cloneValue(cell); long lastModTime = Bytes.toLong(lastModTimeBytes); long jobSubmitTimeMillis = lastModTime - Constants.AVERGAE_JOB_DURATION; LOG.debug("Approximate job submit time is " + jobSubmitTimeMillis + " based on " + lastModTime); return jobSubmitTimeMillis; } JobHistoryRawService(Connection hbaseConnection); List<Scan> getHistoryRawTableScans(String cluster, String minJobId, String maxJobId, boolean reprocess, int batchSize); Scan getHistoryRawTableScan(String cluster, String minJobId, String maxJobId, boolean reprocess, boolean includeRaw); Configuration getRawJobConfiguration(QualifiedJobId jobId); String getRawJobHistory(QualifiedJobId jobId); byte[] getRawJobHistoryBytes(QualifiedJobId jobId); Configuration createConfigurationFromResult(Result result); byte[] getRowKey(String cluster, String jobId); QualifiedJobId getQualifiedJobIdFromResult(Result result); InputStream getJobHistoryInputStreamFromResult(Result result); Put getJobProcessedSuccessPut(byte[] row, boolean success); long getApproxSubmitTime(Result value); Put getJobSubmitTimePut(byte[] row, long submitTimeMillis); void markJobForReprocesssing(QualifiedJobId jobId); byte[] getJobHistoryRawFromResult(Result value); Put getAggregatedStatusPut(byte[] row, byte[] col, Boolean status); boolean getStatusAgg(byte[] row, byte[] col); }### Answer: @Test(expected = IllegalArgumentException.class) public void testGetApproxSubmitTimeNull() throws IOException, MissingColumnInResultException { JobHistoryRawService rawService = new JobHistoryRawService(hbaseConnection); long st = rawService.getApproxSubmitTime(null); assertEquals(0L, st); } @Test(expected = MissingColumnInResultException.class) public void testGetApproxSubmitTimeMissingCol() throws IOException, MissingColumnInResultException { JobHistoryRawService rawService = new JobHistoryRawService(hbaseConnection); Result result = new Result(); long st = rawService.getApproxSubmitTime(result); assertEquals(0L, st); } @Test public void testGetApproxSubmitTime() throws IOException, MissingColumnInResultException { JobHistoryRawService rawService = new JobHistoryRawService(hbaseConnection); Cell[] cells = new Cell[1]; long modts = 1396550668000L; cells[0] = CellUtil.createCell(Bytes.toBytes("someRowKey"), Constants.INFO_FAM_BYTES, Constants.JOBHISTORY_LAST_MODIFIED_COL_BYTES, HConstants.LATEST_TIMESTAMP, KeyValue.Type.Put.getCode(), Bytes.toBytes(modts)); Result result = Result.create(cells); long st = rawService.getApproxSubmitTime(result); long expts = modts - Constants.AVERGAE_JOB_DURATION; assertEquals(expts, st); }
### 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> { @Override public int compareTo(Object other) { if (other == null) { return -1; } JobKey otherKey = (JobKey)other; return new CompareToBuilder().appendSuper(super.compareTo(otherKey)) .append(this.jobId, otherKey.getJobId()) .toComparison(); } 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 testOrdering() { JobKey key1 = new JobKey("c1@local", "auser", "app", 1234L, "job_20120101000000_0001"); JobKey key2 = new JobKey("c1@local", "auser", "app", 1234L, "job_20120101000000_2222"); JobKey key3 = new JobKey("c1@local", "auser", "app", 1234L, "job_20120101000000_11111"); JobKey key4 = new JobKey("c1@local", "auser", "app", 1345L, "job_20120101000000_0001"); JobKeyConverter conv = new JobKeyConverter(); byte[] key1Bytes = conv.toBytes(key1); byte[] key2Bytes = conv.toBytes(key2); byte[] key3Bytes = conv.toBytes(key3); byte[] key4Bytes = conv.toBytes(key4); assertTrue(Bytes.compareTo(key4Bytes, key1Bytes) < 0); assertTrue(Bytes.compareTo(key1Bytes, key2Bytes) < 0); assertTrue(Bytes.compareTo(key2Bytes, key3Bytes) < 0); }
### 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: SqlParser { public Statement createStatement(String sql) { return (Statement) invokeParser("statement", sql, PardSqlBaseParser::singleStatement); } Statement createStatement(String sql); Expression createExpression(String expression); }### Answer: @Test public void testSelectJoin() { String sql = "SELECT id, name FROM test0 JOIN test1 ON test0.id=test1.id where test0.id>10"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testInsert() { String sql = "INSERT INTO test VALUES(10, abc, 10.0)"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testCreateSchema() { String sql = "CREATE SCHEMA IF NOT EXISTS test"; Statement statement = parser.createStatement(sql); CreateSchema expected = new CreateSchema(QualifiedName.of("test"), true); System.out.println(statement.toString()); assertEquals(statement.toString(), expected.toString()); } @Test public void testDropSchema() { String sql = "Drop SCHEMA IF EXISTS test"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testUse() { String sql = "use schema"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testCreateTableVP() { String sql = "CREATE TABLE orders_range\n" + "(id INT PRIMARY KEY, name VARCHAR(30)) ON node1,\n" + "(id INT PRIMARY KEY, order_date DATE)"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testCreateTableHPHash() { String sql = "CREATE TABLE orders_range\n" + "(\n" + "id INT PRIMARY KEY,\n" + "name VARCHAR(30),\n" + "order_date DATE\n" + ") PARTITION BY HASH(id) PARTITIONS 4"; Statement statement = parser.createStatement(sql); CreateTable ctstmt = (CreateTable) statement; QualifiedName name = ctstmt.getName(); System.out.println("prefix:" + (name.getPrefix().isPresent() ? name.getPrefix().get() : null)); System.out.println("suffix:" + name.getSuffix()); System.out.println("orignal part:"); name.getOriginalParts().forEach(System.out::println); System.out.println(statement.toString()); } @Test public void testCreateTableHPList() { String sql = "CREATE TABLE orders_range\n" + "(\n" + "id INT PRIMARY KEY,\n" + "name VARCHAR(30),\n" + "order_date DATE\n" + ") PARTITION BY LIST\n" + "(\n" + "p0 id IN (1, 2, 3) AND name IN ('alice', 'bob') ON node0,\n" + "p1 id IN (4, 5) ON node1,\n" + "p2 id IN (8, 9, 10)\n" + ")"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testCreateTableHPRange() { String sql = "CREATE TABLE orders_range\n" + "(\n" + "id INT PRIMARY KEY,\n" + "name VARCHAR(30),\n" + "order_date DATE\n" + ") PARTITION BY RANGE\n" + "(\n" + "p0 id < 5 AND order_date >= '2017-01-01' ON node0,\n" + "p1 id < 10 ON node1,\n" + "p2 id < 15 ON node2,\n" + "p3 id < MAXVALUE\n" + ")"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); } @Test public void testSelectSimple() { String sql = "SELECT * FROM test WHERE id > 10 GROUP BY name ORDER BY order_date LIMIT 10"; Statement statement = parser.createStatement(sql); System.out.println(statement.toString()); }
### 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: Expr implements Serializable { public static Expr generalReplace(Expr e1, Item from, Item to) { Expr e = Expr.clone(e1); if (e instanceof SingleExpr) { SingleExpr se = (SingleExpr) e; Item lv = se.getLvalue(); Item rv = se.getRvalue(); if (lv.equals(from)) { lv = Item.clone(to); } if (rv.equals(from)) { rv = Item.clone(to); } return new SingleExpr(lv, rv, se.getCompareType()); } else if (e instanceof CompositionExpr) { CompositionExpr ce = (CompositionExpr) e; for (int i = 0; i < ce.getConditions().size(); i++) { Expr ex = ce.getConditions().get(i); ce.getConditions().set(i, generalReplace(ex, from, to)); } return ce; } else if (e instanceof UnaryExpr) { UnaryExpr ue = (UnaryExpr) e; return new UnaryExpr(ue.getCompareType(), generalReplace(ue.getExpression(), from, to)); } else if (e instanceof TrueExpr || e instanceof FalseExpr) { return e; } return e; } Expr(); static Expr replace(Expr e1, ColumnItem from, ColumnItem to); static Expr replaceTableName(Expr e1, String from, String to); static Expr generalReplace(Expr e1, Item from, Item to); static Expr clone(Expr expr); static List<String> extractTableColumn(Expr expr, String tableName); static List<SingleExpr> extractTableJoinExpr(Expr expr); static Expr extractTableColumnFilter(Expr expr, List<String> projectList); static Expr extractTableFilter(Expr expr, String tableName); static Expr parse(Condition cond, String tableName); static Expr optimize(Expr e1, LogicOperator opt); static Expr and(Expr e1, Expr e2, LogicOperator opt); static Expr or(Expr e1, Expr e2, LogicOperator opt); static Expr parse(List<Condition> conditions, String tableName); static Expr parse(Expression expr); abstract String toString(); abstract int hashCode(); abstract boolean equals(Object o); abstract Expression toExpression(); static PushDownLaw pdAnd; static PushDownLaw pdOr; static TrueFalseLaw tfLaw; static MinimalItemLaw milaw; }### Answer: @Test public void testGeneralReplace() { SqlParser parser = new SqlParser(); String expr = "a.id>'E100' and a.age<18"; Expression expression = parser.createExpression(expr); RowConstructor constructor = new RowConstructor(); constructor.appendString("'E101'"); constructor.appendString("'Geroge'"); constructor.appendString("'Beijing'"); constructor.appendInt(12); Row row = constructor.build(); String[] col = new String[]{"id", "name", "city", "age"}; List<Column> cols = new ArrayList<>(); for (int i = 0; i < col.length; i++) { Column c = new Column(); c.setColumnName(col[i]); c.setTableName("a"); c.setDataType(DataTypeInt.VARCHAR); if (i == col.length - 1) { c.setDataType(DataTypeInt.INT); } cols.add(c); } boolean match = match(expression, row, cols); System.out.println(match); expr = "a.id>'E200' and a.age<18"; expression = parser.createExpression(expr); match = match(expression, row, cols); System.out.println(match); }
### Question: PersistParser extends Parser { @Override public Definition parse(String processName, int processVersion) { DefinitionDO definitionDO; if (processVersion == 0) { DefinitionDOExample definitionDOExample = new DefinitionDOExample(); definitionDOExample.createCriteria().andDefinitionNameEqualTo(processName) .andOwnSignEqualTo(CoreModule.getInstance().getOwnSign()) .andStatusEqualTo(true); List<DefinitionDO> definitionDOList = definitionDOMapper.selectByExampleWithBLOBs(definitionDOExample); definitionDO = definitionDOList != null && !definitionDOList.isEmpty() ? definitionDOList.get(0) : null; } else { DefinitionDOExample definitionDOExample = new DefinitionDOExample(); definitionDOExample.createCriteria().andDefinitionNameEqualTo(processName).andDefinitionVersionEqualTo( processVersion).andOwnSignEqualTo(CoreModule.getInstance().getOwnSign()); List<DefinitionDO> definitionDOList = definitionDOMapper.selectByExampleWithBLOBs(definitionDOExample); definitionDO = definitionDOList != null && !definitionDOList.isEmpty() ? definitionDOList.get(0) : null; } require(definitionDO != null, String.format("definition [%s:%s ] not found in DB", processName, processVersion)); Document processXML; try { processXML = DocumentHelper.parseText(definitionDO.getContent()); } catch (DocumentException e) { logger.error("parse definition content error:" + e.getMessage(), e); logger.error("error content:\n" + definitionDO.getContent()); throw new IllegalArgumentException("parse definition content error", e); } return super.parser0(processName, definitionDO.getDefinitionVersion(), processXML, definitionDO.getStatus()); } @Override boolean needRefresh(String processName, int processVersion, Definition oldDefinition); @Override Definition parse(String processName, int processVersion); }### Answer: @Test public void testPersistParser() { SAXReader reader = new SAXReader(); URL url = this.getClass().getResource("/persist_definition.xml"); Document document = null; try { document = reader.read(url); } catch (DocumentException e) { e.printStackTrace(); } String definitionContent = document.asXML(); DefinitionHelper.getInstance().deployDefinition("persist_definition", "测试", definitionContent, true); DefinitionHelper.getInstance().deployDefinition("persist_definition", "测试", definitionContent, true); Definition definition = persistParser.parse("persist_definition", 0); Assert.assertEquals("persist_definition", definition.getName()); Assert.assertEquals(2, definition.getVersion()); Assert.assertNotNull(definition.getState("i'm start")); Definition definition1 = persistParser.parse("persist_definition", 1); Assert.assertEquals(1, definition1.getVersion()); }
### Question: PersistMachine extends Machine { public String getBizId() { return bizId; } protected PersistMachine(String bizId, String processName, int processVersion, ProcessDO processDO, ProcessDOMapper processDOMapper , StateDOMapper stateDOMapper , PersistHelper persistHelper , TaskDOMapper taskDOMapper , ParticipationDOMapper participationDOMapper , JobDOMapper jobDOMapper); List<StateDOWithBLOBs> getStateDOList(); String getStatePathString(); void rollback(); String getBizId(); boolean isExist(); boolean isCompleted(); ProcessDO getProcessDO(); }### Answer: @Test public void testMachineRunPerf() throws InterruptedException { final int count = 500; int threadCount = 5; long startTime = System.currentTimeMillis(); Thread[] threadList = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { threadList[i] = new Thread("perf-thread-" + i) { @Override public void run() { for (int i = 0; i < count; i++) { String bizId = getBizId(); PersistMachine m = persistMachineFactory.newInstance(bizId, "process"); m.addContext("goto", 2); m.addContext("_i", 3); m.run(); System.out.println("thread:" + this.getName() + " count:" + i + " bizId:" + bizId); } } }; } for (Thread t : threadList) { t.start(); } for (Thread t : threadList) { t.join(); } long duration = System.currentTimeMillis() - startTime; System.out.println("total time:" + duration + "ms"); System.out.println("average time:" + (duration / (count * threadCount)) + "ms"); } @Test public void PersistMachineTest_run_not_DB() { String bizId = getBizId(); PersistMachine p = persistMachineFactory.newInstance(bizId, "process"); p.addContext("goto", 2); p.addContext("i", 3); p.run(); } @Test public void testMachineRunWithException() { PersistMachine p = persistMachineFactory.newInstance(getBizId(), "process_with_biz_exception"); p.addContext("goto", 2); p.addContext("_i", 1); try { p.run(); Assert.fail("Should get exception here!"); } catch (Exception e) { System.out.println("get a exception:" + e.getMessage() + "\n"); e.printStackTrace(); } PersistMachine p2 = persistMachineFactory.newInstance(p.getBizId()); Assert.assertEquals("state2", p2.getCurrentStateName()); p2.addContext("_i", 0); p2.run(); Assert.assertEquals("end", p2.getCurrentStateName()); } @Test public void testMachineRunWithEvent() { PersistMachine p = persistMachineFactory.newInstance(getBizId(), "process_with_event_p"); p.run(); System.out.println(p.getCurrentStateName()); Assert.assertEquals("some info", p.getContext("_info")); PersistMachine p2 = persistMachineFactory.newInstance(p.getBizId()); p2.addContext("goto", 2); p2.addContext("_i", 3); p2.addContext("info", "some info1"); p2.run(); Assert.assertEquals("wok", p2.getContext("_errorInfo")); System.out.println(p2.getContext()); Assert.assertEquals(6, p2.getContext("_a")); }
### Question: State extends RunnableState { @Override public StateLike parse(Element elem) { super.parse(elem); if (elem.attributeValue(REPEATLIST_TAG) != null) { repeatList = elem.attributeValue(REPEATLIST_TAG); } if (elem.attributeValue(IGNOREWEEKEND_TAG) != null) { ignoreWeekend = Boolean.valueOf(elem.attributeValue(IGNOREWEEKEND_TAG)); } List<Element> invokesPaths = elem.selectNodes(INVOKES_TAG); for (Element node : invokesPaths) { for (Iterator i = node.elementIterator(); i.hasNext(); ) { Element child = (Element)i.next(); try { invokes.add(InvokableFactory.newInstance(child.getName(), child)); } catch (RuntimeException re) { logger.error(String.format("实例Invokable类型时候出错,类型为: %s , 异常为: %s", child.getName(), re.toString())); throw re; } catch (Throwable e) { logger.error(String.format("实例Invokable类型时候出错,类型为: %s , 异常为: %s", child.getName(), e.toString())); throw new UndeclaredThrowableException(e, "error happened when newInstance Invokable class:" + child.getName()); } } } return this; } @Override Result execute(Map<String, Object> context); @Override StateLike parse(Element elem); String getRepeatList(); void setRepeatList(String repeatList); Boolean getIgnoreWeekend(); void setIgnoreWeekend(Boolean ignoreWeekend); }### Answer: @Test public void testWillGo() { State state = new State(); String xml = "<state name=\"state\">\n" + " <paths>\n" + " <path to=\"1\" expr=\"i==1\"/>\n" + " <path to=\"2\" expr=\"i==2\"/>\n" + " </paths>\n" + " </state>"; Document document = null; try { document = DocumentHelper.parseText(xml); } catch (DocumentException e) { e.printStackTrace(); } StateLike s = state.parse(document.getRootElement()); Map m = new HashMap(); m.put("i", 2); String result = null; try { result = s.willGo(m); } catch (Throwable e) { e.printStackTrace(); } Assert.assertEquals("2", result); }
### 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: XMLParser { List<BlockInfo> parseLine(String line) throws IOException { if (line.contains("<inode>")) { transitionTo(State.INODE); } if (line.contains("<type>FILE</type>")) { transitionTo(State.FILE); } List<String> replicationStrings = valuesFromXMLString(line, "replication"); if (!replicationStrings.isEmpty()) { if (replicationStrings.size() > 1) { throw new IOException(String.format("Found %s replication strings", replicationStrings.size())); } transitionTo(State.FILE_WITH_REPLICATION); currentReplication = Short.parseShort(replicationStrings.get(0)); } Matcher blockMatcher = BLOCK_PATTERN.matcher(line); List<BlockInfo> blockInfos = new ArrayList<>(); while (blockMatcher.find()) { if (currentState != State.FILE_WITH_REPLICATION) { throw new IOException("Found a block string when in state: " + currentState); } long id = Long.parseLong(blockMatcher.group(1)); long gs = Long.parseLong(blockMatcher.group(2)); long size = Long.parseLong(blockMatcher.group(3)); blockInfos.add(new BlockInfo(id, gs, size, currentReplication)); } if (line.contains("</inode>")) { transitionTo(State.DEFAULT); } return blockInfos; } }### Answer: @Test public void testBlocksFromLine() throws Exception { String[] lines = { "<INodeSection><lastInodeId>1" + "</lastInodeId><inode><id>2</id><type>FILE</type>" + "<name>fake-file</name>" + "<replication>3</replication><mtime>3</mtime>" + "<atime>4</atime>" + "<perferredBlockSize>5</perferredBlockSize>" + "<permission>hdfs:hdfs:rw-------</permission>" + "<blocks><block><id>6</id><genstamp>7</genstamp>" + "<numBytes>8</numBytes></block>" + "<block><id>9</id><genstamp>10</genstamp>" + "<numBytes>11</numBytes></block></inode>", "<inode><type>DIRECTORY</type></inode>", "<inode><type>FILE</type>", "<replication>12</replication>", "<blocks><block><id>13</id><genstamp>14</genstamp><numBytes>15</numBytes></block>", "</inode>" }; Map<BlockInfo, Short> expectedBlockCount = new HashMap<>(); expectedBlockCount.put(new BlockInfo(6, 7, 8), (short) 3); expectedBlockCount.put(new BlockInfo(9, 10, 11), (short) 3); expectedBlockCount.put(new BlockInfo(13, 14, 15), (short) 12); final Map<BlockInfo, Short> actualBlockCount = new HashMap<>(); XMLParser parser = new XMLParser(); for (String line : lines) { for (BlockInfo info : parser.parseLine(line)) { actualBlockCount.put(info, info.getReplication()); } } for (Map.Entry<BlockInfo, Short> expect : expectedBlockCount.entrySet()) { assertEquals(expect.getValue(), actualBlockCount.get(expect.getKey())); } }
### Question: AuditLogDirectParser implements AuditCommandParser { @Override public AuditReplayCommand parse(Text inputLine, Function<Long, Long> relativeToAbsolute) throws IOException { Matcher m = MESSAGE_ONLY_PATTERN.matcher(inputLine.toString()); if (!m.find()) { throw new IOException("Unable to find valid message pattern from audit log line: " + inputLine); } long relativeTimestamp; try { relativeTimestamp = AUDIT_DATE_FORMAT.parse(m.group(1)).getTime() - startTimestamp; } catch (ParseException p) { throw new IOException("Exception while parsing timestamp from audit log", p); } String auditMessageSanitized = m.group(2).replace("(options=", "(options:"); Map<String, String> parameterMap = AUDIT_SPLITTER.split(auditMessageSanitized); return new AuditReplayCommand(relativeToAbsolute.apply(relativeTimestamp), SPACE_SPLITTER.split(parameterMap.get("ugi")).iterator().next(), parameterMap.get("cmd").replace("(options:", "(options="), parameterMap.get("src"), parameterMap.get("dst"), parameterMap.get("ip")); } @Override void initialize(Configuration conf); @Override AuditReplayCommand parse(Text inputLine, Function<Long, Long> relativeToAbsolute); static final String AUDIT_START_TIMESTAMP_KEY; }### Answer: @Test public void testSimpleInput() throws Exception { Text in = getAuditString("1970-01-01 00:00:11,000", "fakeUser", "listStatus", "sourcePath", "null"); AuditReplayCommand expected = new AuditReplayCommand(1000, "fakeUser", "listStatus", "sourcePath", "null", "0.0.0.0"); assertEquals(expected, parser.parse(in, IDENTITY_FN)); } @Test public void testInputWithRenameOptions() throws Exception { Text in = getAuditString("1970-01-01 00:00:11,000", "fakeUser", "rename (options=[TO_TRASH])", "sourcePath", "destPath"); AuditReplayCommand expected = new AuditReplayCommand(1000, "fakeUser", "rename (options=[TO_TRASH])", "sourcePath", "destPath", "0.0.0.0"); assertEquals(expected, parser.parse(in, IDENTITY_FN)); } @Test public void testInputWithTokenAuth() throws Exception { Text in = getAuditString("1970-01-01 00:00:11,000", "fakeUser (auth:TOKEN)", "create", "sourcePath", "null"); AuditReplayCommand expected = new AuditReplayCommand(1000, "fakeUser", "create", "sourcePath", "null", "0.0.0.0"); assertEquals(expected, parser.parse(in, IDENTITY_FN)); } @Test public void testInputWithProxyUser() throws Exception { Text in = getAuditString("1970-01-01 00:00:11,000", "proxyUser (auth:TOKEN) via fakeUser", "create", "sourcePath", "null"); AuditReplayCommand expected = new AuditReplayCommand(1000, "proxyUser", "create", "sourcePath", "null", "0.0.0.0"); assertEquals(expected, parser.parse(in, IDENTITY_FN)); }
### 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: LockingBinaryTree extends BinaryTree<Integer> { public LockingBinaryTree(Integer data) { super(data); } LockingBinaryTree(Integer data); boolean isLocked(); boolean lock(); void unlock(); }### Answer: @Test public void lockingBinaryTree() { LockingBinaryTree lockingBinaryTree = new LockingBinaryTree(0); lockingBinaryTree.left = new LockingBinaryTree(1); lockingBinaryTree.right = new LockingBinaryTree(2); lockingBinaryTree.left.left = new LockingBinaryTree(3); assertFalse(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); ((LockingBinaryTree) lockingBinaryTree.left).lock(); assertTrue(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); ((LockingBinaryTree) lockingBinaryTree.left).unlock(); assertFalse(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); lockingBinaryTree.lock(); assertTrue(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); lockingBinaryTree.unlock(); assertFalse(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); ((LockingBinaryTree) lockingBinaryTree.left.left).lock(); assertTrue(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); ((LockingBinaryTree) lockingBinaryTree.left.left).unlock(); assertFalse(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); ((LockingBinaryTree) lockingBinaryTree.right).lock(); assertFalse(((LockingBinaryTree) lockingBinaryTree.left).isLocked()); ((LockingBinaryTree) lockingBinaryTree.right).unlock(); } @Test public void lockingBinaryTree() { LockingBinaryTree lockingBinaryTree = new LockingBinaryTree(0); lockingBinaryTree.left = new LockingBinaryTree(1); lockingBinaryTree.right = new LockingBinaryTree(2); lockingBinaryTree.left.left = new LockingBinaryTree(3); assertFalse(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); ((LockingBinaryTree)lockingBinaryTree.left).lock(); assertTrue(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); ((LockingBinaryTree)lockingBinaryTree.left).unlock(); assertFalse(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); lockingBinaryTree.lock(); assertTrue(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); lockingBinaryTree.unlock(); assertFalse(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); ((LockingBinaryTree)lockingBinaryTree.left.left).lock(); assertTrue(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); ((LockingBinaryTree)lockingBinaryTree.left.left).unlock(); assertFalse(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); ((LockingBinaryTree)lockingBinaryTree.right).lock(); assertFalse(((LockingBinaryTree)lockingBinaryTree.left).isLocked()); ((LockingBinaryTree)lockingBinaryTree.right).unlock(); }
### 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: SparseArray2DImpl implements ISparseArray2D<T> { @Override public T getAt(int row, int col) throws ArrayIndexOutOfBoundsException { if (row>this.row || col>column){ throw new ArrayIndexOutOfBoundsException(); } else{ IndexNode current = rowLinkedList.head; while (current!=null){ if (row==current.index){ ArrayNode<T> currentNode = current.head; while (currentNode!=null){ if (currentNode.column==col){ return (T)(currentNode.data); } else{ currentNode = currentNode.nextCol; } } } else{ current = current.next; } } } return null; } 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 testGetAt() { try { array.getAt(10001, 1); assertTrue( "You failed to throw the exception properly for row out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } try { array.getAt(1, 10001); assertTrue( "You failed to throw the exception properly for column out of bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } assertEquals("You did not return null from an empty array", null, array.getAt(1000, 1000)); array.putAt(10, 100, "C"); array.putAt(10, 150, "L"); array.putAt(30, 150, "D"); array.putAt(150, 10, "X"); array.putAt(10, 20, "Z"); array.putAt(5, 150, "Y"); assertEquals("You failed to return a correct entry", "C", array.getAt(10, 100)); assertEquals("You did not return null for an empty cell", null, array.getAt(50, 50)); assertEquals("You failed to return a correct entry", "D", array.getAt(30, 150)); assertEquals("You did not return null for non-existent cell", null, array.getAt(100, 10)); assertEquals("You failed to return a correct entry", "X", array.getAt(150, 10)); assertEquals("Insert at head of row failed", "Z", array.getAt(10, 20)); assertEquals("Insert at head of col failed", "Y", array.getAt(5, 150)); List<String> list = array.getRowFor(10); assertEquals("Row count wrong after inserts", 3,list.size()); assertEquals("Element order wrong", "Z", list.get(0)); assertEquals("ELement order wrong", "C", list.get(1)); assertEquals("Element order wrong", "L", list.get(2)); list = array.getColumnFor(150); assertEquals("Col count wrong after inserts", 3, list.size()); assertEquals("Element order wrong", "Y", list.get(0)); assertEquals("ELement order wrong", "L", list.get(1)); assertEquals("Element order wrong", "D", list.get(2)); }
### Question: CircularArraySequence implements Sequence { @Override public Object last() { CircularArraySequence<T> tempSequence = new CircularArraySequence<T>(this); T lastObj; if (rear == 0){ if (tempSequence.backingArray[tempSequence.backingArray.length-1]==null && tempSequence.backingArray[tempSequence.rear] != null){ lastObj = tempSequence.backingArray[tempSequence.rear]; backingArray[rear] = null; fillCount-=1; rear = 0; } else if(tempSequence.backingArray[tempSequence.backingArray.length-1]==null && tempSequence.backingArray[tempSequence.rear] == null){ lastObj = null; } else{ lastObj = tempSequence.backingArray[tempSequence.backingArray.length-1]; backingArray[backingArray.length-1] = null; fillCount-=1; rear = tempSequence.backingArray.length-1; } } else{ lastObj = (T) tempSequence.backingArray[tempSequence.rear-1]; backingArray[rear-1] = null; fillCount-=1; rear-=1; } return lastObj; } 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 testLast() { assertTrue("New sequence not reporting empty", seq.isEmpty()); assertEquals("Taking last of an new empty sequence did not return null", null, seq.last()); seq.append("a"); seq.append("b"); seq.append("c"); assertEquals("Last element returned not correct", "c", seq.last()); assertEquals("Number of elements wrong after last called", 2, seq.length()); assertEquals("last element returned not correct", "b", seq.last()); assertEquals("Number of elements wrong after last called", 1, seq.length()); assertEquals("Last element returned not correct", "a", seq.last()); assertEquals("Taking last of an empty sequence didn't return null", null, seq.last()); }
### 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: SparseArray2DImpl implements ISparseArray2D<T> { @Override public List<T> getColumnFor(int col) throws ArrayIndexOutOfBoundsException { if (col>column || col<0){ throw new ArrayIndexOutOfBoundsException(); } ArrayList<T> list = new ArrayList<T>(); IndexNode current = colLinkedList.head; while (current!=null){ if (col==current.index){ ArrayNode<T> currentNode = current.head; while (currentNode!=null){ list.add(currentNode.data); currentNode = currentNode.nextRow; } current = current.next; } else{ current = current.next; } } return list ; } 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 testGetColumnFor() { try { array.getColumnFor(10001); assertTrue("You failed to detect column out bounds", false); } catch (ArrayIndexOutOfBoundsException ae) { assertTrue(true); } List<String> list = array.getColumnFor(100); assertTrue("You did not return an empty list for an empty array", list.isEmpty()); array.putAt(10, 100, "C"); array.putAt(10, 150, "L"); array.putAt(30, 150, "D"); array.putAt(90, 150, "Z"); array.putAt(30, 100, "O"); array.putAt(30, 200, "T"); list = array.getColumnFor(150); assertEquals("Did not return correct entry count for column", 3, list.size()); assertEquals("First element of column was wrong", "L", list.get(0)); assertEquals("Second element of column was wrong", "D", list.get(1)); assertEquals("Third element of column was wrong", "Z", list.get(2)); list = array.getColumnFor(1000); assertTrue("You did not return empty for nonexistent column", list.isEmpty()); }