method2testcases stringlengths 118 3.08k |
|---|
### Question:
MBeanServerHelper { public static void unregister(MBeanServer server, ObjectName name) throws JBIException { if (name != null) { if (server == null) { throw new JBIException("MBeanServer is null when registering MBean " + name); } try { doUnregister(server, name); } catch (JMException e) { throw new JBIException("Unable to unregister object with name " + name, e); } } } static ObjectName register(MBeanServer server, ObjectName name, Object object); static void unregister(MBeanServer server, ObjectName name); }### Answer:
@Test(expected = JBIException.class) public void testUnregisterNullServerThrowsJBIException() throws Exception { MBeanServerHelper.unregister(null, defaultObjectName); } |
### Question:
DateUtils { private DateUtils() { } private DateUtils(); static String format(Date date); static Date parse(String dateStr, String dateFormat); static String format(Date date, String dateFormat); static Date toDate(String dateStr, String dateFormat); static Date toDate(String str); static Date toDate2(String str); static Date getFirstDayOfMonth(int year, int month); static Date getFirstDayOfMonth(String yearMonth); static Date getLastDayOfMonth(String yearMonth); static Date getLastDayOfMonth(int year, int month); static Date getFirstDateOfThisYear(); static int getMonthOfDate(Date date); static int getQuarterOfDate(Date date); static Date getLastDayOfMonth(Date date); static Date getFirstDayOfMonth(Date date); static int getDiffDays(Date left, Date right); static Date getDateByOffset(Date date, int offset); static final int getDayOfWeek(Date date); static Date clearTime(Date date); static int getDateDiffDays(Date curDate, Date oriDate); static int getDateDiffDay(Date curDate, Date oriDate); static String getDate(Date date); static String getDate(Date date, String pattern); static Date getMonthByOffset(Date date, int offset); static boolean isBetween(Date beginDate, Date endDate, Date date); static Date longToDate(long l); static final String YYYYMMDD; static final String YYYYMMDDS; static final String YYYYMMDDHMS; static final String YYYYMMDDHM; }### Answer:
@Test public void testDateUtils() { String date = DateUtils.format(new Date()); logger.info("DateUtils测试类 运行结果:{}",date); } |
### Question:
FindBugsHealthDescriptor extends AbstractHealthDescriptor { @Override protected Localizable createDescription(final AnnotationProvider result) { if (result.getNumberOfAnnotations() == 0) { return Messages._FindBugs_ResultAction_HealthReportNoItem(); } else if (result.getNumberOfAnnotations() == 1) { return Messages._FindBugs_ResultAction_HealthReportSingleItem(); } else { return Messages._FindBugs_ResultAction_HealthReportMultipleItem(result.getNumberOfAnnotations()); } } FindBugsHealthDescriptor(final HealthDescriptor healthDescriptor); }### Answer:
@Test public void verifyNumberOfItems() { AnnotationProvider provider = mock(AnnotationProvider.class); FindBugsHealthDescriptor healthDescriptor = new FindBugsHealthDescriptor(NullHealthDescriptor.NULL_HEALTH_DESCRIPTOR); Localizable description = healthDescriptor.createDescription(provider); assertEquals(WRONG_DESCRIPTION, Messages.FindBugs_ResultAction_HealthReportNoItem(), description.toString()); when(provider.getNumberOfAnnotations()).thenReturn(1); description = healthDescriptor.createDescription(provider); assertEquals(WRONG_DESCRIPTION, Messages.FindBugs_ResultAction_HealthReportSingleItem(), description.toString()); when(provider.getNumberOfAnnotations()).thenReturn(2); description = healthDescriptor.createDescription(provider); assertEquals(WRONG_DESCRIPTION, Messages.FindBugs_ResultAction_HealthReportMultipleItem(2), description.toString()); } |
### Question:
FindBugsPlugin extends Plugin { public static boolean isFindBugs2x(final MojoExecution mojoExecution) { try { String[] versions = StringUtils.split(mojoExecution.getVersion(), "."); if (versions.length > 1) { int major = Integer.parseInt(versions[0]); int minor = Integer.parseInt(versions[1]); return major > 2 || (major == 2 && minor >= 4); } } catch (Throwable exception) { } return false; } @Override void start(); static boolean isFindBugs2x(final MojoExecution mojoExecution); }### Answer:
@Test public void testNoSuchMethodError() { MojoExecution execution = mock(MojoExecution.class); when(execution.getVersion()).thenThrow(new NoSuchMethodError()); assertFalse(WRONG_MAVEN_DETECTION, FindBugsPlugin.isFindBugs2x(execution)); } |
### Question:
KettleControlBolt extends BaseRichBolt { @SuppressWarnings("rawtypes") @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; componentToPendingTasks = new HashMap<String, List<Integer>>(); for (String componentId : leafSteps) { List<Integer> tasks = context.getComponentTasks(componentId); if (tasks == null || tasks.isEmpty()) { throw new IllegalStateException("No tasks defined for leaf step " + componentId); } componentToPendingTasks.put(componentId, new ArrayList<Integer>(tasks)); } notifier.init(stormConf); } KettleControlBolt(String transformationName, Notifier notifier,
Set<String> leafSteps); @SuppressWarnings("rawtypes") @Override void prepare(Map stormConf, TopologyContext context,
OutputCollector collector); @Override void execute(Tuple input); @Override void declareOutputFields(OutputFieldsDeclarer declarer); @Override void cleanup(); }### Answer:
@Test(expected = IllegalStateException.class) public void prepare_no_tasks_for_leaf_step_null() { KettleControlBolt bolt = new KettleControlBolt(TRANS_NAME, notifier, Collections.singleton(STEP_1)); EasyMock.expect(context.getComponentTasks(STEP_1)).andReturn(null); control.replay(); bolt.prepare(Collections.emptyMap(), context, collector); }
@Test(expected = IllegalStateException.class) public void prepare_no_tasks_for_leaf_step_empty() { KettleControlBolt bolt = new KettleControlBolt(TRANS_NAME, notifier, Collections.singleton(STEP_1)); EasyMock.expect(context.getComponentTasks(STEP_1)).andReturn( Collections.<Integer> emptyList()); control.replay(); bolt.prepare(Collections.emptyMap(), context, collector); } |
### Question:
KettleControlBolt extends BaseRichBolt { @Override public void cleanup() { super.cleanup(); notifier.cleanup(); } KettleControlBolt(String transformationName, Notifier notifier,
Set<String> leafSteps); @SuppressWarnings("rawtypes") @Override void prepare(Map stormConf, TopologyContext context,
OutputCollector collector); @Override void execute(Tuple input); @Override void declareOutputFields(OutputFieldsDeclarer declarer); @Override void cleanup(); }### Answer:
@Test public void cleanup() { KettleControlBolt bolt = new KettleControlBolt(TRANS_NAME, notifier, Collections.singleton(STEP_1)); notifier.cleanup(); EasyMock.expectLastCall(); control.replay(); bolt.cleanup(); control.verify(); } |
### Question:
ReportEvent extends EventImpl { public void toText(Writer o) throws IOException { o.write(StringEscapeUtils.escapeJava(this.toString())); } ReportEvent(ReportEvent e); ReportEvent(String src); ReportEvent(Map<String, Long> longMetrics,
Map<String, String> stringMetrics, Map<String, Double> doubleMetrics); void setLongMetric(String name, long value); void setDoubleMetric(String name, double value); void setStringMetric(String name, String value); Long getLongMetric(String name); Double getDoubleMetric(String name); String getStringMetric(String name); Map<String, Double> getAllDoubleMetrics(); Map<String, String> getAllStringMetrics(); Map<String, Long> getAllLongMetrics(); long getNumMetrics(); void toJson(Writer o); void toHtml(Writer o); String toString(); void toText(Writer o); static ReportEvent createLegacyHtmlReport(String name, String data); void merge(ReportEvent e); void hierarchicalMerge(String prefix, ReportEvent e); String toText(); String toJson(); String toHtml(); final static String R_NAME; final static String A_COUNT; }### Answer:
@Test public void testReportText() throws IOException { Writer w = new OutputStreamWriter(System.out); e.toText(w); w.flush(); } |
### Question:
ReportEvent extends EventImpl { public void merge(ReportEvent e) { super.merge(e); mergeWithPrefix("", e); } ReportEvent(ReportEvent e); ReportEvent(String src); ReportEvent(Map<String, Long> longMetrics,
Map<String, String> stringMetrics, Map<String, Double> doubleMetrics); void setLongMetric(String name, long value); void setDoubleMetric(String name, double value); void setStringMetric(String name, String value); Long getLongMetric(String name); Double getDoubleMetric(String name); String getStringMetric(String name); Map<String, Double> getAllDoubleMetrics(); Map<String, String> getAllStringMetrics(); Map<String, Long> getAllLongMetrics(); long getNumMetrics(); void toJson(Writer o); void toHtml(Writer o); String toString(); void toText(Writer o); static ReportEvent createLegacyHtmlReport(String name, String data); void merge(ReportEvent e); void hierarchicalMerge(String prefix, ReportEvent e); String toText(); String toJson(); String toHtml(); final static String R_NAME; final static String A_COUNT; }### Answer:
@Test public void testMerge() throws IOException { ReportEvent e1 = new ReportEvent("test"); e1.setLongMetric("another", 12345); long attrs = e.getNumMetrics(); System.out.println("- before merge, " + attrs + " attributes"); Writer out = new OutputStreamWriter(System.out); e.toJson(out); out.flush(); System.out.println("- after merge, " + attrs + " + 1 attributes"); e.merge(e1); e.toJson(out); out.flush(); assertEquals(attrs + 1, e.getNumMetrics()); } |
### Question:
ReportEvent extends EventImpl { public void hierarchicalMerge(String prefix, ReportEvent e) { super.hierarchicalMerge(prefix, e); mergeWithPrefix(prefix + ".", e); } ReportEvent(ReportEvent e); ReportEvent(String src); ReportEvent(Map<String, Long> longMetrics,
Map<String, String> stringMetrics, Map<String, Double> doubleMetrics); void setLongMetric(String name, long value); void setDoubleMetric(String name, double value); void setStringMetric(String name, String value); Long getLongMetric(String name); Double getDoubleMetric(String name); String getStringMetric(String name); Map<String, Double> getAllDoubleMetrics(); Map<String, String> getAllStringMetrics(); Map<String, Long> getAllLongMetrics(); long getNumMetrics(); void toJson(Writer o); void toHtml(Writer o); String toString(); void toText(Writer o); static ReportEvent createLegacyHtmlReport(String name, String data); void merge(ReportEvent e); void hierarchicalMerge(String prefix, ReportEvent e); String toText(); String toJson(); String toHtml(); final static String R_NAME; final static String A_COUNT; }### Answer:
@Test public void testHierarchicalMerge() throws IOException { ReportEvent e1 = new ReportEvent("test"); e1.setLongMetric("another", 12345); e1.setLongMetric("duplicateLong", 23456); long attrs = e.getNumMetrics(); System.out.println("- before merge, " + attrs + " attributes"); Writer out = new OutputStreamWriter(System.out); e.toJson(out); out.flush(); System.out.println("- after merge, " + attrs + " + 2 metrics"); e.hierarchicalMerge("event1", e1); e.toJson(out); out.flush(); assertEquals(attrs + 2, e.getNumMetrics()); assertEquals(e.getLongMetric("event1.another"), Long.valueOf(12345L)); assertEquals(e.getLongMetric("event1.duplicateLong"), Long.valueOf(54321L)); } |
### Question:
FailOverSink extends EventSink.Base { public FailOverSink(EventSink primary, EventSink backup) { Preconditions.checkNotNull(primary); Preconditions.checkNotNull(backup); this.primary = primary; this.backup = backup; suffix = uniq.getAndIncrement(); this.name = "failover_" + suffix; this.R_FAILS = "rpt." + name + ".fails"; this.R_BACKUPS = "rpt." + name + ".backups"; } FailOverSink(EventSink primary, EventSink backup); @Override void append(Event e); @Override void close(); @Override void open(); @Override ReportEvent getReport(); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); @Override String getName(); static SinkBuilder builder(); }### Answer:
@Test public void testFailOverSink() throws IOException { CounterSink primary = new CounterSink("primary"); CounterSink secondary = new CounterSink("backup"); IntervalFlakeyEventSink<EventSink> flake = new IntervalFlakeyEventSink<EventSink>( primary, 2); FailOverSink failsink = new FailOverSink(flake, secondary); failsink.open(); for (int i = 0; i < 100; i++) { Event e = new EventImpl(("event " + i).getBytes()); failsink.append(e); } failsink.close(); Assert.assertEquals(primary.getCount(), secondary.getCount()); } |
### Question:
FormatterDecorator extends
EventSinkDecorator<S> { public void append(Event e) throws IOException { Preconditions.checkNotNull(e); String body = e.escapeString(formatString); Event e2 = new EventImpl(body.getBytes(), e.getTimestamp(), e.getPriority(), e.getNanos(), e.getHost()); for (Entry<String, byte[]> entry : e.getAttrs().entrySet()) { e2.set(entry.getKey(), entry.getValue()); } super.append(e2); } FormatterDecorator(S s, String formatString); void append(Event e); static SinkDecoBuilder builder(); }### Answer:
@Test public void testFormat() throws IOException{ MemorySinkSource mem = new MemorySinkSource(); EventSink format = new FormatterDecorator<EventSink>(mem, "test %{body}"); Event e = new EventImpl("content".getBytes()); e.set("attr1", "value".getBytes()); format.open(); format.append(e); format.close(); mem.open(); Event e2 = mem.next(); assertEquals("test content", new String(e2.getBody())); assertEquals("value", Attributes.readString(e2, "attr1")); } |
### Question:
ZKClient implements Watcher { public ZKClient(String hosts) { this.hosts = hosts; } ZKClient(String hosts); boolean init(); synchronized boolean init(final InitCallback initCallback); synchronized void close(); boolean ensureExists(final String path, final byte[] data); void ensureDeleted(final String path, final int version); synchronized ZooKeeper getZK(); static long extractSuffix(String prefix, String znode); String getLastSequentialChild(final String path, final String prefix,
final boolean watch); List<String> getChildren(final String path, final boolean watch); byte[] getData(final String path, final boolean watch, final Stat stat); Stat setData(final String path, final byte[] data, final int version); String create(final String path, final byte[] data,
final List<ACL> acls, final CreateMode mode); void delete(final String path, final int version); Stat exists(final String path, final boolean watch); @Override void process(WatchedEvent event); }### Answer:
@Test public void testZKClient() throws Exception { File temp = File.createTempFile("flume-zk-test", ""); temp.delete(); temp.mkdir(); temp.deleteOnExit(); ZKInProcessServer zk = new ZKInProcessServer(3181, temp.getAbsolutePath()); zk.start(); ZKClient client = new ZKClient("localhost:3181"); client.init(); client.ensureDeleted("/test-flume", -1); assertTrue("Delete not successful!", client.exists("/test-flume", false) == null); client.ensureExists("/test-flume", "hello world".getBytes()); Stat stat = new Stat(); byte[] data = client.getData("/test-flume", false, stat); String dataString = new String(data); assertEquals("Didn't get expected 'hello world' from getData - " + dataString, dataString, "hello world"); client.delete("/test-flume", stat.getVersion()); assertTrue("Final delete not successful!", client.exists("/test-flume", false) == null); zk.stop(); } |
### Question:
MemoryBackedConfigStore extends ConfigStore { public void addLogicalNode(String physNode, String logicNode) { if (nodeMap.containsEntry(physNode, logicNode)) { return; } nodeMap.put(physNode, logicNode); } @Override FlumeConfigData getConfig(String host); @Override void setConfig(String host, String flowid, String source, String sink); @Override Map<String, FlumeConfigData> getConfigs(); void addChokeLimit(String physNode, String chokeID, int limit); void addLogicalNode(String physNode, String logicNode); List<String> getLogicalNodes(String physNode); @Override Multimap<String, String> getLogicalNodeMap(); @Override void bulkSetConfig(Map<String, FlumeConfigData> configs); @Override void removeLogicalNode(String logicNode); @Override void unmapLogicalNode(String physNode, String logicNode); @Override void init(); @Override void shutdown(); @Override void unmapAllLogicalNodes(); @Override Map<String, Integer> getChokeMap(String physNode); }### Answer:
@Test public void testNodes() throws IOException { File tmp = File.createTempFile("test-flume", ""); tmp.delete(); tmp.deleteOnExit(); MemoryBackedConfigStore store = new MemoryBackedConfigStore(); ConfigManager manager = new ConfigManager(store); manager.addLogicalNode("physical", "logical1"); manager.addLogicalNode("physical", "logical2"); manager.addLogicalNode("physical", "logical3"); manager.addLogicalNode("p2", "l2"); manager.addLogicalNode("p3", "l3"); List<String> lns = manager.getLogicalNode("physical"); assertTrue(lns.contains("logical1")); assertTrue(lns.contains("logical2")); assertTrue(lns.contains("logical3")); assertTrue(manager.getLogicalNode("p2").contains("l2")); assertTrue(manager.getLogicalNode("p3").contains("l3")); } |
### Question:
DiskFailoverDeco extends
EventSinkDecorator<S> { public static SinkDecoBuilder builder() { return new SinkDecoBuilder() { @Override public EventSinkDecorator<EventSink> build(Context context, String... argv) { Preconditions.checkArgument(argv.length <= 1, "usage: diskFailover[(maxMillis[, checkmillis])]"); FlumeConfiguration conf = FlumeConfiguration.get(); long delayMillis = conf.getAgentLogMaxAge(); if (argv.length >= 1) { delayMillis = Long.parseLong(argv[0]); } long checkmillis = 250; if (argv.length >= 2) { checkmillis = Long.parseLong(argv[1]); } FlumeNode node = FlumeNode.getInstance(); String dfonode = context.getValue(LogicalNodeContext.C_LOGICAL); DiskFailoverManager dfoman = node.getAddDFOManager(dfonode); return new DiskFailoverDeco<EventSink>(null, dfoman, new TimeTrigger( new ProcessTagger(), delayMillis), checkmillis); } }; } DiskFailoverDeco(S s, final DiskFailoverManager dfoman, RollTrigger t,
long checkmillis); void setSink(S sink); @Override synchronized void append(Event e); @Override synchronized void close(); @Override synchronized void open(); static SinkDecoBuilder builder(); @Override String getName(); @Override ReportEvent getReport(); }### Answer:
@Test public void testBuilder() { DiskFailoverDeco.builder().build(new Context()); DiskFailoverDeco.builder().build(new Context(), "1000"); }
@Test(expected = IllegalArgumentException.class) public void testBuilderFail1() { DiskFailoverDeco.builder().build(new Context(), "12341", "foo"); }
@Test(expected = IllegalArgumentException.class) public void testBuilderFail2() { DiskFailoverDeco.builder().build(new Context(), "foo"); } |
### Question:
CommandManager implements Reportable { public CommandManager() { this(cmdArrays); } CommandManager(); CommandManager(Object[][] cmdArray); void addCommand(String cmd, Execable ex); synchronized void start(); synchronized void stop(); long submit(Command cmd); boolean isSuccess(long cmdid); boolean isFailure(long cmdid); @Override String getName(); CommandStatus getStatus(long id); @Override ReportEvent getReport(); }### Answer:
@Test public void testCommandManager() throws InterruptedException { CommandManager cmdman = new CommandManager(); List<Long> ids = new ArrayList<Long>(); for (int i = 0; i < 10; i++) { LOG.info("command manager start stop " + i); Command cmd = new Command("noop"); long id = cmdman.submit(cmd); ids.add(id); assertFalse(cmdman.isFailure(id)); assertFalse(cmdman.isSuccess(id)); } for (Long l : ids) { CommandStatus status = cmdman.getStatus(l); assertEquals("", status.getMessage()); assertTrue(status.isQueued()); } cmdman.start(); Clock.sleep(200); cmdman.stop(); for (Long l : ids) { CommandStatus status = cmdman.getStatus(l); assertEquals("", status.getMessage()); assertTrue(status.isSuccess()); assertFalse(cmdman.isFailure(l)); assertTrue(cmdman.isSuccess(l)); } LOG.info(cmdman.getReport()); } |
### Question:
CommandManager implements Reportable { public long submit(Command cmd) { Preconditions.checkNotNull(cmd, "No null commands allowed, use \"noop\""); LOG.info("Submitting command: " + cmd); long cmdId = curCommandId.getAndIncrement(); CommandStatus cmdStat = CommandStatus.createCommandStatus(cmdId, cmd); synchronized (this) { statuses.put(cmdId, cmdStat); queue.add(cmdStat); } return cmdId; } CommandManager(); CommandManager(Object[][] cmdArray); void addCommand(String cmd, Execable ex); synchronized void start(); synchronized void stop(); long submit(Command cmd); boolean isSuccess(long cmdid); boolean isFailure(long cmdid); @Override String getName(); CommandStatus getStatus(long id); @Override ReportEvent getReport(); }### Answer:
@Test(expected = NullPointerException.class) public void testSubmitNull() throws InterruptedException { CommandManager cmdman = new CommandManager(); cmdman.submit(null); } |
### Question:
CommandManager implements Reportable { void exec(Command cmd) throws MasterExecException { Execable ex = cmds.get(cmd.getCommand()); if (ex == null) { throw new MasterExecException("Don't know how to handle Command: '" + cmd + "'", null); } LOG.info("Executing command: " + cmd); try { ex.exec(cmd.getArgs()); } catch (MasterExecException e) { throw e; } catch (IOException e) { throw new MasterExecException(e.getMessage(), e); } } CommandManager(); CommandManager(Object[][] cmdArray); void addCommand(String cmd, Execable ex); synchronized void start(); synchronized void stop(); long submit(Command cmd); boolean isSuccess(long cmdid); boolean isFailure(long cmdid); @Override String getName(); CommandStatus getStatus(long id); @Override ReportEvent getReport(); }### Answer:
@Test(expected = NullPointerException.class) public void testExecNull() throws MasterExecException { CommandManager cmdman = new CommandManager(); cmdman.exec(null); }
@Test(expected = NullPointerException.class) public void testExecCmdNull() throws MasterExecException { CommandManager cmdman = new CommandManager(); cmdman.exec(new Command(null)); }
@Test(expected = MasterExecException.class) public void testExecInvalidCmd() throws MasterExecException { CommandManager cmdman = new CommandManager(); cmdman.exec(new Command("illegal")); } |
### Question:
CommandManager implements Reportable { void handleCommand(CommandStatus cmd) { try { if (cmd == null) { return; } cmd.toExecing(""); exec(cmd.cmd); cmd.toSucceeded(""); } catch (MasterExecException e) { LOG.warn("During " + cmd + " : " + e.getMessage()); cmd.toFailed(e.getMessage()); } catch (Exception e) { LOG.error("Unexpected exception during " + cmd + " : " + e.getMessage(), e); cmd.toFailed(e.getMessage()); } } CommandManager(); CommandManager(Object[][] cmdArray); void addCommand(String cmd, Execable ex); synchronized void start(); synchronized void stop(); long submit(Command cmd); boolean isSuccess(long cmdid); boolean isFailure(long cmdid); @Override String getName(); CommandStatus getStatus(long id); @Override ReportEvent getReport(); }### Answer:
@Test public void testHandleCommand() { Execable ex = new Execable() { @Override public void exec(String[] args) throws MasterExecException, IOException { throw new IllegalArgumentException("failure here"); } }; CommandManager cmdman = new CommandManager(); cmdman.addCommand("err", ex); cmdman.handleCommand(null); long id = cmdman.submit(new Command("err")); CommandStatus stat = cmdman.getStatus(id); cmdman.handleCommand(stat); assertTrue(cmdman.isFailure(id)); id = cmdman.submit(new Command("noop")); stat = cmdman.getStatus(id); cmdman.handleCommand(stat); assertTrue(cmdman.isSuccess(id)); } |
### Question:
DiskFailoverSource extends EventSource.Base { @Override public void open() throws IOException { dfMan.open(); dfMan.recover(); } DiskFailoverSource(DiskFailoverManager dfMan); @Override Event next(); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); void recover(); @Override void close(); @Override void open(); }### Answer:
@Test(expected = IOException.class) public void testSeqfileErrorOnOpen() throws IOException, InterruptedException { LOG.info("Exception on open empty file with seqfile"); File tmpdir = FileUtil.mktempdir(); tmpdir.deleteOnExit(); File corrupt = new File(tmpdir, "walempty.00000000.20091104-101213997-0800.seq"); LOG.info("corrupt file is named: " + corrupt.getAbsolutePath()); corrupt.createNewFile(); corrupt.deleteOnExit(); File commit = new File(tmpdir, "committed"); commit.deleteOnExit(); EventSource src = new SeqfileEventSource(corrupt.getAbsolutePath()); try { src.open(); } catch (IOException e) { throw e; } finally { FileUtil.rmr(tmpdir); } } |
### Question:
LogicalNodeManager implements Reportable { synchronized public void decommission(String name) throws IOException { LogicalNode nd = threads.remove(name); if (nd == null) { throw new IOException("Attempting to decommission node '" + name + "' but it does not exist!"); } ReportManager.get().remove(nd); nd.close(); } LogicalNodeManager(String physicalNode); synchronized Collection<LogicalNode> getNodes(); synchronized void spawn(String name, String src, String snk); synchronized void testingSpawn(String name, String src, String snk); synchronized void decommission(String name); @Override ReportEvent getReport(); String getPhysicalNodeName(); @Override String getName(); synchronized LogicalNode get(String ln); synchronized void decommissionAllBut(List<String> excludes); }### Answer:
@Test(expected = IOException.class) public void tesIllegalDecommission() throws IOException { LogicalNodeManager lnm = new LogicalNodeManager("local"); lnm.decommission("nonexist"); } |
### Question:
AgentFailChainSink extends EventSink.Base { public static String genE2EChain(String... chain) { String body = " %s "; String spec = FailoverChainManager.genAvailableSinkSpec(body, Arrays .asList(chain)); spec = "{ ackedWriteAhead => { stubbornAppend => { insistentOpen => " + spec + " } } }"; LOG.info("Setting e2e failover chain to " + spec); return spec; } AgentFailChainSink(RELIABILITY rel, String... hosts); AgentFailChainSink(Context context, RELIABILITY rel, String... hosts); @Override void open(); @Override void close(); @Override void append(Event e); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); static String genBestEffortChain(String... chain); static String genE2EChain(String... chain); static String genDfoChain(String... chain); static List<String> thriftifyArgs(int defaultPort, List<String> list); static SinkBuilder e2eBuilder(); static SinkBuilder dfoBuilder(); static SinkBuilder beBuilder(); @Override String getName(); }### Answer:
@Test public void testWALFailchain() throws FlumeSpecException { ReportManager.get().clear(); String spec = AgentFailChainSink.genE2EChain("counter(\"foo1\")", "counter(\"foo2\")", "counter(\"foo3\")"); LOG.info("waled failchain: " + spec); EventSink snk = FlumeBuilder.buildSink(new Context(), spec); LOG.info(snk.getReport().toJson()); ReportManager.get().getReportable("foo1"); } |
### Question:
AgentFailChainSink extends EventSink.Base { public static String genBestEffortChain(String... chain) { String body = "{ lazyOpen => { stubbornAppend => %s } } "; String spec = FailoverChainManager.genAvailableSinkSpec(body, Arrays .asList(chain)); LOG.info("Setting best effort failover chain to " + spec); return spec; } AgentFailChainSink(RELIABILITY rel, String... hosts); AgentFailChainSink(Context context, RELIABILITY rel, String... hosts); @Override void open(); @Override void close(); @Override void append(Event e); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); static String genBestEffortChain(String... chain); static String genE2EChain(String... chain); static String genDfoChain(String... chain); static List<String> thriftifyArgs(int defaultPort, List<String> list); static SinkBuilder e2eBuilder(); static SinkBuilder dfoBuilder(); static SinkBuilder beBuilder(); @Override String getName(); }### Answer:
@Test public void testBEFailchain() throws FlumeSpecException { ReportManager.get().clear(); String spec = AgentFailChainSink.genBestEffortChain("counter(\"foo1\")", "counter(\"foo2\")", "counter(\"foo3\")"); LOG.info("best effort failchain: " + spec); EventSink snk = FlumeBuilder.buildSink(new Context(), spec); LOG.info(snk.getReport().toJson()); ReportManager.get().getReportable("foo1"); } |
### Question:
AgentFailChainSink extends EventSink.Base { public static String genDfoChain(String... chain) { StringBuilder sb = new StringBuilder(); String primaries = genBestEffortChain(chain); sb.append("let primary := " + primaries); String body = "< primary ? {diskFailover => { insistentOpen => primary} } >"; LOG.info("Setting dfo failover chain to " + body); sb.append(" in "); sb.append(body); return sb.toString(); } AgentFailChainSink(RELIABILITY rel, String... hosts); AgentFailChainSink(Context context, RELIABILITY rel, String... hosts); @Override void open(); @Override void close(); @Override void append(Event e); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); static String genBestEffortChain(String... chain); static String genE2EChain(String... chain); static String genDfoChain(String... chain); static List<String> thriftifyArgs(int defaultPort, List<String> list); static SinkBuilder e2eBuilder(); static SinkBuilder dfoBuilder(); static SinkBuilder beBuilder(); @Override String getName(); }### Answer:
@Test public void testDFOFailchain() throws FlumeSpecException { ReportManager.get().clear(); String spec = AgentFailChainSink.genDfoChain("counter(\"foo1\")", "counter(\"foo2\")", "counter(\"foo3\")"); LOG.info("disk failover failchain: " + spec); EventSink snk = FlumeBuilder.buildSink(new Context(), spec); LOG.info(snk.getReport().toJson()); ReportManager.get().getReportable("foo1"); } |
### Question:
NaiveFileWALDeco extends
EventSinkDecorator<S> { public static SinkDecoBuilder builderEndToEndDir() { return new SinkDecoBuilder() { @Override public EventSinkDecorator<EventSink> build(Context context, String... argv) { Preconditions.checkArgument(argv.length <= 3, "usage: ackedWriteAhead[(maxMillis,walnode,checkMs)]"); FlumeConfiguration conf = FlumeConfiguration.get(); long delayMillis = conf.getAgentLogMaxAge(); if (argv.length >= 1) { delayMillis = Long.parseLong(argv[0]); } FlumeNode node = FlumeNode.getInstance(); String walnode = context.getValue(LogicalNodeContext.C_LOGICAL); if (argv.length >= 2) { walnode = argv[1]; } if (walnode == null) { LOG.warn("Context does not have a logical node name " + "-- this will likely be a problem if you have multiple WALs"); } long checkMs = 250; if (argv.length >= 3) { checkMs = Long.parseLong(argv[2]); } WALManager walman = node.getAddWALManager(walnode); return new NaiveFileWALDeco<EventSink>(context, null, walman, new TimeTrigger(delayMillis), node.getAckChecker() .getAgentAckQueuer(), checkMs); } }; } NaiveFileWALDeco(Context ctx, S s, final WALManager walman,
RollTrigger t, AckListener al, long checkMs); @Override synchronized void append(Event e); @Override synchronized void close(); @Override synchronized void open(); void setSink(S sink); synchronized boolean rotate(); boolean isEmpty(); static SinkDecoBuilder builderEndToEndDir(); @Override String getName(); @Override ReportEvent getReport(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testBadE2eBuilderArgs() { SinkDecoBuilder b = NaiveFileWALDeco.builderEndToEndDir(); b.build(new Context(), "foo", "bar"); } |
### Question:
LogicalNode implements Reportable { public boolean checkConfig(FlumeConfigData data) { if (data == null) { return false; } if (data.getSourceVersion() <= lastGoodCfg.getSourceVersion()) { if (data.getSourceVersion() < lastGoodCfg.getSourceVersion()) { LOG.warn("reject because config older than the current. "); return false; } LOG.debug("do nothing: retrieved config (" + new Date(data.getSourceVersion()) + ") same as current (" + new Date(lastGoodCfg.getSourceVersion()) + "). "); return false; } try { loadConfig(data); } catch (Exception e) { LOG.warn("Configuration " + data + " failed to load!", e); return false; } return true; } LogicalNode(Context ctx, String name); void loadConfig(FlumeConfigData cfg); boolean checkConfig(FlumeConfigData data); void getReports(Map<String, ReportEvent> reports); ReportEvent getReport(); String getName(); long getConfigVersion(); NodeStatus getStatus(); void close(); EventSink getSink(); EventSource getSource(); static final long VERSION_INFIMUM; static final String A_RECONFIGURES; }### Answer:
@Test public void testCheckConfig() { LogicalNode node = new LogicalNode(new Context(), "test-logical-node"); assertFalse(node.checkConfig(null)); FlumeConfigData cfgData = new FlumeConfigData(0, "null", "null", 0, 0, "my-test-flow"); assertTrue(node.checkConfig(cfgData)); assertFalse(node.checkConfig(cfgData)); FlumeConfigData cfgData2 = new FlumeConfigData(0, "null", "null", 1, 0, "my-test-flow"); assertTrue(node.checkConfig(cfgData2)); assertFalse(node.checkConfig(cfgData2)); assertFalse(node.checkConfig(cfgData)); FlumeConfigData cfgData3 = new FlumeConfigData(0, "null", "null", 1, 1, "my-test-flow"); assertFalse(node.checkConfig(cfgData)); assertFalse(node.checkConfig(cfgData2)); assertFalse(node.checkConfig(cfgData3)); } |
### Question:
TailSource extends EventSource.Base { public TailSource(File f, long offset, long waitTime) { this(f, offset, waitTime, false); } TailSource(File f, long offset, long waitTime); TailSource(File f, long offset, long waitTime, boolean startFromEnd); TailSource(long waitTime); synchronized void removeCursor(Cursor cursor); @Override void close(); @Override Event next(); @Override synchronized void open(); static SourceBuilder builder(); static SourceBuilder multiTailBuilder(); static final String A_TAILSRCFILE; }### Answer:
@Test public void testTailSource() throws IOException, FlumeSpecException, InterruptedException { File f = File.createTempFile("temp", ".tmp"); f.deleteOnExit(); final CompositeSink snk = new CompositeSink(new ReportTestingContext(), "{ delay(50) => counter(\"count\") }"); final EventSource src = TailSource.builder().build(f.getAbsolutePath()); final CountDownLatch done = new CountDownLatch(1); final int count = 30; runDriver(src, snk, done, count); FileWriter fw = new FileWriter(f); for (int i = 0; i < count; i++) { fw.append("Line " + i + "\n"); fw.flush(); } fw.close(); assertTrue(done.await(10, TimeUnit.SECONDS)); CounterSink ctr = (CounterSink) ReportManager.get().getReportable("count"); assertEquals(count, ctr.getCount()); } |
### Question:
TailSource extends EventSource.Base { @Override public void close() throws IOException { synchronized (this) { done = true; thd = null; } } TailSource(File f, long offset, long waitTime); TailSource(File f, long offset, long waitTime, boolean startFromEnd); TailSource(long waitTime); synchronized void removeCursor(Cursor cursor); @Override void close(); @Override Event next(); @Override synchronized void open(); static SourceBuilder builder(); static SourceBuilder multiTailBuilder(); static final String A_TAILSRCFILE; }### Answer:
@Test public void testFileOutputStream() throws IOException { File tmp = File.createTempFile("tmp-", ".tmp"); FileOutputStream f = new FileOutputStream(tmp); f.write("0123456789".getBytes()); f.close(); assertEquals(10, tmp.length()); f = new FileOutputStream(tmp); f.write("01234".getBytes()); f.close(); assertEquals(5, tmp.length()); } |
### Question:
ExponentialBackoff implements BackoffPolicy { public void backoff() { retryTime = Clock.unixTime() + sleepIncrement; sleepIncrement *= 2; backoffCount++; } ExponentialBackoff(long initialSleep, long max); void backoff(); boolean isRetryOk(); boolean isFailed(); void reset(); @Override long sleepIncrement(); @Override String getName(); @Override ReportEvent getReport(); @Override void waitUntilRetryOk(); final static public String A_INITIAL; final static public String A_COUNT; final static public String A_COUNTCAP; final static public String A_CURRENTBACKOFF; final static public String A_RETRYTIME; }### Answer:
@Test public void testBackoff() throws InterruptedException { Clock.setClock(mock); System.out.println(mock); ExponentialBackoff bo = new ExponentialBackoff(100, 5); Assert.assertTrue(bo.isRetryOk()); Assert.assertFalse(bo.isFailed()); mock.forward(1); System.out.println(mock); Assert.assertTrue(bo.isRetryOk()); Assert.assertFalse(bo.isFailed()); bo.backoff(); mock.forward(99); System.out.println(mock); Assert.assertFalse(bo.isFailed()); Assert.assertFalse(bo.isRetryOk()); mock.forward(1); System.out.println(mock); Assert.assertTrue(bo.isRetryOk()); Assert.assertFalse(bo.isFailed()); bo.reset(); bo.backoff(); bo.backoff(); bo.backoff(); bo.backoff(); bo.backoff(); mock.forward(1599); System.out.println(mock); Assert.assertFalse(bo.isRetryOk()); Assert.assertTrue(bo.isFailed()); mock.forward(1); System.out.println(mock); Assert.assertFalse(bo.isRetryOk()); Assert.assertTrue(bo.isFailed()); } |
### Question:
ExecEventSource extends EventSource.Base { public void close() throws IOException { readOut.shutdown(); readErr.shutdown(); boolean latched = false; try { latched = latch.await(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.debug("Waiting for exec thread exit was interrupted", e); } stdinISP.shutdown(); stderrISP.shutdown(); if (proc != null) { proc.destroy(); proc = null; } if (!latched) { throw new IOException("Timeout waiting for exec threads to exit"); } } ExecEventSource(String command, boolean aggregate, boolean restart, int period); void close(); Event next(); void open(); static SourceBuilder buildPeriodic(); static SourceBuilder buildStream(); static SourceBuilder builder(); static final String A_PROC_SOURCE; static final String A_EXEC_CMD; }### Answer:
@Test public void testClose() throws IOException, InterruptedException { File temp = File.createTempFile("flmtst", null); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("#!/bin/bash\n while true; do sleep 1; done; >&2 \n"); out.close(); String cmd = temp.getAbsolutePath(); final EventSource source = new ExecEventSource.Builder().build("/bin/bash " + cmd); final CountDownLatch latch = new CountDownLatch(1); source.open(); Thread t = new Thread() { public void run() { try { source.next(); latch.countDown(); } catch (Exception e) { LOG.warn("Event consumption thread caught exception, test will fail", e); } } }; t.start(); source.close(); assertTrue("source.next did not exit after close within 5 seconds", latch .await(5000, TimeUnit.MILLISECONDS)); } |
### Question:
ExecNioSource extends EventSource.Base { public static SourceBuilder buildStream() { return new SourceBuilder() { @Override public EventSource build(String... argv) { Preconditions.checkArgument(argv.length == 1, "execStream(\"cmdline \")"); String command = argv[0]; boolean aggregate = false; boolean restart = false; int period = 0; return new ExecNioSource(command, aggregate, restart, period); } }; } ExecNioSource(String command, boolean aggregate, boolean restart, int period); void close(); Event next(); void open(); static SourceBuilder buildPeriodic(); static SourceBuilder buildStream(); static SourceBuilder builder(); static final String A_PROC_SOURCE; static final String A_EXEC_CMD; }### Answer:
@Test public void testStreamBuilder() throws IOException, FlumeSpecException { ExecNioSource e = (ExecNioSource) ExecNioSource.buildStream().build( "ps -aux"); assertEquals(e.inAggregateMode, false); assertEquals(e.command, "ps -aux"); assertEquals(e.restart, false); assertEquals(e.period, 0); } |
### Question:
ExecNioSource extends EventSource.Base { public static SourceBuilder buildPeriodic() { return new SourceBuilder() { @Override public EventSource build(String... argv) { Preconditions.checkArgument(argv.length == 2, "execPeriodic(\"cmdline \",period)"); String command = argv[0]; boolean aggregate = true; boolean restart = true; int period = Integer.parseInt(argv[1]); return new ExecNioSource(command, aggregate, restart, period); } }; } ExecNioSource(String command, boolean aggregate, boolean restart, int period); void close(); Event next(); void open(); static SourceBuilder buildPeriodic(); static SourceBuilder buildStream(); static SourceBuilder builder(); static final String A_PROC_SOURCE; static final String A_EXEC_CMD; }### Answer:
@Test public void testPeriodicBuilder() throws IOException, FlumeSpecException { ExecNioSource e = (ExecNioSource) ExecNioSource.buildPeriodic().build( "ps -aux", "1000"); assertEquals(e.inAggregateMode, true); assertEquals(e.command, "ps -aux"); assertEquals(e.restart, true); assertEquals(e.period, 1000); } |
### Question:
ExecNioSource extends EventSource.Base { public void close() throws IOException { readOut.shutdown(); readErr.shutdown(); boolean latched = false; try { latched = latch.await(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { LOG.debug("Waiting for exec thread exit was interrupted", e); } stdinISP.shutdown(); stderrISP.shutdown(); if (proc != null) { proc.destroy(); proc = null; } if (!latched) { throw new IOException("Timeout waiting for exec threads to exit"); } } ExecNioSource(String command, boolean aggregate, boolean restart, int period); void close(); Event next(); void open(); static SourceBuilder buildPeriodic(); static SourceBuilder buildStream(); static SourceBuilder builder(); static final String A_PROC_SOURCE; static final String A_EXEC_CMD; }### Answer:
@Test public void testClose() throws IOException, InterruptedException { File temp = File.createTempFile("flmtst", null); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("#!/bin/bash\n while true; do sleep 1; done; >&2 \n"); out.close(); String cmd = temp.getAbsolutePath(); final EventSource source = new ExecNioSource.Builder().build("/bin/bash " + cmd); final CountDownLatch started = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread() { public void run() { try { source.open(); started.countDown(); source.next(); latch.countDown(); } catch (Exception e) { LOG.warn("Event consumption thread caught exception, test will fail", e); } } }; t.start(); started.await(1000, TimeUnit.MILLISECONDS); Clock.sleep(100); source.close(); assertTrue("source.next did not exit after close within 5 seconds", latch .await(5000, TimeUnit.MILLISECONDS)); } |
### Question:
ReorderDecorator extends
EventSinkDecorator<S> { public ReorderDecorator(S s, double yank, double spew, long seed) { super(s); Preconditions.checkArgument(yank >= 0 && yank <= 1.0); Preconditions.checkArgument(spew >= 0 && spew <= 1.0); this.yank = yank; this.spew = spew; this.rand = new Random(seed); } ReorderDecorator(S s, double yank, double spew, long seed); void append(Event e); void close(); static SinkDecoBuilder builder(); }### Answer:
@Test public void testReorderDecorator() throws IOException { ReorderDecorator<EventSink> reorder = new ReorderDecorator<EventSink>(new ConsoleEventSink(), .5, .5, 0); reorder.open(); for (int i = 0; i < 10; i++) { Event e = new EventImpl(new byte[0]); e.set("order", ByteBuffer.allocate(4).putInt(i).array()); reorder.append(e); } System.out.println("closing"); reorder.close(); } |
### Question:
ThriftEventAdaptor extends Event { public static Priority convert(com.cloudera.flume.handlers.thrift.Priority p) { Preconditions.checkNotNull(p, "Prioirity argument must be valid."); switch (p) { case FATAL: return Priority.FATAL; case ERROR: return Priority.ERROR; case WARN: return Priority.WARN; case INFO: return Priority.INFO; case DEBUG: return Priority.DEBUG; case TRACE: return Priority.TRACE; default: throw new IllegalStateException("Unknown value " + p); } } ThriftEventAdaptor(ThriftFlumeEvent evt); @Override byte[] getBody(); @Override Priority getPriority(); @Override long getTimestamp(); static Priority convert(com.cloudera.flume.handlers.thrift.Priority p); static com.cloudera.flume.handlers.thrift.Priority convert(Priority p); @Override String toString(); @Override long getNanos(); @Override String getHost(); static ThriftFlumeEvent convert(Event e); @Override byte[] get(String attr); @Override Map<String, byte[]> getAttrs(); @Override void set(String attr, byte[] vArray); @Override void hierarchicalMerge(String prefix, Event e); @Override void merge(Event e); }### Answer:
@Test public void testConvert() { ThriftFlumeEvent thriftEvent = ThriftEventAdaptor.convert(testEvent); Assert.assertNotNull(thriftEvent); Assert.assertNotNull(thriftEvent.host); Assert.assertNotNull(thriftEvent.timestamp); Assert.assertNotNull(thriftEvent.fields); Assert.assertNotNull(thriftEvent.priority); for (Entry<String, byte[]> entry : testEvent.getAttrs().entrySet()) { Assert.assertTrue(thriftEvent.fields.containsKey(entry.getKey())); Assert.assertTrue(Arrays.equals(thriftEvent.fields.get(entry.getKey()) .array(), entry.getValue())); } } |
### Question:
FlumeSpecGen { static String genArg(CommonTree t) throws FlumeSpecException { ASTNODE type = ASTNODE.valueOf(t.getText()); switch (type) { case HEX: case DEC: case BOOL: case OCT: case STRING: case FLOAT: return t.getChild(0).getText(); default: throw new FlumeSpecException("Not a node of literal type: " + t.toStringTree()); } } @SuppressWarnings("unchecked") static String genEventSource(CommonTree t); @SuppressWarnings("unchecked") static String genEventSink(CommonTree t); @SuppressWarnings("unchecked") static List<FlumeNodeSpec> generate(String s); }### Answer:
@Test public void testHex() throws RecognitionException, FlumeSpecException { String hex = "0x1234"; CommonTree thex = FlumeBuilder.parseLiteral(hex); String outHex = FlumeSpecGen.genArg(thex); assertEquals(hex, outHex); }
@Test public void testDec() throws RecognitionException, FlumeSpecException { String orig = "12234"; CommonTree tree = FlumeBuilder.parseLiteral(orig); String out = FlumeSpecGen.genArg(tree); assertEquals(orig, out); }
@Test public void testString() throws RecognitionException, FlumeSpecException { String orig = "\"This is a a string\""; CommonTree tree = FlumeBuilder.parseLiteral(orig); String out = FlumeSpecGen.genArg(tree); assertEquals(orig, out); } |
### Question:
FixedRetryPolicy implements BackoffPolicy { public FixedRetryPolicy(int numRetries) { this.numRetries = numRetries; } FixedRetryPolicy(int numRetries); @Override void backoff(); @Override boolean isFailed(); @Override boolean isRetryOk(); @Override void reset(); @Override void waitUntilRetryOk(); @Override long sleepIncrement(); @Override String getName(); @Override ReportEvent getReport(); final static public String A_MAX_ATTEMPTS; final static public String A_COUNT; }### Answer:
@Test public void testFixedRetryPolicy() { FixedRetryPolicy policy = new FixedRetryPolicy(3); Assert.assertTrue(policy.isRetryOk()); policy.backoff(); policy.backoff(); policy.backoff(); Assert.assertFalse(policy.isRetryOk()); Assert.assertTrue(policy.isFailed()); policy.reset(); Assert.assertTrue(policy.isRetryOk()); } |
### Question:
CollectorSource extends EventSource.Base { public static SourceBuilder builder() { return new SourceBuilder() { @Override public EventSource build(String... argv) { Preconditions.checkArgument(argv.length <= 1, "usage: collectorSource[(port={" + FlumeConfiguration.COLLECTOR_EVENT_PORT + "})]"); int port = FlumeConfiguration.get().getCollectorPort(); if (argv.length >= 1) port = Integer.parseInt(argv[0]); return new CollectorSource(port); } }; } CollectorSource(int port); @Override void close(); @Override void open(); @Override Event next(); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); int getPort(); static SourceBuilder builder(); }### Answer:
@Test public void testBuilder() throws FlumeSpecException { String src = "collectorSource"; FlumeBuilder.buildSource(src); String src2 = "collectorSource(5150)"; FlumeBuilder.buildSource(src2); try { FlumeBuilder.buildSource("collectorSource(99, \"red luftballoons\")"); } catch (Exception e) { return; } fail("should have caught aproblem"); } |
### Question:
FlumeBuilder { static CommonTree parseHost(String s) throws RecognitionException { return (CommonTree) getDeployParser(s).host().getTree(); } static void setSourceFactory(SourceFactory srcFact); static void setSinkFactory(SinkFactory snkFact); static CommonTree parseSink(String s); static CommonTree parseSource(String s); static Pair<EventSource, EventSink> buildNode(Context context, File f); @SuppressWarnings("unchecked") static Map<String, Pair<String, String>> parseConf(Context ctx,
String s); @SuppressWarnings("unchecked") static Map<String, Pair<EventSource, EventSink>> build(
Context context, String s); static EventSource buildSource(String s); static EventSink buildSink(Context context, String s); @Deprecated static EventSink buildSink(String s); static String toLine(String name, String src, String snk); static String buildArg(CommonTree t); static Set<String> getSinkNames(); static Set<String> getDecoratorNames(); static Set<String> getSourceNames(); }### Answer:
@Test public void testHostnamne() throws org.antlr.runtime.RecognitionException { CommonTree t = null; t = FlumeBuilder.parseHost("localhost"); System.out.println(t); t = FlumeBuilder.parseHost("localhost.localdomain.com"); System.out.println(t); t = FlumeBuilder.parseHost("1.2.3.4"); System.out.println(t); } |
### Question:
CollectorSource extends EventSource.Base { public CollectorSource(int port) { this.src = new ThriftEventSource(port); this.port = port; } CollectorSource(int port); @Override void close(); @Override void open(); @Override Event next(); @Override void getReports(String namePrefix, Map<String, ReportEvent> reports); int getPort(); static SourceBuilder builder(); }### Answer:
@Test public void testCollectorSource() throws FlumeSpecException, IOException { EventSource src = FlumeBuilder.buildSource("collectorSource(34568)"); EventSink snk = FlumeBuilder.buildSink(new Context(), "rpcSink(\"localhost\", 34568)"); src.open(); snk.open(); snk.append(new EventImpl("foo".getBytes())); src.next(); snk.close(); src.close(); } |
### Question:
FlumeBuilder { public static CommonTree parseSink(String s) throws RecognitionException { FlumeDeployParser parser = getDeployParser(s); CommonTree ast = (CommonTree) parser.sink().getTree(); return ast; } static void setSourceFactory(SourceFactory srcFact); static void setSinkFactory(SinkFactory snkFact); static CommonTree parseSink(String s); static CommonTree parseSource(String s); static Pair<EventSource, EventSink> buildNode(Context context, File f); @SuppressWarnings("unchecked") static Map<String, Pair<String, String>> parseConf(Context ctx,
String s); @SuppressWarnings("unchecked") static Map<String, Pair<EventSource, EventSink>> build(
Context context, String s); static EventSource buildSource(String s); static EventSink buildSink(Context context, String s); @Deprecated static EventSink buildSink(String s); static String toLine(String name, String src, String snk); static String buildArg(CommonTree t); static Set<String> getSinkNames(); static Set<String> getDecoratorNames(); static Set<String> getSourceNames(); }### Answer:
@Ignore @Test public void testDecoChain() throws RecognitionException { String decoChain = "{ nullDeco => nullDeco => nullDeco => null}"; FlumeBuilder.parseSink(decoChain); }
@Test public void testRollSinkParse() throws FlumeSpecException, RecognitionException { String roll = "roll (2123) { null } "; FlumeBuilder.parseSink(roll); }
@Test(expected = RuntimeRecognitionException.class) public void testLetInWrongPlace() throws RecognitionException { String badsink = "{ deco1 => { let letvar := test in deco2 => [ < sink1 ? sink2> , sink3, { deco3 => sink4} ] } } "; CommonTree parse = FlumeBuilder.parseSink(badsink); LOG.info(parse.toStringTree()); } |
### Question:
PatternMatch { public PatternMatch nth(int n, PatternMatch child) { return new PatternMatch(PatternType.PARENT_NTH, this, child, n); } private PatternMatch(PatternType type, Object... args); @SuppressWarnings("unchecked") Map<String, CommonTree> match(CommonTree ct); static PatternMatch var(String name, PatternMatch p); static PatternMatch wild(); static PatternMatch kind(String k); static PatternMatch tuple(PatternMatch... tuple); PatternMatch child(PatternMatch child); PatternMatch nth(int n, PatternMatch child); static PatternMatch recursive(PatternMatch child); static PatternMatch or(PatternMatch... choice); static void replaceChildren(CommonTree dst, CommonTree src); static final Logger LOG; }### Answer:
@Test public void testNth() throws RecognitionException { CommonTree sink = FlumeBuilder.parseSink(simple); PatternMatch pp = kind("DECO").nth(1, kind("SINK").child(var("node", kind("logicalNode")))); Map<String, CommonTree> m = pp.match(sink); assertNotNull(m); assertEquals(m.get("node").getText(), "logicalNode"); dumpMatches(m); LOG.info(m); pp = kind("DECO").nth(0, kind("SINK").child(var("node", kind("logicalNode")))); m = pp.match(sink); assertNull(m); dumpMatches(m); LOG.info(m); } |
### Question:
PatternMatch { public static PatternMatch recursive(PatternMatch child) { return new PatternMatch(PatternType.PARENT_RECURSIVE, child); } private PatternMatch(PatternType type, Object... args); @SuppressWarnings("unchecked") Map<String, CommonTree> match(CommonTree ct); static PatternMatch var(String name, PatternMatch p); static PatternMatch wild(); static PatternMatch kind(String k); static PatternMatch tuple(PatternMatch... tuple); PatternMatch child(PatternMatch child); PatternMatch nth(int n, PatternMatch child); static PatternMatch recursive(PatternMatch child); static PatternMatch or(PatternMatch... choice); static void replaceChildren(CommonTree dst, CommonTree src); static final Logger LOG; }### Answer:
@Test public void testRecursive() throws RecognitionException { CommonTree sink = FlumeBuilder .parseSink("let foo := < null ? [ console, { test => { test2 => { batch(10) => logicalNode(\"collector\") } } } ] > in foo"); LOG.info(sink.toStringTree()); PatternMatch pp = recursive(var("batchsize", kind("DEC"))); Map<String, CommonTree> m = pp.match(sink); assertNotNull(m); dumpMatches(m); LOG.info(m); pp = recursive(kind("SINK").child(var("LogicalNodeName", kind("STRING")))); m = pp.match(sink); assertNotNull(m); dumpMatches(m); LOG.info(m); } |
### Question:
PatternMatch { public static PatternMatch or(PatternMatch... choice) { return new PatternMatch(PatternType.OR, (Object[]) choice); } private PatternMatch(PatternType type, Object... args); @SuppressWarnings("unchecked") Map<String, CommonTree> match(CommonTree ct); static PatternMatch var(String name, PatternMatch p); static PatternMatch wild(); static PatternMatch kind(String k); static PatternMatch tuple(PatternMatch... tuple); PatternMatch child(PatternMatch child); PatternMatch nth(int n, PatternMatch child); static PatternMatch recursive(PatternMatch child); static PatternMatch or(PatternMatch... choice); static void replaceChildren(CommonTree dst, CommonTree src); static final Logger LOG; }### Answer:
@Test public void testOr() throws RecognitionException { CommonTree sink = FlumeBuilder .parseSink(" { batch(10) => logicalNode(\"collector\") } "); PatternMatch pdeco = tuple(kind("DECO"), var("deco", kind("SINK")), var( "child", kind("SINK"))); PatternMatch psink = tuple(kind("SINK"), var("name", wild()), var("sink", kind("STRING"))); PatternMatch pp = or(psink, pdeco); LOG.info(sink.toStringTree()); Map<String, CommonTree> m = pp.match(sink); assertNotNull(m); assertTrue(m.containsKey("deco")); dumpMatches(m); LOG.info(m); m = pp.match(m.get("child")); assertNotNull(m); assertTrue(m.containsKey("sink")); dumpMatches(m); LOG.info(m); } |
### Question:
ThriftReportServer extends ThriftServer implements
ThriftFlumeReportServer.Iface { @Override public Map<String, ThriftFlumeReport> getAllReports() throws TException { Map<String, ThriftFlumeReport> retMap = new HashMap<String, ThriftFlumeReport>(); ReportManager reportManager = ReportManager.get(); Map<String, Reportable> reports = reportManager.getReportables(); for (Entry<String, Reportable> e : reports.entrySet()) { ThriftFlumeReport report = reportToThrift(e.getValue().getReport()); retMap.put(e.getKey(), report); } return retMap; } ThriftReportServer(FlumeConfiguration cfg); ThriftReportServer(int port); static ThriftFlumeReport reportToThrift(ReportEvent report); @Override ThriftFlumeReport getReportByName(String reportName); @Override Map<String, ThriftFlumeReport> getAllReports(); void serve(); void stop(); }### Answer:
@Test public void testGetAllReports() throws TException { TTransport transport = new TSocket("localhost", PORT); TProtocol protocol = new TBinaryProtocol(transport); transport.open(); ThriftFlumeReportServer.Client client = new ThriftFlumeReportServer.Client( protocol); Map<String, ThriftFlumeReport> ret = client.getAllReports(); assertTrue(ret.size() == 1); ThriftFlumeReport rep = ret.get("reportable1"); assertNotNull("Report 'reportable1' not found", rep); assertTrue("Expected exactly one double metric", rep.getDoubleMetricsSize() == 1); assertTrue("Expected double metric to be equal to 0.5", rep .getDoubleMetrics().get("doubleAttr") == 0.5); } |
### Question:
ThriftReportServer extends ThriftServer implements
ThriftFlumeReportServer.Iface { @Override public ThriftFlumeReport getReportByName(String reportName) throws TException { ReportManager reportManager = ReportManager.get(); Map<String, Reportable> reports = reportManager.getReportables(); if (reports.containsKey(reportName)) { return reportToThrift(reports.get(reportName).getReport()); } return null; } ThriftReportServer(FlumeConfiguration cfg); ThriftReportServer(int port); static ThriftFlumeReport reportToThrift(ReportEvent report); @Override ThriftFlumeReport getReportByName(String reportName); @Override Map<String, ThriftFlumeReport> getAllReports(); void serve(); void stop(); }### Answer:
@Test public void testGetReportByName() throws TException { TTransport transport = new TSocket("localhost", PORT); TProtocol protocol = new TBinaryProtocol(transport); transport.open(); ThriftFlumeReportServer.Client client = new ThriftFlumeReportServer.Client( protocol); ThriftFlumeReport rep = client.getReportByName("reportable1"); assertNotNull("Report 'repotable1' not found", rep); assertTrue("Expected exactly one double metric", rep.getDoubleMetricsSize() == 1); assertTrue("Expected double metric to be equal to 0.5", rep .getDoubleMetrics().get("doubleAttr") == 0.5); } |
### Question:
AvroReportServer implements AvroFlumeReportServer { @Override public Map<CharSequence, AvroFlumeReport> getAllReports() throws AvroRemoteException { Map<CharSequence, AvroFlumeReport> retMap = new HashMap<CharSequence, AvroFlumeReport>(); ReportManager reportManager = ReportManager.get(); Map<String, Reportable> reports = reportManager.getReportables(); for (Entry<String, Reportable> e : reports.entrySet()) { AvroFlumeReport report = reportToAvro(e.getValue().getReport()); retMap.put(e.getKey(), report); } return retMap; } AvroReportServer(FlumeConfiguration cfg); AvroReportServer(int port); @Override Map<CharSequence, AvroFlumeReport> getAllReports(); @Override AvroFlumeReport getReportByName(CharSequence reportName); static AvroFlumeReport reportToAvro(ReportEvent report); void serve(); void stop(); }### Answer:
@Test public void testGetAllReports() throws IOException { transport = new HttpTransceiver(url); try { this.avroClient = (AvroFlumeReportServer) SpecificRequestor.getClient( AvroFlumeReportServer.class, transport); } catch (Exception e) { throw new IOException("Failed to open AvroReportServer at " + PORT + " : " + e.getMessage()); } Map<CharSequence, AvroFlumeReport> ret = avroClient.getAllReports(); assertTrue(ret.size() == 1); AvroFlumeReport rep = ret.get(new Utf8("reportable1")); assertNotNull("Report 'reportable1' not found", rep); assertTrue("Expected exactly one double metric", rep.doubleMetrics.size() == 1); assertTrue("Expected double metric to be equal to 0.5", rep.doubleMetrics .get(new Utf8("doubleAttr")) == 0.5); } |
### Question:
AvroReportServer implements AvroFlumeReportServer { @Override public AvroFlumeReport getReportByName(CharSequence reportName) throws AvroRemoteException { ReportManager reportManager = ReportManager.get(); Map<String, Reportable> reports = reportManager.getReportables(); if (reports.containsKey(reportName.toString())) { return reportToAvro(reports.get(reportName.toString()).getReport()); } return null; } AvroReportServer(FlumeConfiguration cfg); AvroReportServer(int port); @Override Map<CharSequence, AvroFlumeReport> getAllReports(); @Override AvroFlumeReport getReportByName(CharSequence reportName); static AvroFlumeReport reportToAvro(ReportEvent report); void serve(); void stop(); }### Answer:
@Test public void testGetReportByName() throws IOException { transport = new HttpTransceiver(url); try { this.avroClient = (AvroFlumeReportServer) SpecificRequestor.getClient( AvroFlumeReportServer.class, transport); } catch (Exception e) { throw new IOException("Failed to open AvroReportServer at " + PORT + " : " + e.getMessage()); } AvroFlumeReport rep = avroClient.getReportByName("reportable1"); assertNotNull("Report 'reportable1' not found", rep); assertTrue("Expected exactly one double metric", rep.doubleMetrics.size() == 1); assertTrue("Expected double metric to be equal to 0.5", rep.doubleMetrics .get(new Utf8("doubleAttr")) == 0.5); } |
### Question:
SimpleMover implements Callable<InputFile> { @Override public InputFile call() throws IOException { final Path dst = this.entry.getTrackedDir(this.target); checkParent(dst); if (entry.getCurrentDir() == dst || (!fs.exists(dst) && fs.rename(entry.getCurrentDir(), dst))) { entry.updateCurrentDir(this.target); } else { log.error("Unable to move file " + entry.getCurrentDir().toUri() + " to " + dst.toUri() + ", skipping"); } return entry; } SimpleMover(Cache<Path,Path> directoryCache, InputFile entry, TrackedDir destination, FileSystem fs); @Override InputFile call(); }### Answer:
@Test public void testCall() throws Exception { FileSystem fs = FileSystem.getLocal(new Configuration()); Path file = getTestFile(fs); InputFile inFile = new InputFile("foo", file, 0, 0, 0, fmc.getBaseHDFSDir()); SimpleMover instance = new SimpleMover(directoryCache, inFile, TrackedDir.FLAGGED_DIR, fs); InputFile result = instance.call(); assertTrue("Should have moved to flagged", result.isMoved()); assertTrue(result.getCurrentDir().equals(result.getFlagged())); }
@Test public void testFailCall() throws Exception { FileSystem fs = FileSystem.getLocal(new Configuration()); Path file = getTestFile(fs); InputFile entry = new InputFile("foo", file, 0, 0, 0, fmc.getBaseHDFSDir()); fs.mkdirs(entry.getFlagging().getParent()); fs.copyFromLocalFile(file, entry.getFlagging()); SimpleMover instance = new SimpleMover(directoryCache, entry, TrackedDir.FLAGGING_DIR, fs); InputFile result = instance.call(); assertFalse("should not have moved due to collision", result.isMoved()); assertTrue(result.getCurrentDir().equals(result.getPath())); } |
### Question:
DatawaveCertRolesLoginModule extends CertRolesLoginModule { @Override public boolean login() throws LoginException { if (trustedHeaderLogin) { log.trace("trustedHeaderLogin is true - returning false for login success"); return false; } boolean success = super.login(); int roleCount = 0; Group[] roleSets = getRoleSets(); if (roleSets != null) { for (Group roleSet : roleSets) { for (Enumeration<? extends Principal> e = roleSet.members(); e.hasMoreElements(); e.nextElement()) { ++roleCount; } } } if (roleCount == 0) { loginOk = false; success = false; } return success; } DatawaveCertRolesLoginModule(); @Override void initialize(Subject subject, CallbackHandler callbackHandler, Map<String,?> sharedState, Map<String,?> options); @Override boolean login(); }### Answer:
@Test public void testSuccessfulLogin() throws Exception { String name = testUserCert.getSubjectDN().getName() + "<" + testUserCert.getIssuerDN().getName() + ">"; callbackHandler.name = name; callbackHandler.credential = testUserCert; boolean success = loginModule.login(); assertTrue("Login didn't succeed for alias in roles.properties", success); DatawavePrincipal principal = (DatawavePrincipal) field(DatawaveCertRolesLoginModule.class, "identity").get(loginModule); assertEquals(name.toLowerCase(), principal.getName()); }
@Test public void testFailedLogin() throws Exception { callbackHandler.name = "fakeUser"; callbackHandler.credential = testUserCert; boolean success = loginModule.login(); assertFalse("Login succeed for alias not in roles.properties", success); } |
### Question:
MultiTableRangePartitioner extends Partitioner<BulkIngestKey,Value> implements DelegatePartitioner { @Override public int getPartition(BulkIngestKey key, Value value, int numPartitions) { readCacheFilesIfNecessary(); String tableName = key.getTableName().toString(); Text[] cutPointArray = splitsByTable.get().get(tableName); if (null == cutPointArray) return (tableName.hashCode() & Integer.MAX_VALUE) % numPartitions; key.getKey().getRow(holder); int index = Arrays.binarySearch(cutPointArray, holder); index = calculateIndex(index, numPartitions, tableName, cutPointArray.length); index = partitionLimiter.limit(numPartitions, index); TaskInputOutputContext<?,?,?,?> c = context; if (c != null && collectStats) { c.getCounter("Partitions: " + key.getTableName(), "part." + formatter.format(index)).increment(1); } return index; } @Override int getPartition(BulkIngestKey key, Value value, int numPartitions); static void setContext(TaskInputOutputContext<?,?,?,?> context); @Override void initializeJob(Job job); @Override void setConf(Configuration conf); @Override void configureWithPrefix(String prefix); @Override int getNumPartitions(); @Override Configuration getConf(); static final String PARTITION_STATS; }### Answer:
@Test public void testGoodSplitsFile() throws IOException, URISyntaxException { mockContextForLocalCacheFile(createUrl("trimmed_splits.txt")); Assert.assertEquals(5, getPartition()); }
@Test(expected = RuntimeException.class) public void testEmptySplitsThrowsException() throws IOException, URISyntaxException { mockContextForLocalCacheFile(createUrl("trimmed_empty_splits.txt")); getPartition(); } |
### Question:
RowHashingPartitioner extends Partitioner<BulkIngestKey,Value> implements DelegatePartitioner { @Override public int getPartition(BulkIngestKey bKey, Value value, int reducers) { HashCodeBuilder hcb = new HashCodeBuilder(157, 41); Key key = bKey.getKey(); Text cf = key.getColumnFamily(); if (colFams.contains(cf)) { hcb.append(cf); } hcb.append(key.getRow()); int partition = (hcb.toHashCode() >>> 1) % reducers; if (log.isTraceEnabled()) { log.trace("Returning " + partition + " for BIK " + bKey); } return partition; } @Override int getPartition(BulkIngestKey bKey, Value value, int reducers); @Override Configuration getConf(); @Override void setConf(Configuration conf); @Override void configureWithPrefix(String prefix); @Override int getNumPartitions(); @Override void initializeJob(Job job); static final String COLUMN_FAMILIES; }### Answer:
@Test public void testShardPartitioning() { RowHashingPartitioner sdp = new RowHashingPartitioner(); final int nRed = 30; Text tbl = new Text("table"); for (int i = 0; i < 10; ++i) { String shard = "20110101_" + i; int expectedReducer = sdp.getPartition(new BulkIngestKey(tbl, new Key(shard, "fluff", "fluff")), null, nRed); for (int j = 0; j < 10; ++j) { Assert.assertEquals(expectedReducer, sdp.getPartition(new BulkIngestKey(tbl, new Key(shard, Integer.toHexString(j), "u")), null, nRed)); } } } |
### Question:
RowHashingPartitioner extends Partitioner<BulkIngestKey,Value> implements DelegatePartitioner { @Override public void setConf(Configuration conf) { this.conf = conf; configure(COLUMN_FAMILIES); } @Override int getPartition(BulkIngestKey bKey, Value value, int reducers); @Override Configuration getConf(); @Override void setConf(Configuration conf); @Override void configureWithPrefix(String prefix); @Override int getNumPartitions(); @Override void initializeJob(Job job); static final String COLUMN_FAMILIES; }### Answer:
@Test public void testShardAndCFPartitioning() { RowHashingPartitioner sdp = new RowHashingPartitioner(); Configuration conf = new Configuration(); conf.set(RowHashingPartitioner.COLUMN_FAMILIES, "tf"); sdp.setConf(conf); assertColumnFamilyPartitioning(sdp); } |
### Question:
TabletLocationHashPartitioner extends Partitioner<BulkIngestKey,Value> implements Configurable, DelegatePartitioner { @Override public void setConf(Configuration conf) { this.conf = conf; } @Override synchronized int getPartition(BulkIngestKey key, Value value, int numReduceTasks); @Override Configuration getConf(); @Override void setConf(Configuration conf); @Override void configureWithPrefix(String prefix); @Override int getNumPartitions(); @Override void initializeJob(Job job); }### Answer:
@Test public void testLocationHashPartitioner() throws Exception { conf.setInt(ShardIdFactory.NUM_SHARDS, SHARDS_PER_DAY); new TestShardGenerator(conf, NUM_DAYS, SHARDS_PER_DAY, TOTAL_TSERVERS, "shard"); TabletLocationHashPartitioner partitionerTwo = new TabletLocationHashPartitioner(); partitionerTwo.setConf(conf); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 0, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 1, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 2, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 3, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 4, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 5, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 20, MAX_EXPECTED_COLLISIONS); BalancedShardPartitionerTest.assertExpectedCollisions(partitionerTwo, 100, MAX_EXPECTED_COLLISIONS); } |
### Question:
LimitedKeyPartitioner extends Partitioner<BulkIngestKey,Value> implements Configurable, DelegatePartitioner { @Override public void setConf(Configuration conf) { this.conf = conf; partitionLimiter = new PartitionLimiter(conf); } @Override int getPartition(BulkIngestKey bKey, Value value, int numPartitions); @Override Configuration getConf(); @Override void setConf(Configuration conf); @Override void configureWithPrefix(String prefix); @Override int getNumPartitions(); @Override void initializeJob(Job job); }### Answer:
@Test public void testLimitedRangeSetViaGenericConfig() throws IllegalAccessException, InstantiationException { Configuration conf = new Configuration(); conf.setInt(PartitionLimiter.MAX_PARTITIONS_PROPERTY, 8); LimitedKeyPartitioner partitioner = LimitedKeyPartitioner.class.newInstance(); partitioner.setConf(conf); assertPartitionsUnderMax(partitioner, 8); }
@Test public void testHigherMaxThanReducers() throws IllegalAccessException, InstantiationException { Configuration conf = new Configuration(); conf.setInt(PartitionLimiter.MAX_PARTITIONS_PROPERTY, NUM_REDUCERS + 1); LimitedKeyPartitioner partitioner = LimitedKeyPartitioner.class.newInstance(); partitioner.setConf(conf); assertPartitionsUnderMax(partitioner, NUM_REDUCERS); } |
### Question:
LimitedKeyPartitioner extends Partitioner<BulkIngestKey,Value> implements Configurable, DelegatePartitioner { @Override public int getPartition(BulkIngestKey bKey, Value value, int numPartitions) { int partitioner = getKeyHashcode(bKey) & Integer.MAX_VALUE; return partitionLimiter.limit(numPartitions, partitioner); } @Override int getPartition(BulkIngestKey bKey, Value value, int numPartitions); @Override Configuration getConf(); @Override void setConf(Configuration conf); @Override void configureWithPrefix(String prefix); @Override int getNumPartitions(); @Override void initializeJob(Job job); }### Answer:
@Test(expected = Exception.class) public void testNoMaxPartitions() { LimitedKeyPartitioner partitioner = new LimitedKeyPartitioner(); partitioner.getPartition(createKeyFor(""), new Value(), NUM_REDUCERS); } |
### Question:
TermAndZone implements Serializable, Comparable<TermAndZone> { @Override public boolean equals(Object o) { if (o instanceof TermAndZone) { return this.term.equals(((TermAndZone) o).term) && this.zone.equals(((TermAndZone) o).zone); } return false; } TermAndZone(String token); TermAndZone(String term, String zone); String getToken(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object o); @Override int compareTo(TermAndZone o); public String zone; public String term; }### Answer:
@Test public void testEquals() { String token = "Hello:World"; String otherToken = "term:zone"; TermAndZone uut = new TermAndZone(token); TermAndZone match = new TermAndZone(token); TermAndZone other = new TermAndZone(otherToken); Object obj = new Object(); Assert.assertTrue("Equals failed to recognize a matching instance", uut.equals(match)); Assert.assertFalse("Equals incorrectly matched different instance", uut.equals(other)); Assert.assertFalse("Equals incorrectly matched a non-instance", uut.equals(obj)); } |
### Question:
TermAndZone implements Serializable, Comparable<TermAndZone> { @Override public int compareTo(TermAndZone o) { int comparison = this.zone.compareTo(o.zone); if (comparison == 0) { comparison = this.term.compareTo(o.term); } return comparison; } TermAndZone(String token); TermAndZone(String term, String zone); String getToken(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object o); @Override int compareTo(TermAndZone o); public String zone; public String term; }### Answer:
@Test public void testCompare() { String token = "Hello:World"; String lessZonetoken = "Hello:world"; String greaterZonetoken = "Hello:WORLD"; String lessTermToken = "term:World"; String greaterTermToken = "Ello:World"; TermAndZone uut = new TermAndZone(token); TermAndZone match = new TermAndZone(token); TermAndZone lessZone = new TermAndZone(lessZonetoken); TermAndZone greaterZone = new TermAndZone(greaterZonetoken); TermAndZone lessTerm = new TermAndZone(lessTermToken); TermAndZone greaterTerm = new TermAndZone(greaterTermToken); Assert.assertTrue("CompareTo failed to recognize a matching instance.", (0 == uut.compareTo(match))); Assert.assertTrue("CompareTo failed to recognize an instance containing a less than Zone value.", (0 > uut.compareTo(lessZone))); Assert.assertTrue("CompareTo failed to recognize an instance containing a less than Term value.", (0 > uut.compareTo(lessTerm))); Assert.assertTrue("CompareTo failed to recognize an instance containing a greater than Zone value.", (0 < uut.compareTo(greaterZone))); Assert.assertTrue("CompareTo failed to recognize an instance containing a greater than Term value.", (0 < uut.compareTo(greaterTerm))); } |
### Question:
BulkIngestKey implements WritableComparable<BulkIngestKey> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BulkIngestKey other = (BulkIngestKey) obj; return compareTo(other) == 0; } BulkIngestKey(); BulkIngestKey(Text tableName, Key key); Text getTableName(); Key getKey(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); void setTableName(final Text tableName); @Override int compareTo(BulkIngestKey other); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testEquals() { Text tableName1 = new Text("testTable"); Key key1 = new Key(new Text("row\0key"), new Text("colFam"), new Text("col\0qual"), new Text("col\0vis")); BulkIngestKey bik1 = new BulkIngestKey(tableName1, key1); Text tableName2 = new Text("testTable"); Key key2 = new Key(new Text("row\0key"), new Text("colFam"), new Text("col\0qual"), new Text("col\0vis")); BulkIngestKey bik2 = new BulkIngestKey(tableName2, key2); assertEquals(bik1, bik2); bik2 = new BulkIngestKey(new Text("differentTableName"), key2); assertFalse(bik1.equals(bik2)); bik2 = new BulkIngestKey(tableName2, new Key()); assertFalse(bik1.equals(bik2)); assertTrue(bik1.equals(bik1)); assertFalse(bik1.equals(null)); assertFalse(bik1.toString().equals("")); } |
### Question:
BulkIngestKey implements WritableComparable<BulkIngestKey> { @Override public int hashCode() { return hashCode; } BulkIngestKey(); BulkIngestKey(Text tableName, Key key); Text getTableName(); Key getKey(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override String toString(); void setTableName(final Text tableName); @Override int compareTo(BulkIngestKey other); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@Test public void testHashCode() { Text tableName1 = new Text("testTable"); Key key1 = new Key(new Text("row\0key"), new Text("colFam"), new Text("col\0qual"), new Text("col\0vis")); BulkIngestKey bik1 = new BulkIngestKey(tableName1, key1); Text tableName2 = new Text("testTable"); Key key2 = new Key(new Text("row\0key"), new Text("colFam"), new Text("col\0qual"), new Text("col\0vis")); BulkIngestKey bik2 = new BulkIngestKey(tableName2, key2); assertEquals(bik1.hashCode(), bik2.hashCode()); bik2 = new BulkIngestKey(new Text("differentTableName"), key2); assertNotEquals(bik1.hashCode(), bik2.hashCode()); bik2 = new BulkIngestKey(tableName2, new Key()); assertNotEquals(bik1.hashCode(), bik2.hashCode()); bik2 = new BulkIngestKey(tableName2, null); assertNotEquals(bik1.hashCode(), bik2.hashCode()); } |
### Question:
DelegatingPartitioner extends Partitioner<BulkIngestKey,Value> implements Configurable { @Override public void setConf(Configuration conf) { this.conf = conf; this.partitionerCache = new PartitionerCache(conf); try { createDelegatesForTables(); } catch (ClassNotFoundException e) { log.error(e); throw new RuntimeException(e); } } DelegatingPartitioner(); DelegatingPartitioner(Configuration configuration); static void configurePartitioner(Job job, Configuration conf, String[] tableNames); @Override // delegates partitioning int getPartition(BulkIngestKey key, Value value, int numPartitions); @Override Configuration getConf(); @Override void setConf(Configuration conf); }### Answer:
@Test(expected = Exception.class) public void testThrowsExceptionOnInconsistentConfig() throws Exception { conf.set(DelegatingPartitioner.TABLE_NAMES_WITH_CUSTOM_PARTITIONERS, "table1,table2"); conf.set(PartitionerCache.PREFIX_DEDICATED_PARTITIONER + "table1", AlwaysReturnOne.class.getName()); manager.setConf(conf); }
@Test(expected = IllegalArgumentException.class) public void testDoesntLikeEmptyList() throws Exception { conf.set(DelegatingPartitioner.TABLE_NAMES_WITH_CUSTOM_PARTITIONERS, ""); manager.setConf(conf); } |
### Question:
TableSplitsCache extends BaseHdfsFileCacheUtil { public FileStatus getFileStatus() { FileStatus splitsStatus = null; try { splitsStatus = FileSystem.get(this.splitsPath.toUri(), conf).getFileStatus(this.splitsPath); } catch (IOException ex) { String logMessage = ex instanceof FileNotFoundException ? "No splits file present" : "Could not get the FileStatus of the splits file"; log.warn(logMessage); } return splitsStatus; } TableSplitsCache(Configuration conf); static List<Text> trimSplits(List<Text> tableSplits, int maxSplits); @Override void setCacheFilePath(Configuration conf); static Path getSplitsPath(Configuration conf); static boolean shouldRefreshSplits(Configuration conf); FileStatus getFileStatus(); @Override void writeCacheFile(FileSystem fs, Path tmpSplitsFile); List<Text> getSplits(String table); List<Text> getSplits(String table, int maxSplits); Map<String,List<Text>> getSplits(); static final String REFRESH_SPLITS; static final String SPLITS_CACHE_DIR; static final String MAX_SPLIT_DECREASE; static final String MAX_SPLIT_PERCENTAGE_DECREASE; }### Answer:
@Test public void testGetFileStatus() { logger.info("testGetFileStatus called..."); setSplitsCacheDir(); setupConfiguration(); try { TableSplitsCache uut = new TableSplitsCache(createMockJobConf()); FileStatus fileStatus = uut.getFileStatus(); Assert.assertNotNull("FileStatus", fileStatus); } finally { logger.info("testGetFileStatus completed."); } } |
### Question:
MultiRFileOutputFormatter extends FileOutputFormat<BulkIngestKey,Value> { public static void setGenerateMapFilePerShardLocation(Configuration conf, boolean generateMapFilePerShardLocation) { conf.setBoolean(GENERATE_MAP_FILE_PER_SHARD_LOCATION, generateMapFilePerShardLocation); } static void setGenerateMapFileRowKeys(Configuration conf, boolean generateMapFileRowKeys); static void setGenerateMapFilePerShardLocation(Configuration conf, boolean generateMapFilePerShardLocation); static void setCompressionType(Configuration conf, String compressionType); static void setCompressionTableBlackList(Configuration conf, Set<String> compressionTableBlackList); static void setFileType(Configuration conf, String type); static void setAccumuloConfiguration(Configuration conf); static void setRFileLimits(Configuration conf, int maxEntries, long maxSize); static void addTableToLocalityGroupConfiguration(Configuration conf, String tableName); @Override synchronized OutputCommitter getOutputCommitter(TaskAttemptContext context); @Override RecordWriter<BulkIngestKey,Value> getRecordWriter(final TaskAttemptContext context); static final String CONFIGURE_LOCALITY_GROUPS; static final String EVENT_PARTITION_COUNT; static final String EDGE_PARTITION_COUNT; static final String INDEX_PARTITION_COUNT; static final String REV_INDEX_PARTITION_COUNT; static final String LOCATION_PARTITION_COUNT; static final String CONFIGURED_TABLE_NAMES; }### Answer:
@Test public void testTableSeparationWithFilePerShardLoc() throws IOException, InterruptedException { MultiRFileOutputFormatter.setGenerateMapFilePerShardLocation(conf, true); RecordWriter<BulkIngestKey,Value> writer = createWriter(formatter, conf); writeShardPairs(writer, 2); assertNumFileNames(3); assertFileNameForShardIndex(0); assertFileNameForShard(1, "server1", 1); assertFileNameForShard(2, "server2", 1); } |
### Question:
ConstraintChecker { public void check(Text table, byte[] visibility) throws ConstraintViolationException { if (!isConfigured) { return; } Collection<VisibilityConstraint> tableConstraints = constraints.get(table); if (tableConstraints != null && !tableConstraints.isEmpty()) { for (VisibilityConstraint constraint : tableConstraints) { if (!constraint.isValid(visibility)) { throw new ConstraintViolationException(table, constraint); } } } } private ConstraintChecker(Multimap<Text,VisibilityConstraint> constraints); static ConstraintChecker create(Configuration conf); boolean isConfigured(); void check(Text table, byte[] visibility); static final String INITIALIZERS; }### Answer:
@Test(expected = ConstraintChecker.ConstraintViolationException.class) public void shouldFailOnViolatedConstraint() { constraintChecker.check(new Text("eventTable"), emptyViz); }
@Test public void shouldPassOnNotViolatedConstraint() { constraintChecker.check(new Text("eventTable"), nonemptyViz); }
@Test public void shouldPassForNonConfiguredTable() { constraintChecker.check(new Text("indexTable"), emptyViz); } |
### Question:
PropogatingIterator implements SortedKeyValueIterator<Key,Value>, OptionDescriber { public PropogatingIterator deepCopy(IteratorEnvironment env) { return new PropogatingIterator(this, env); } private PropogatingIterator(PropogatingIterator other, IteratorEnvironment env); PropogatingIterator(); PropogatingIterator(SortedKeyValueIterator<Key,Value> iterator, ColumnToClassMapping<Combiner> Aggregators); PropogatingIterator deepCopy(IteratorEnvironment env); @Override Key getTopKey(); @Override Value getTopValue(); @Override boolean hasTop(); @Override void next(); @Override void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive); @Override void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options, IteratorEnvironment env); @Override IteratorOptions describeOptions(); @Override boolean validateOptions(Map<String,String> options); static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_DESCRIPTION; static final String UNNAMED_OPTION_DESCRIPTION; static final String AGGREGATOR_DEFAULT; static final String AGGREGATOR_DEFAULT_OPT; static final Map<String,String> defaultMapOptions; }### Answer:
@Test(expected = NullPointerException.class) public void testDeepCopyCannotCopyUninitialized() { PropogatingIterator uut = new PropogatingIterator(); uut.deepCopy(new MockIteratorEnvironment(false)); } |
### Question:
Now { public static Now getInstance() { if (instance == null) { synchronized (Now.class) { if (instance == null) { instance = new Now(false); } } } return instance; } Now(); private Now(boolean delegate); static Now getInstance(); long get(); @Override boolean equals(Object o2); @Override int hashCode(); }### Answer:
@Test public void testSingleton() { Now now = Now.getInstance(); Now now2 = Now.getInstance(); Assert.assertSame(now, now2); }
@Test public void testDelegate() { Now now = Now.getInstance(); Now now2 = new Now(); Assert.assertEquals(now, now2); }
@Test public void testDelegate3() { Now now = new Now(); Now now2 = Now.getInstance(); Assert.assertEquals(now, now2); } |
### Question:
Now { public Now() { this(true); } Now(); private Now(boolean delegate); static Now getInstance(); long get(); @Override boolean equals(Object o2); @Override int hashCode(); }### Answer:
@Test public void testNow() throws InterruptedException { Now now = Now.getInstance(); for (int i = 0; i < 5; i++) { long time = System.currentTimeMillis(); long nowTime = now.get(); long time2 = System.currentTimeMillis(); Assert.assertTrue("Failed to get a reasonable time from the Now class....may be due running tests on a very busy machine", Math.abs(nowTime - time) < (1100 + time2 - time)); Thread.sleep(1000); } } |
### Question:
JsonIngestHelper extends ContentBaseIngestHelper { @Override public void setup(Configuration config) { super.setup(config); helper = new JsonDataTypeHelper(); helper.setup(config); this.setEmbeddedHelper(helper); flattener = helper.newFlattener(); } @Override void setup(Configuration config); @Override Multimap<String,NormalizedContentInterface> getEventFields(RawRecordContainer event); }### Answer:
@Test public void testSetup() throws Exception { JsonIngestHelper ingestHelper = init(initConfig(FlattenMode.NORMAL)); Assert.assertNotNull(ingestHelper.getEmbeddedHelper()); } |
### Question:
ContentJsonColumnBasedHandler extends ContentIndexingColumnBasedHandler<KEYIN> { @Override public void setup(TaskAttemptContext context) { super.setup(context); } @Override void setup(TaskAttemptContext context); @Override AbstractContentIngestHelper getContentIndexingDataTypeHelper(); }### Answer:
@Test public void testJsonContentHandlers() throws Exception { conf.addResource(ClassLoader.getSystemResource("config/ingest/all-config.xml")); conf.addResource(ClassLoader.getSystemResource("config/ingest/tvmaze-ingest-config.xml")); conf.addResource(ClassLoader.getSystemResource("config/ingest/edge-ingest-config.xml")); conf.addResource(ClassLoader.getSystemResource("config/ingest/metadata-config.xml")); TypeRegistry.getInstance(conf); JsonDataTypeHelper helper = new JsonDataTypeHelper(); helper.setup(conf); JsonIngestHelper ingestHelper = new JsonIngestHelper(); ingestHelper.setup(conf); TaskAttemptContext context = new TaskAttemptContextImpl(conf, new TaskAttemptID()); ContentJsonColumnBasedHandler<Text> jsonHandler = new ContentJsonColumnBasedHandler<>(); jsonHandler.setup(context); JsonRecordReader reader = getJsonRecordReader("/input/tvmaze-seinfeld.json"); Assert.assertTrue("First Record did not read properly?", reader.nextKeyValue()); RawRecordContainer event = reader.getEvent(); Assert.assertNotNull("Event 1 was null.", event); Assert.assertTrue("Event 1 has parsing errors", event.getErrors().isEmpty()); ProtobufEdgeDataTypeHandler<Text,BulkIngestKey,Value> edgeHandler = new ProtobufEdgeDataTypeHandler<>(); edgeHandler.setup(context); ColumnBasedHandlerTestUtil.processEvent(jsonHandler, edgeHandler, event, 231, 90, 4, 38, PRINT_GENERATED_KEYS_ONLY_ON_FAIL); reader.close(); } |
### Question:
JsonRecordReader extends AbstractEventRecordReader<BytesWritable> { @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { super.initialize(split, context); if (!(split instanceof FileSplit)) { throw new IOException("Cannot handle split type " + split.getClass().getName()); } FileSplit fsplit = (FileSplit) split; Path file = fsplit.getPath(); rawFileName = file.getName(); fileURI = file.toUri(); FileSystem fs = file.getFileSystem(context.getConfiguration()); InputStream is = fs.open(file); start = fsplit.getStart(); end = start + fsplit.getLength(); pos = start; String normURI = fileURI.getScheme() + ": setupReader(is); if (logger.isInfoEnabled()) { logger.info("Reading Json records from " + normURI + " via " + is.getClass().getName()); } jsonHelper = (JsonDataTypeHelper) createHelper(context.getConfiguration()); this.parseHeaderOnly = !jsonHelper.processExtraFields(); jsonFlattener = jsonHelper.newFlattener(); if (logger.isInfoEnabled()) { logger.info("Json flattener mode: " + jsonFlattener.getFlattenMode().name()); } } @Override void close(); @Override LongWritable getCurrentKey(); @Override BytesWritable getCurrentValue(); Multimap<String,String> getCurrentFields(); @Override float getProgress(); @Override void initialize(InputSplit split, TaskAttemptContext context); @Override boolean nextKeyValue(); @Override RawRecordContainer getEvent(); boolean isParseHeaderOnly(); }### Answer:
@Test public void testInitialize() throws Exception { JsonRecordReader reader = init(true, FlattenMode.NORMAL); reader.close(); } |
### Question:
Files { public static void ensureDir(final String dir) { ensureDir(dir, false); } static void ensureDir(final String dir); static void ensureDir(final String dir, final boolean checkWrite); static void ensureDir(final File dir); static void ensureDir(final File dir, final boolean checkWrite); static String checkDir(final String dir); static String checkDir(final String dir, final boolean checkWrite); static String checkDir(final File dir); static String checkDir(final File dir, final boolean checkWrite); static String checkFile(final File file, final boolean checkWrite); static void ensureMv(final String src, final String dest); static void ensureMv(final String src, final String dest, final boolean overwrite); static void ensureMv(final File src, final File dest); static void ensureMv(final File src, final File dest, final boolean overwrite); static String mv(final String src, final String dest); static String mv(final String src, final String dest, final boolean overwrite); static String mv(final File src, final File dest); static String mv(final File src, final File dest, final boolean overwrite); static File tmpDir(); }### Answer:
@Test(expected = IllegalStateException.class) public void testEnsureDirException() throws Exception { File file = mock(File.class); expect(file.exists()).andReturn(false); expect(file.mkdirs()).andReturn(false); replay(file); Files.ensureDir(file); }
@Test public void testEnsureDirString() throws Exception { Files.ensureDir("file"); } |
### Question:
DataTypeHelperImpl implements DataTypeHelper { @Override public void setup(Configuration config) { initType(config); String policyEnforcerClass = ""; if (null != config.get("all" + Properties.INGEST_POLICY_ENFORCER_CLASS)) { policyEnforcerClass = config.get("all" + Properties.INGEST_POLICY_ENFORCER_CLASS); } if (null != config.get(getType().typeName() + Properties.INGEST_POLICY_ENFORCER_CLASS)) { policyEnforcerClass = config.get(getType().typeName() + Properties.INGEST_POLICY_ENFORCER_CLASS); } try { ingestPolicyEnforcer = (IngestPolicyEnforcer) Class.forName(policyEnforcerClass).newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { logger.error(e.getLocalizedMessage()); throw new RuntimeException(e.getLocalizedMessage()); } aliaser.setup(getType(), config); } @Override void setup(Configuration config); Type getType(); String clean(String fieldName, String fieldValue); IngestPolicyEnforcer getPolicyEnforcer(); void setPolicyEnforcer(IngestPolicyEnforcer ingestPolicyEnforcer); }### Answer:
@Test(expected = IllegalArgumentException.class) public void testInvalidConfig() { DataTypeHelperImpl helper = new DataTypeHelperImpl(); TypeRegistry.reset(); TypeRegistry.getInstance(conf); helper.setup(conf); } |
### Question:
Files { public static File tmpDir() { return new File(System.getProperty("java.io.tmpdir")); } static void ensureDir(final String dir); static void ensureDir(final String dir, final boolean checkWrite); static void ensureDir(final File dir); static void ensureDir(final File dir, final boolean checkWrite); static String checkDir(final String dir); static String checkDir(final String dir, final boolean checkWrite); static String checkDir(final File dir); static String checkDir(final File dir, final boolean checkWrite); static String checkFile(final File file, final boolean checkWrite); static void ensureMv(final String src, final String dest); static void ensureMv(final String src, final String dest, final boolean overwrite); static void ensureMv(final File src, final File dest); static void ensureMv(final File src, final File dest, final boolean overwrite); static String mv(final String src, final String dest); static String mv(final String src, final String dest, final boolean overwrite); static String mv(final File src, final File dest); static String mv(final File src, final File dest, final boolean overwrite); static File tmpDir(); }### Answer:
@Test public void testTmpDir() throws Exception { File tmp = Files.tmpDir(); assertNotNull(tmp); } |
### Question:
OptionBuilder { public Option create(final String opt, final String desc) { return create(opt, null, desc); } Option create(final String opt, final String desc); Option create(final String opt, final String longOpt, final String desc); void reset(); public int args; public char valSeparator; public boolean required; public boolean optionalArg; public Class<?> type; }### Answer:
@Test public void testCreate() throws Exception { Option option = this.optionBuilder.create("opt", "desc"); assertEquals(option.getArgs(), 0); assertEquals(String.class, option.getType()); assertEquals(option.getOpt(), "opt"); assertEquals(option.getDescription(), "desc"); assertNull(option.getLongOpt()); assertFalse(option.isRequired()); assertEquals(option.getValueSeparator(), 0); }
@Test public void testCreate1() throws Exception { Option option = this.optionBuilder.create("opt", "longOpt", "desc"); assertEquals(option.getLongOpt(), "longOpt"); } |
### Question:
IngestFieldFilter { public void setup(Configuration conf) { fieldNameFilters = new FieldConfiguration(); fieldNameFilters.load(conf.get(dataType.typeName() + FILTER_FIELD_SUFFIX), false); fieldNameFilters.load(conf.get(dataType.typeName() + FILTER_FIELD_NAME_SUFFIX), false); logger.info("Field Name Filters for " + dataType.typeName() + ": " + fieldNameFilters); fieldValueFilters = new FieldConfiguration(conf.get(dataType.typeName() + FILTER_FIELD_VALUE_SUFFIX), true); logger.info("Field Value Filters for " + dataType.typeName() + ": " + fieldValueFilters); } IngestFieldFilter(Type dataType); void setup(Configuration conf); void apply(Multimap<String,?> fields); @Deprecated
static final String FILTER_FIELD_SUFFIX; static final String FILTER_FIELD_NAME_SUFFIX; static final String FILTER_FIELD_VALUE_SUFFIX; static final char PAIR_DELIM; static final char VALUE_DELIM; static final char FIELD_DELIM; }### Answer:
@Test(expected = IllegalArgumentException.class) public void shouldFailOnIncorrectConfig1() { conf.set(dataType.typeName() + IngestFieldFilter.FILTER_FIELD_NAME_SUFFIX, "TOO:MANY:TOKENS,NAME:NICKNAME"); filter.setup(conf); }
@Test(expected = IllegalArgumentException.class) public void shouldFailOnIncorrectConfig2() { conf.set(dataType.typeName() + IngestFieldFilter.FILTER_FIELD_VALUE_SUFFIX, "COUNT:DOES&NOT&MATCH"); filter.setup(conf); } |
### Question:
ResourceAvailabilityUtil { public static boolean isDiskAvailable(float minPercentageAvailable) { return isDiskAvailable(ROOT_PATH, minPercentageAvailable); } static boolean isMemoryAvailable(float minPercentageAvailable); static boolean isDiskAvailable(float minPercentageAvailable); static boolean isDiskAvailable(final String path, float minPercentageAvailable); static final String ROOT_PATH; }### Answer:
@Test public void testIsDiskAvailable_DefaultPath() { float reasonableMinAvailability = 0.0f; float unreasonableMinAvailability = 1.01f; boolean result1 = ResourceAvailabilityUtil.isDiskAvailable("/", reasonableMinAvailability); boolean result2 = ResourceAvailabilityUtil.isDiskAvailable(unreasonableMinAvailability); assertTrue(reasonableMinAvailability + "% minimum disk space should always be available", result1); assertTrue(unreasonableMinAvailability + "% minimum disk space should never be available", !result2); } |
### Question:
ResourceAvailabilityUtil { public static boolean isMemoryAvailable(float minPercentageAvailable) { final Runtime runtime = Runtime.getRuntime(); long freeMemory = runtime.freeMemory(); long totalMemory = runtime.totalMemory(); return ((((double) freeMemory / (double) totalMemory))) >= minPercentageAvailable; } static boolean isMemoryAvailable(float minPercentageAvailable); static boolean isDiskAvailable(float minPercentageAvailable); static boolean isDiskAvailable(final String path, float minPercentageAvailable); static final String ROOT_PATH; }### Answer:
@Test public void testIsMemoryAvailable_DefaultPath() { float reasonableMinAvailability = 0.0f; float unreasonableMinAvailability = 1.01f; boolean result1 = ResourceAvailabilityUtil.isMemoryAvailable(reasonableMinAvailability); boolean result2 = ResourceAvailabilityUtil.isMemoryAvailable(unreasonableMinAvailability); assertTrue(reasonableMinAvailability + "% minimum memory should always be available", result1); assertTrue(unreasonableMinAvailability + "% minimum memory should never be available", !result2); } |
### Question:
ShardIndexKeyFunctor implements KeyFunctor { static boolean isKeyInBloomFilter(org.apache.accumulo.core.data.Key cbKey) { return (cbKey.getRowData().length() > 0 && cbKey.getColumnFamilyData().length() > 0); } @Override org.apache.hadoop.util.bloom.Key transform(org.apache.accumulo.core.data.Key cbKey); @Override org.apache.hadoop.util.bloom.Key transform(Range range); }### Answer:
@Test public void testIsKeyInBloomFilter() { org.apache.accumulo.core.data.Key cbKey = new org.apache.accumulo.core.data.Key(); Assert.assertFalse("empty key should not be in bloom filter", ShardIndexKeyFunctor.isKeyInBloomFilter(cbKey)); cbKey = new org.apache.accumulo.core.data.Key("row only"); Assert.assertFalse("row only key should not be in bloom filter", ShardIndexKeyFunctor.isKeyInBloomFilter(cbKey)); cbKey = new org.apache.accumulo.core.data.Key("", "cf only"); Assert.assertFalse("cf only key should not be in bloom filter", ShardIndexKeyFunctor.isKeyInBloomFilter(cbKey)); cbKey = new org.apache.accumulo.core.data.Key("", "", "cq only"); Assert.assertFalse("cq only key should not be in bloom filter", ShardIndexKeyFunctor.isKeyInBloomFilter(cbKey)); cbKey = new org.apache.accumulo.core.data.Key("row", "", "and cq"); Assert.assertFalse("row and cq only key should not be in bloom filter", ShardIndexKeyFunctor.isKeyInBloomFilter(cbKey)); cbKey = new org.apache.accumulo.core.data.Key("row", "and cf"); Assert.assertTrue("row and cf only key should be in bloom filter", ShardIndexKeyFunctor.isKeyInBloomFilter(cbKey)); } |
### Question:
QueryPropertyMarker extends ASTReference { public static boolean instanceOf(JexlNode node, Class<? extends QueryPropertyMarker> type) { return QueryPropertyMarkerVisitor.instanceOf(node, type, null); } QueryPropertyMarker(); QueryPropertyMarker(int id); QueryPropertyMarker(Parser p, int id); QueryPropertyMarker(JexlNode source); static boolean instanceOf(JexlNode node, Class<? extends QueryPropertyMarker> type); static JexlNode getQueryPropertySource(JexlNode node, Class<? extends QueryPropertyMarker> type); }### Answer:
@Test public void instanceOfTest() throws Exception { String baseQuery = "(GEO >= '0202' && GEO <= '020d') && (WKT_BYTE_LENGTH >= '+AE0' && WKT_BYTE_LENGTH < '+bE8')"; JexlNode baseQueryNode = JexlASTHelper.parseJexlQuery(baseQuery); JexlNode delayedNode = ASTDelayedPredicate.create(baseQueryNode); assertTrue(ASTDelayedPredicate.instanceOf(delayedNode)); JexlNode sourceNode = ASTDelayedPredicate.getDelayedPredicateSource(delayedNode); assertEquals(baseQuery, JexlStringBuildingVisitor.buildQuery(sourceNode)); String delayedQueryString = JexlStringBuildingVisitor.buildQuery(delayedNode); JexlNode reconstructedDelayedNode = JexlASTHelper.parseJexlQuery(delayedQueryString); assertTrue(ASTDelayedPredicate.instanceOf(reconstructedDelayedNode)); sourceNode = ASTDelayedPredicate.getDelayedPredicateSource(delayedNode); assertEquals(baseQuery, JexlStringBuildingVisitor.buildQuery(sourceNode)); } |
### Question:
QueryPropertyMarker extends ASTReference { public static JexlNode getQueryPropertySource(JexlNode node, Class<? extends QueryPropertyMarker> type) { List<JexlNode> sourceNodes = new ArrayList<>(); if (QueryPropertyMarkerVisitor.instanceOf(node, type, sourceNodes) && !sourceNodes.isEmpty()) { if (sourceNodes.size() == 1) return sourceNodes.get(0); else return JexlNodeFactory.createUnwrappedAndNode(sourceNodes); } return null; } QueryPropertyMarker(); QueryPropertyMarker(int id); QueryPropertyMarker(Parser p, int id); QueryPropertyMarker(JexlNode source); static boolean instanceOf(JexlNode node, Class<? extends QueryPropertyMarker> type); static JexlNode getQueryPropertySource(JexlNode node, Class<? extends QueryPropertyMarker> type); }### Answer:
@Test public void testGetQueryPropertySource() throws ParseException { String source = "FOO == 'bar'"; JexlNode sourceNode = JexlASTHelper.parseJexlQuery(source); JexlNode delayedNode = ASTDelayedPredicate.create(sourceNode); String delayedString = JexlStringBuildingVisitor.buildQueryWithoutParse(delayedNode); assertEquals(delayedString, "((ASTDelayedPredicate = true) && (FOO == 'bar'))"); JexlNode parsedSource = QueryPropertyMarker.getQueryPropertySource(delayedNode, ASTDelayedPredicate.class); assertEquals(sourceNode, parsedSource); } |
### Question:
UniqueTransform extends DocumentTransform.DefaultDocumentTransform { @Nullable @Override public Entry<Key,Document> apply(@Nullable Entry<Key,Document> keyDocumentEntry) { if (keyDocumentEntry != null) { try { if (isDuplicate(keyDocumentEntry.getValue())) { keyDocumentEntry = null; } } catch (IOException ioe) { log.error("Failed to convert document to bytes. Returning document as unique.", ioe); } } return keyDocumentEntry; } UniqueTransform(Set<String> fields); UniqueTransform(BaseQueryLogic<Entry<Key,Value>> logic, Set<String> fields); Predicate<Entry<Key,Document>> getUniquePredicate(); @Nullable @Override Entry<Key,Document> apply(@Nullable Entry<Key,Document> keyDocumentEntry); }### Answer:
@Test public void testUniqueness() { Random random = new Random(2000); List<Document> input = new ArrayList<>(); for (int i = 0; i < 100; i++) { input.add(createDocument(random, false)); } Set<String> fields = new HashSet<>(); int expected = input.size(); while (expected > input.size() / 2 || expected < 10) { fields.clear(); while (fields.size() < 3) { fields.add("Attr" + random.nextInt(100)); } expected = countUniqueness(input, fields); } Transformer docToEntry = input1 -> { Document d = (Document) input1; return Maps.immutableEntry(d.getMetadata(), d); }; TransformIterator inputIterator = new TransformIterator(input.iterator(), docToEntry); fields = fields.stream().map(field -> (random.nextBoolean() ? '$' + field : field)).collect(Collectors.toSet()); UniqueTransform transform = new UniqueTransform(fields); Iterator iter = Iterators.transform(inputIterator, transform); List<Object> eventList = Lists.newArrayList(); while (iter.hasNext()) { Object next = iter.next(); if (next != null) { eventList.add(next); } } Assert.assertEquals(expected, eventList.size()); Assert.assertNull(transform.apply(null)); } |
### Question:
FlagMaker implements Runnable, Observer, SizeValidator { FileSystem getHadoopFS() throws IOException { Configuration hadoopConfiguration = new Configuration(); hadoopConfiguration.set("fs.defaultFS", fmc.getHdfs()); try { return FileSystem.get(hadoopConfiguration); } catch (IOException ex) { log.error("Unable to connect to HDFS. Exiting"); throw ex; } } FlagMaker(FlagMakerConfig fmconfig); static void main(String... args); @Override void run(); @Override void update(Observable o, Object arg); @Override boolean isValidSize(FlagDataTypeConfig fc, Collection<InputFile> files); static final Pattern pattern; }### Answer:
@Test public void testGetHadoopFS() throws Exception { log.info("----- testGetHadoopFS -----"); File fdir = new File(FLAG_DIR); if (fdir.exists()) fdir.delete(); FlagMaker instance = new TestWrappedFlagMaker(fmc); FileSystem result = instance.getHadoopFS(); result.mkdirs(new Path(FLAG_DIR)); assertTrue(fdir.exists() && fdir.isDirectory()); } |
### Question:
DatawaveKey { public boolean isInvalidKey() { return invalidKey; } DatawaveKey(Key key); DatawaveKey setReverse(final boolean isReverse); String getShardId(boolean ignore); String getShardId(); String getFieldName(boolean ignore); String getFieldName(); String getFieldValue(boolean ignore); String getFieldValue(); KeyType getType(); String getUid(); Text getRow(); long getTimeStamp(); String getDataType(); boolean isInvalidKey(); @Override String toString(); static final int NULL; static final Text DOCUMENT_COLUMN; static final byte[] DOCUMENT_COLUMN_BYTES; static final Text TF_COLUMN; static final byte[] TF_COLUMN_BYTES; static final Text FI_COLUMN; static final byte[] FI_COLUMN_BYTES; }### Answer:
@Test public void parseShardFiKeyInvalid() { Key testKey = new Key("row", "fi\u0000fieldNameA", "fieldValueA\u0000datatype", "viz"); DatawaveKey key = new DatawaveKey(testKey); Assert.assertTrue(key.isInvalidKey()); } |
### Question:
RegexTrie { public boolean contains(final String string) { Node current = root; final int length = string.length(); for (int i = 0; i < length; i++) { current = current.next.get(string.charAt(i)); if (current == null) { return false; } } return current.terminator; } RegexTrie(); RegexTrie(List<String> strings); RegexTrie(String... strings); void addAll(List<String> strings); void add(String string); boolean contains(final String string); String toRegex(); }### Answer:
@Test public void testTrie() { String[] strings = new String[] {"", "A", "AB", "ABCDEF", "BC", "BB"}; String[] other = new String[] {"AA", "B", "BBB", "BCB", "ABC", "ABCD", "ABCDE", "ABCDEFF", "C"}; RegexTrie trie = new RegexTrie(Arrays.asList(strings)); for (String string : strings) { Assert.assertTrue(trie.contains(string)); } for (String string : other) { Assert.assertFalse(trie.contains(string)); } } |
### Question:
RegexTrie { public String toRegex() { StringBuilder regex = new StringBuilder(); toRegex(root, regex); return regex.toString(); } RegexTrie(); RegexTrie(List<String> strings); RegexTrie(String... strings); void addAll(List<String> strings); void add(String string); boolean contains(final String string); String toRegex(); }### Answer:
@Test public void testRegex() { String[] strings = new String[] {"", "A", "AB", "ABCDEF", "BC", "BB"}; String[] other = new String[] {"AA", "B", "BBB", "BCB", "ABC", "ABCD", "ABCDE", "ABCDEFF", "C"}; String regex = new RegexTrie(Arrays.asList(strings)).toRegex(); Pattern pattern = Pattern.compile(regex); for (String string : strings) { Assert.assertTrue(pattern.matcher(string).matches()); } for (String string : other) { Assert.assertFalse(pattern.matcher(string).matches()); } } |
### Question:
ShardTableConfigHelper extends AbstractTableConfigHelper { @Override public void configure(TableOperations tops) throws AccumuloException, AccumuloSecurityException, TableNotFoundException { switch (this.tableType) { case SHARD: configureShardTable(tops); break; case GIDX: configureGidxTable(tops); break; case GRIDX: configureGridxTable(tops); break; case DINDX: configureDictionaryTable(tops); break; default: throw new TableNotFoundException(null, tableName, "Table is not a Shard Type Table"); } } @Override void setup(String tableName, Configuration config, Logger log); @Override void configure(TableOperations tops); static final String SHARD_TABLE_BALANCER_CONFIG; static final String ENABLE_BLOOM_FILTERS; static final String MARKINGS_SETUP_ITERATOR_ENABLED; static final String MARKINGS_SETUP_ITERATOR_CONFIG; static final String LOCALITY_GROUPS; }### Answer:
@Test(expected = NullPointerException.class) public void testConfigureCalledBeforeSetup() throws AccumuloSecurityException, AccumuloException, TableNotFoundException { ShardTableConfigHelperTest.logger.info("ShardTableConfigHelperTest.testConfigureCalledBeforeSetup called."); try { ShardTableConfigHelper uut = new ShardTableConfigHelper(); TableOperations tops = mockUpTableOperations(); uut.configure(tops); Assert.fail("ShardTableConfigHelper.configure failed to throw expected exception."); } finally { ShardTableConfigHelperTest.logger.info("ShardTableConfigHelperTest.testConfigureCalledBeforeSetup completed."); } } |
### Question:
ChainableEventDataQueryFilter implements EventDataQueryFilter { @Override public void startNewDocument(Key documentKey) { for (int i = 0; i < filters.size(); i++) { filters.get(i).startNewDocument(documentKey); } } ChainableEventDataQueryFilter(); private ChainableEventDataQueryFilter(ChainableEventDataQueryFilter other); void addFilter(EventDataQueryFilter filter); @Override void startNewDocument(Key documentKey); @Override boolean apply(@Nullable Map.Entry<Key,String> entry); @Override boolean peek(@Nullable Map.Entry<Key,String> entry); @Override boolean keep(Key k); @Override Key getStartKey(Key from); @Override Key getStopKey(Key from); @Override Range getKeyRange(Map.Entry<Key,Document> from); @Override EventDataQueryFilter clone(); @Override Range getSeekRange(Key current, Key endKey, boolean endKeyInclusive); @Override int getMaxNextCount(); @Override Key transform(Key toTransform); }### Answer:
@Test public void startNewDocumentTest() { EventDataQueryFilter mockFilter1 = EasyMock.createMock(EventDataQueryFilter.class); EventDataQueryFilter mockFilter2 = EasyMock.createMock(EventDataQueryFilter.class); Key key = new Key(); mockFilter1.startNewDocument(key); mockFilter2.startNewDocument(key); EasyMock.replay(mockFilter1, mockFilter2); filter.addFilter(mockFilter1); filter.addFilter(mockFilter2); filter.startNewDocument(key); EasyMock.verify(mockFilter1, mockFilter2); } |
### Question:
RangeFactory { public static Range createDocumentSpecificRange(String shard, String docId) { Key start = new Key(shard, docId); Key end = start.followingKey(PartialKey.ROW_COLFAM); return new Range(start, true, end, false); } static Range createDocumentSpecificRange(String shard, String docId); static Range createTldDocumentSpecificRange(String shard, String docId); static Range createShardRange(String shard); static Range createDayRange(String shard); static final String NULL_BYTE_STRING; static final String MAX_UNICODE_STRING; }### Answer:
@Test public void testBuildDocumentSpecificRange() { String shard = "20190314_0"; String docId = "docId0"; Range docRange = RangeFactory.createDocumentSpecificRange(shard, docId); String expectedEndKeyCF = docId + RangeFactory.NULL_BYTE_STRING; assertEquals(shard, docRange.getStartKey().getRow().toString()); assertEquals(docId, docRange.getStartKey().getColumnFamily().toString()); assertEquals(shard, docRange.getEndKey().getRow().toString()); assertEquals(expectedEndKeyCF, docRange.getEndKey().getColumnFamily().toString()); } |
### Question:
RangeFactory { public static Range createTldDocumentSpecificRange(String shard, String docId) { Key start = new Key(shard, docId); Key end = new Key(shard, docId + MAX_UNICODE_STRING); return new Range(start, true, end, false); } static Range createDocumentSpecificRange(String shard, String docId); static Range createTldDocumentSpecificRange(String shard, String docId); static Range createShardRange(String shard); static Range createDayRange(String shard); static final String NULL_BYTE_STRING; static final String MAX_UNICODE_STRING; }### Answer:
@Test public void testBuildTldDocumentSpecificRange() { String shard = "20190314_0"; String docId = "docId0"; Range tldDocRange = RangeFactory.createTldDocumentSpecificRange(shard, docId); String expectedEndKeyCF = docId + RangeFactory.MAX_UNICODE_STRING; assertEquals(shard, tldDocRange.getStartKey().getRow().toString()); assertEquals(docId, tldDocRange.getStartKey().getColumnFamily().toString()); assertEquals(shard, tldDocRange.getEndKey().getRow().toString()); assertEquals(expectedEndKeyCF, tldDocRange.getEndKey().getColumnFamily().toString()); } |
### Question:
RangeFactory { public static Range createShardRange(String shard) { Key start = new Key(shard); Key end = new Key(shard + NULL_BYTE_STRING); return new Range(start, true, end, false); } static Range createDocumentSpecificRange(String shard, String docId); static Range createTldDocumentSpecificRange(String shard, String docId); static Range createShardRange(String shard); static Range createDayRange(String shard); static final String NULL_BYTE_STRING; static final String MAX_UNICODE_STRING; }### Answer:
@Test public void testBuildShardRange() { String shard = "20190314_0"; Range shardRange = RangeFactory.createShardRange(shard); String expectedEndKeyRow = shard + RangeFactory.NULL_BYTE_STRING; assertEquals(shard, shardRange.getStartKey().getRow().toString()); assertEquals(expectedEndKeyRow, shardRange.getEndKey().getRow().toString()); } |
### Question:
RangeFactory { public static Range createDayRange(String shard) { Key start = new Key(shard + FIRST_SHARD); Key end = new Key(shard + MAX_UNICODE_STRING); return new Range(start, true, end, false); } static Range createDocumentSpecificRange(String shard, String docId); static Range createTldDocumentSpecificRange(String shard, String docId); static Range createShardRange(String shard); static Range createDayRange(String shard); static final String NULL_BYTE_STRING; static final String MAX_UNICODE_STRING; }### Answer:
@Test public void testBuildDayRange() { String shard = "20190314"; Range dayRange = RangeFactory.createDayRange(shard); String expectedStartKeyRow = "20190314_0"; String expectedEndKeyRow = shard + RangeFactory.MAX_UNICODE_STRING; assertEquals(expectedStartKeyRow, dayRange.getStartKey().getRow().toString()); assertEquals(expectedEndKeyRow, dayRange.getEndKey().getRow().toString()); } |
### Question:
GetStartKeyForRoot implements Function<Range,Key> { @Override public Key apply(Range input) { Key k = input.getStartKey(); return TLD.buildParentKey(k.getRow(), TLD.parseRootPointerFromId(k.getColumnFamilyData()), k.getColumnQualifierData(), k.getColumnVisibility(), k.getTimestamp()); } static GetStartKeyForRoot instance(); @Override Key apply(Range input); }### Answer:
@Test public void testApply() { String shard = "20190314_0"; String doc = "datatype\u0000p1.p2.p3.c1.gc1"; Key start = new Key(shard, doc); Key end = new Key(shard, doc + "\uffff"); Range range = new Range(start, true, end, false); Key expected = new Key(shard, "datatype\u0000p1.p2.p3"); assertEquals(expected, GetStartKeyForRoot.instance().apply(range)); } |
### Question:
TLD { public static ByteSequence parsePointerFromFI(ByteSequence cq) { ArrayList<Integer> nulls = lastInstancesOf(0, cq, 2); final int start = nulls.get(1) + 1, stop = cq.length(); return cq.subSequence(start, stop); } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testParsePointerFromFI() { Key fiKey = buildFiKey(rootId); ByteSequence parsed = TLD.parsePointerFromFI(fiKey.getColumnQualifierData()); ByteSequence expected = new ArrayByteSequence(datatype + '\u0000' + rootId); assertEquals(expected, parsed); fiKey = buildFiKey(childId); parsed = TLD.parsePointerFromFI(fiKey.getColumnQualifierData()); expected = new ArrayByteSequence(datatype + '\u0000' + childId); assertEquals(expected, parsed); fiKey = buildFiKey(grandchildId); parsed = TLD.parsePointerFromFI(fiKey.getColumnQualifierData()); expected = new ArrayByteSequence(datatype + '\u0000' + grandchildId); assertEquals(expected, parsed); } |
### Question:
TLD { public static ByteSequence parseRootPointerFromFI(ByteSequence cq) { ArrayList<Integer> nulls = lastInstancesOf(0, cq, 2); final int start = nulls.get(1) + 1, stop = cq.length(); return parseRootPointerFromId(cq.subSequence(start, stop)); } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testParseRootPointerFromFI() { Key fiKey = buildFiKey(rootId); ByteSequence parsed = TLD.parseRootPointerFromFI(fiKey.getColumnQualifierData()); ByteSequence expected = new ArrayByteSequence(datatype + '\u0000' + rootId); assertEquals(expected, parsed); fiKey = buildFiKey(childId); parsed = TLD.parseRootPointerFromFI(fiKey.getColumnQualifierData()); assertEquals(expected, parsed); fiKey = buildFiKey(grandchildId); parsed = TLD.parseRootPointerFromFI(fiKey.getColumnQualifierData()); assertEquals(expected, parsed); } |
### Question:
TLD { public static ByteSequence parseRootPointerFromId(ByteSequence id) { ArrayList<Integer> dots = instancesOf('.', id); int stop; if (dots.size() > 2) { stop = dots.get(2); } else { stop = id.length(); } return id.subSequence(0, stop); } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testParseRootPointerFromId_String() { assertEquals(rootId, TLD.parseRootPointerFromId(rootId)); assertEquals(rootId, TLD.parseRootPointerFromId(childId)); assertEquals(rootId, TLD.parseRootPointerFromId(grandchildId)); }
@Test public void testParseRootPointerFromId_ByteSequence() { assertEquals(root, TLD.parseRootPointerFromId(root)); assertEquals(root, TLD.parseRootPointerFromId(child)); assertEquals(root, TLD.parseRootPointerFromId(grandchild)); } |
### Question:
TLD { public static ByteSequence estimateRootPointerFromId(ByteSequence id) { if (id.length() > 21) { for (int i = 21; i < id.length(); ++i) { if (id.byteAt(i) == '.') { return id.subSequence(0, i); } } return id.subSequence(0, id.length()); } return parseParentPointerFromId(id); } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testEstimateRootPointerFromId() { ByteSequence root = new ArrayByteSequence(rootId); ByteSequence child = new ArrayByteSequence(childId); ByteSequence grandchild = new ArrayByteSequence(grandchildId); assertEquals(root, TLD.estimateRootPointerFromId(root)); assertEquals(child, TLD.estimateRootPointerFromId(child)); assertEquals(child, TLD.estimateRootPointerFromId(grandchild)); } |
### Question:
TLD { public static boolean isRootPointer(ByteSequence id) { ArrayList<Integer> dots = instancesOf('.', id); return dots.size() <= 2; } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testIsRootPointer() { ByteSequence root = new ArrayByteSequence(rootId); ByteSequence child = new ArrayByteSequence(childId); ByteSequence grandchild = new ArrayByteSequence(grandchildId); assertTrue(TLD.isRootPointer(root)); assertFalse(TLD.isRootPointer(child)); assertFalse(TLD.isRootPointer(grandchild)); } |
### Question:
TLD { public static ByteSequence fromString(String s) { return new ArrayByteSequence(s.getBytes()); } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testFromString() { ByteSequence expected = new ArrayByteSequence(rootId); ByteSequence fromString = TLD.fromString(rootId); assertEquals(expected, fromString); } |
### Question:
TLD { public static ByteSequence parseParentPointerFromId(ByteSequence id) { ArrayList<Integer> dots = instancesOf('.', id); int stop; if (dots.size() > 2) { stop = dots.get(Math.max(2, dots.size() - 2)); } else { stop = id.length(); } return id.subSequence(0, stop); } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testParseParentPointerFromId() { ByteSequence root = new ArrayByteSequence(rootId); ByteSequence child = new ArrayByteSequence(childId); ByteSequence grandchild = new ArrayByteSequence(grandchildId); assertEquals(root, TLD.parseParentPointerFromId(root)); assertEquals(root, TLD.parseParentPointerFromId(child)); assertEquals(root, TLD.parseParentPointerFromId(grandchild)); } |
### Question:
TLD { public static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat) { ArrayList<Integer> positions = Lists.newArrayList(); for (int i = sequence.length() - 1; i >= 0 && positions.size() != repeat; --i) { if (sequence.byteAt(i) == b) { positions.add(i); } } return positions; } private TLD(); static ByteSequence parsePointerFromFI(ByteSequence cq); static ByteSequence parseParentPointerFromId(ByteSequence id); static ByteSequence parseFieldAndValueFromFI(ByteSequence cf, ByteSequence cq); static ByteSequence parseFieldAndValueFromTF(ByteSequence cq); static ByteSequence parseRootPointerFromFI(ByteSequence cq); static ByteSequence parseRootPointerFromId(ByteSequence id); static String parseRootPointerFromId(String id); static ByteSequence estimateRootPointerFromId(ByteSequence id); static boolean isRootPointer(ByteSequence id); static ByteSequence fromString(String s); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence); static ArrayList<Integer> instancesOf(int b, ByteSequence sequence, int repeat); static ArrayList<Integer> lastInstancesOf(int b, ByteSequence sequence, int repeat); static Key buildParentKey(Text shard, ByteSequence id, ByteSequence cq, Text cv, long ts); static Key getNextParentKey(Key docKey); }### Answer:
@Test public void testLastInstancesOf() { ByteSequence bytes = new ArrayByteSequence("how.many.dots.do.we.have?"); ArrayList<Integer> expectedPositions = Lists.newArrayList(19, 16, 13, 8, 3); ArrayList<Integer> instances = TLD.lastInstancesOf('.', bytes, -1); assertEquals(expectedPositions, instances); }
@Test public void testLastInstancesOfWithRepeat() { ByteSequence bytes = new ArrayByteSequence("how.many.dots.do.we.have?"); ArrayList<Integer> expectedPositions = Lists.newArrayList(19, 16, 13); ArrayList<Integer> instances = TLD.lastInstancesOf('.', bytes, 3); assertEquals(expectedPositions, instances); } |
### Question:
RangeStreamScanner extends ScannerSession implements Callable<RangeStreamScanner> { protected String getDay(final Key key) { String myDay = null; byte[] cq = key.getColumnQualifierData().getBackingArray(); if (cq.length >= dateCfLength) { myDay = new String(cq, 0, dateCfLength); if (log.isTraceEnabled()) { log.trace("Day is " + myDay + " for " + key); } } return myDay; } RangeStreamScanner(String tableName, Set<Authorizations> auths, ResourceQueue delegator, int maxResults, Query settings); RangeStreamScanner(String tableName, Set<Authorizations> auths, ResourceQueue delegator, int maxResults, Query settings, SessionOptions options,
Collection<Range> ranges); RangeStreamScanner(ScannerSession other); void setExecutor(ExecutorService service); RangeStreamScanner setScannerFactory(ScannerFactory factory); @Override Range buildNextRange(final Key lastKey, final Range previousRange); @Override boolean hasNext(); RangeStreamScanner setShardsPerDayThreshold(int shardsPerDayThreshold); @Override RangeStreamScanner call(); }### Answer:
@Test public void testGetDay() throws Exception { ScannerFactory scanners = new ScannerFactory(connector, 1); RangeStreamScanner rangeStreamScanner = scanners.newRangeScanner(config.getIndexTableName(), config.getAuthorizations(), config.getQuery(), config.getShardsPerDayThreshold()); Key key = new Key("row".getBytes(), "cf".getBytes(), "20190314".getBytes()); String expectedDay = "20190314"; assertEquals(expectedDay, rangeStreamScanner.getDay(key)); key = new Key("row".getBytes(), "cf".getBytes()); assertNull(rangeStreamScanner.getDay(key)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.