target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void toNanosLong1() { Duration duration = TimeDuration.ofSeconds(1.5); assertThat(duration.toNanos(), equalTo(1500000000L)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isPositive1() { Duration duration = TimeDuration.ofSeconds(0); assertThat(!duration.isNegative(), equalTo(true)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isPositive2() { Duration duration = TimeDuration.ofSeconds(1.3); assertThat(!duration.isNegative(), equalTo(true)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isPositive3() { Duration duration = TimeDuration.ofSeconds(0.5); assertThat(!duration.isNegative(), equalTo(true)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isPositive4() { Duration duration = TimeDuration.ofSeconds(5.0); assertThat(!duration.isNegative(), equalTo(true)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void testgetParentNode() { Node parentNode = Node.builder().name("a").uniqueId("u").build(); when(nodeDAO.getParentNode("u")).thenReturn(parentNode); assertNotNull(services.getParentNode("u")); }
@Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); }
Services implements IServices { @Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); } }
Services implements IServices { @Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); } }
Services implements IServices { @Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public Node getParentNode(String uniqueNodeId) { return nodeDAO.getParentNode(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test public void isPositive5() { Duration duration = TimeDuration.ofSeconds(-0.5); assertThat(!duration.isNegative(), equalTo(false)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isPositive6() { Duration duration = TimeDuration.ofSeconds(-5.5); assertThat(!duration.isNegative(), equalTo(false)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isNegative1() { Duration duration = TimeDuration.ofSeconds(0); assertThat(duration.isNegative(), equalTo(false)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isNegative2() { Duration duration = TimeDuration.ofSeconds(1.3); assertThat(duration.isNegative(), equalTo(false)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isNegative3() { Duration duration = TimeDuration.ofSeconds(0.5); assertThat(duration.isNegative(), equalTo(false)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isNegative4() { Duration duration = TimeDuration.ofSeconds(5.0); assertThat(duration.isNegative(), equalTo(false)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isNegative5() { Duration duration = TimeDuration.ofSeconds(-0.5); assertThat(duration.isNegative(), equalTo(true)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void isNegative6() { Duration duration = TimeDuration.ofSeconds(-5.5); assertThat(duration.isNegative(), equalTo(true)); }
public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
TimeDuration { public static Duration ofSeconds(double sec) { return Duration.ofNanos((long) (sec * NANOSEC_IN_SEC)); } private TimeDuration(); static Duration createDuration(long sec, int nanoSec); static Duration ofDays(double day); static Duration ofHours(double hour); static Duration ofMinutes(double min); static Duration ofSeconds(double sec); static Duration ofHertz(double hz); static int dividedBy(Duration dividendDuration, Duration divisorDuration); static double toSecondsDouble(Duration duration); static String toSecondString(Duration duration); }
@Test public void equals1() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0)); assertThat(interval, equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0)))); }
public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void equals2() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 1), Instant.ofEpochSecond(3600, 0)); assertThat(interval, not(equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0))))); }
public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void testGetChildNodes() { when(nodeDAO.getChildNodes("a")).thenReturn(Arrays.asList(Node.builder().build())); assertNotNull(services.getChildNodes("a")); }
@Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); }
Services implements IServices { @Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); } }
Services implements IServices { @Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); } }
Services implements IServices { @Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public List<Node> getChildNodes(String nodeUniqueId) { logger.info("Getting child nodes for node unique id={}", nodeUniqueId); return nodeDAO.getChildNodes(nodeUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test public void equals3() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 1)); assertThat(interval, not(equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), Instant.ofEpochSecond(3600, 0))))); }
public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void equals4() { TimeInterval interval = TimeInterval.between(Instant.ofEpochSecond(0, 0), null); assertThat(interval, equalTo(TimeInterval.between(Instant.ofEpochSecond(0, 0), null))); }
public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void equals5() { TimeInterval interval = TimeInterval.between(null, Instant.ofEpochSecond(0, 0)); assertThat(interval, equalTo(TimeInterval.between(null, Instant.ofEpochSecond(0, 0)))); }
public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
TimeInterval { public static TimeInterval between(Instant start, Instant end) { return new TimeInterval(start, end); } private TimeInterval(Instant start, Instant end); boolean contains(Instant instant); static TimeInterval between(Instant start, Instant end); TimeInterval minus(Duration duration); static TimeInterval around(Duration duration, Instant reference); static TimeInterval after(Duration duration, Instant reference); static TimeInterval before(Duration duration, Instant reference); Instant getStart(); Instant getEnd(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void getNow() { Instant ts = TimeParser.getInstant("now"); assertTrue("Failed to obtain Timestamp corresponding to now ", ts != null && ts instanceof Instant); }
@Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant(); } }
TimeParser { @Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant(); } } }
TimeParser { @Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant(); } } }
TimeParser { @Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant(); } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { @Deprecated public static Instant getInstant(String time) { if (time.equalsIgnoreCase(NOW)) { return Instant.now(); } else { Matcher nUnitsAgoMatcher = timeQuantityUnitsPattern.matcher(time); while (nUnitsAgoMatcher.find()) { return Instant.now().minus(parseDuration(nUnitsAgoMatcher.group(1))); } DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; return LocalDateTime.parse(time, formatter).atZone(TimeZone.getDefault().toZoneId()).toInstant(); } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void getDuration() { Duration lastMin = TimeParser.parseDuration("1 min"); assertEquals("Failed to get Duration for last min", Duration.ofSeconds(60), lastMin); Duration lastHour = TimeParser.parseDuration("1 hour"); assertEquals("Failed to get Duration for last hour", Duration.ofHours(1), lastHour); TemporalAmount last5Min = TimeParser.parseDuration(" 5 mins"); assertEquals("Failed to get Duration for last 5 mins", Duration.ofMinutes(5), last5Min); TemporalAmount last5Hour = TimeParser.parseDuration(" 5 hours"); assertEquals("Failed to get Duration for last 5 hours", Duration.ofHours(5), last5Hour); Duration last5Day = TimeParser.parseDuration(" 5 days"); assertEquals("Failed to get Duration for last 5 days", 60 * 60 * 24 * 5, last5Day.getSeconds()); }
@Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void parse() { Instant now = Instant.now(); TimeRelativeInterval interval = TimeRelativeInterval.of(TimeParser.parseTemporalAmount("1 min"), now); assertEquals(now.minusSeconds(60), interval.toAbsoluteInterval().getStart()); assertEquals(now, interval.toAbsoluteInterval().getEnd()); }
public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void parseCompositeTimeString() { TemporalAmount last5Mins30Secs = TimeParser.parseDuration("5 mins 30 secs"); assertEquals("Failed to get Duration for last 5 mins", Duration.ofMinutes(5).plusSeconds(30), last5Mins30Secs); TemporalAmount last3Hours5Mins30Secs = TimeParser.parseDuration("3 hours 5 mins 30 secs"); assertEquals("Failed to get Duration for last 5 mins", Duration.ofHours(3).plusMinutes(5).plusSeconds(30), last3Hours5Mins30Secs); }
@Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void parseRelativeInterval() { TimeRelativeInterval interval = TimeRelativeInterval.of(TimeParser.parseTemporalAmount("1 month"), LocalDateTime .parse("2011-02-01T00:00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toInstant(ZoneOffset.UTC)); TimeInterval jan = interval.toAbsoluteInterval(); assertEquals(31L, Duration.between(jan.getStart(), jan.getEnd()).toDays()); TimeInterval feb = TimeRelativeInterval .of(TimeParser.parseTemporalAmount("1 month"), LocalDateTime .parse("2011-03-01T00:00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toInstant(ZoneOffset.UTC)) .toAbsoluteInterval(); assertEquals(28L, Duration.between(feb.getStart(), feb.getEnd()).toDays()); TimeInterval leapFeb = TimeRelativeInterval .of(TimeParser.parseTemporalAmount("1 month"), LocalDateTime .parse("2012-03-01T00:00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toInstant(ZoneOffset.UTC)) .toAbsoluteInterval(); assertEquals(29L, Duration.between(leapFeb.getStart(), leapFeb.getEnd()).toDays()); }
public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void testParseDuration() { TemporalAmount amount = TimeParser.parseDuration("3 days"); final long seconds = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC).plus(amount).toEpochSecond(ZoneOffset.UTC); assertEquals(3*24*60*60, seconds); }
@Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { @Deprecated public static Duration parseDuration(String string) { int quantity = 0; String unit = ""; Matcher timeQunatityUnitsMatcher = durationTimeQunatityUnitsPattern.matcher(string); Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); while (timeQunatityUnitsMatcher.find()) { quantity = "".equals(timeQunatityUnitsMatcher.group(1)) ? 1 : Integer.valueOf(timeQunatityUnitsMatcher.group(1)); unit = timeQunatityUnitsMatcher.group(2).toLowerCase(); switch (unit) { case "ms": case "milli": timeQuantities.put(MILLIS, quantity); break; case "s": case "sec": case "secs": timeQuantities.put(SECONDS, quantity); break; case "m": case "min": case "mins": timeQuantities.put(MINUTES, quantity); break; case "h": case "hour": case "hours": timeQuantities.put(HOURS, quantity); break; case "d": case "day": case "days": timeQuantities.put(DAYS, quantity); break; default: break; } } Duration duration = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) { duration = duration.plus(entry.getValue(), entry.getKey()); } return duration; } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void testParseTemporalAmount() { TemporalAmount amount = TimeParser.parseTemporalAmount("3 days"); long seconds = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC).plus(amount).toEpochSecond(ZoneOffset.UTC); assertEquals(3*24*60*60, seconds); amount = TimeParser.parseTemporalAmount("3 days 20 mins 10 sec"); seconds = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC).plus(amount).toEpochSecond(ZoneOffset.UTC); assertEquals(3*24*60*60 + 20*60 + 10, seconds); amount = TimeParser.parseTemporalAmount("now"); seconds = LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC).plus(amount).toEpochSecond(ZoneOffset.UTC); assertEquals(0, seconds); amount = TimeParser.parseTemporalAmount("1 month 1 weeks 3 days 20 mins 10 sec"); assertEquals(amount, Period.of(0, 1, 10)); amount = TimeParser.parseTemporalAmount("1 month 1 day"); assertEquals(amount, Period.of(0, 1, 1)); amount = TimeParser.parseTemporalAmount("1 mo"); assertEquals(amount, Period.of(0, 1, 0)); amount = TimeParser.parseTemporalAmount("month"); assertEquals(amount, Period.of(0, 1, 0)); amount = TimeParser.parseTemporalAmount("60 days"); assertEquals(amount, Duration.ofDays(60)); }
public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { public static TemporalAmount parseTemporalAmount(final String string) { if (NOW.equalsIgnoreCase(string)) return Duration.ZERO; final Matcher timeQuantityUnitsMatcher = timeQuantityUnitsPattern.matcher(string); final Map<ChronoUnit, Integer> timeQuantities = new HashMap<>(); boolean use_period = false; while (timeQuantityUnitsMatcher.find()) { final double quantity = "".equals(timeQuantityUnitsMatcher.group(1)) ? 1.0 : Double.valueOf(timeQuantityUnitsMatcher.group(1)); final int full = (int) quantity; final double fraction = quantity - full; final String unit = timeQuantityUnitsMatcher.group(2).toLowerCase(); if (unit.startsWith("y")) { timeQuantities.put(YEARS, full); if (fraction > 0) { final int next = (int) (fraction * 12 + 0.5); timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mo")) { timeQuantities.compute(MONTHS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 4*7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("w")) { timeQuantities.compute(WEEKS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 7 + 0.5); timeQuantities.compute(DAYS, (u, prev) -> prev == null ? next : prev + next); } use_period = true; } else if (unit.startsWith("mi")) { timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("h")) { timeQuantities.compute(HOURS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 60 + 0.5); timeQuantities.compute(MINUTES, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("d")) { timeQuantities.compute(DAYS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 24 + 0.5); timeQuantities.compute(HOURS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("s")) { timeQuantities.compute(SECONDS, (u, prev) -> prev == null ? full : prev + full); if (fraction > 0) { final int next = (int) (fraction * 1000 + 0.5); timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? next : prev + next); } } else if (unit.startsWith("mi") || unit.equals("ms")) timeQuantities.compute(MILLIS, (u, prev) -> prev == null ? full : prev + full); } if (use_period) { Period result = Period.ZERO; if (timeQuantities.containsKey(YEARS)) result = result.plusYears(timeQuantities.get(YEARS)); if (timeQuantities.containsKey(WEEKS)) result = result.plusDays(7*timeQuantities.get(WEEKS)); if (timeQuantities.containsKey(MONTHS)) result = result.plusMonths(timeQuantities.get(MONTHS)); if (timeQuantities.containsKey(DAYS)) result = result.plusDays(timeQuantities.get(DAYS)); return result; } else { Duration result = Duration.ofSeconds(0); for (Entry<ChronoUnit, Integer> entry : timeQuantities.entrySet()) result = result.plus(entry.getValue(), entry.getKey()); return result; } } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void testGetRootNode() { when(nodeDAO.getRootNode()).thenReturn(Node.builder().build()); assertNotNull(services.getRootNode()); }
@Override public Node getRootNode() { return nodeDAO.getRootNode(); }
Services implements IServices { @Override public Node getRootNode() { return nodeDAO.getRootNode(); } }
Services implements IServices { @Override public Node getRootNode() { return nodeDAO.getRootNode(); } }
Services implements IServices { @Override public Node getRootNode() { return nodeDAO.getRootNode(); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public Node getRootNode() { return nodeDAO.getRootNode(); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test public void testFormatTemporalAmount() { String text = TimeParser.format(Duration.ofHours(2)); assertEquals("2 hours", text); text = TimeParser.format(Period.of(1, 2, 3)); assertEquals("1 year 2 months 3 days", text); text = TimeParser.format(Duration.ofSeconds(2*24*60*60 + 1*60*60 + 10, 123000000L)); assertEquals("2 days 1 hour 10 seconds 123 ms", text); text = TimeParser.format(Duration.ofSeconds(0)); assertEquals("now", text); text = TimeParser.format(Period.ZERO); assertEquals("now", text); }
public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(period.getYears()).append(" years "); if (period.getMonths() == 1) buf.append("1 month "); else if (period.getMonths() > 0) buf.append(period.getMonths()).append(" months "); if (period.getDays() == 1) buf.append("1 day"); else if (period.getDays() > 0) buf.append(period.getDays()).append(" days"); } else { long secs = ((Duration) amount).getSeconds(); if (secs == 0) return NOW; int p = (int) (secs / (24*60*60)); if (p > 0) { if (p == 1) buf.append("1 day "); else buf.append(p).append(" days "); secs -= p * (24*60*60); } p = (int) (secs / (60*60)); if (p > 0) { if (p == 1) buf.append("1 hour "); else buf.append(p).append(" hours "); secs -= p * (60*60); } p = (int) (secs / (60)); if (p > 0) { if (p == 1) buf.append("1 minute "); else buf.append(p).append(" minutes "); secs -= p * (60); } if (secs > 0) if (secs == 1) buf.append("1 second "); else buf.append(secs).append(" seconds "); final int ms = ((Duration)amount).getNano() / 1000000; if (ms > 0) buf.append(ms).append(" ms"); } return buf.toString().trim(); }
TimeParser { public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(period.getYears()).append(" years "); if (period.getMonths() == 1) buf.append("1 month "); else if (period.getMonths() > 0) buf.append(period.getMonths()).append(" months "); if (period.getDays() == 1) buf.append("1 day"); else if (period.getDays() > 0) buf.append(period.getDays()).append(" days"); } else { long secs = ((Duration) amount).getSeconds(); if (secs == 0) return NOW; int p = (int) (secs / (24*60*60)); if (p > 0) { if (p == 1) buf.append("1 day "); else buf.append(p).append(" days "); secs -= p * (24*60*60); } p = (int) (secs / (60*60)); if (p > 0) { if (p == 1) buf.append("1 hour "); else buf.append(p).append(" hours "); secs -= p * (60*60); } p = (int) (secs / (60)); if (p > 0) { if (p == 1) buf.append("1 minute "); else buf.append(p).append(" minutes "); secs -= p * (60); } if (secs > 0) if (secs == 1) buf.append("1 second "); else buf.append(secs).append(" seconds "); final int ms = ((Duration)amount).getNano() / 1000000; if (ms > 0) buf.append(ms).append(" ms"); } return buf.toString().trim(); } }
TimeParser { public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(period.getYears()).append(" years "); if (period.getMonths() == 1) buf.append("1 month "); else if (period.getMonths() > 0) buf.append(period.getMonths()).append(" months "); if (period.getDays() == 1) buf.append("1 day"); else if (period.getDays() > 0) buf.append(period.getDays()).append(" days"); } else { long secs = ((Duration) amount).getSeconds(); if (secs == 0) return NOW; int p = (int) (secs / (24*60*60)); if (p > 0) { if (p == 1) buf.append("1 day "); else buf.append(p).append(" days "); secs -= p * (24*60*60); } p = (int) (secs / (60*60)); if (p > 0) { if (p == 1) buf.append("1 hour "); else buf.append(p).append(" hours "); secs -= p * (60*60); } p = (int) (secs / (60)); if (p > 0) { if (p == 1) buf.append("1 minute "); else buf.append(p).append(" minutes "); secs -= p * (60); } if (secs > 0) if (secs == 1) buf.append("1 second "); else buf.append(secs).append(" seconds "); final int ms = ((Duration)amount).getNano() / 1000000; if (ms > 0) buf.append(ms).append(" ms"); } return buf.toString().trim(); } }
TimeParser { public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(period.getYears()).append(" years "); if (period.getMonths() == 1) buf.append("1 month "); else if (period.getMonths() > 0) buf.append(period.getMonths()).append(" months "); if (period.getDays() == 1) buf.append("1 day"); else if (period.getDays() > 0) buf.append(period.getDays()).append(" days"); } else { long secs = ((Duration) amount).getSeconds(); if (secs == 0) return NOW; int p = (int) (secs / (24*60*60)); if (p > 0) { if (p == 1) buf.append("1 day "); else buf.append(p).append(" days "); secs -= p * (24*60*60); } p = (int) (secs / (60*60)); if (p > 0) { if (p == 1) buf.append("1 hour "); else buf.append(p).append(" hours "); secs -= p * (60*60); } p = (int) (secs / (60)); if (p > 0) { if (p == 1) buf.append("1 minute "); else buf.append(p).append(" minutes "); secs -= p * (60); } if (secs > 0) if (secs == 1) buf.append("1 second "); else buf.append(secs).append(" seconds "); final int ms = ((Duration)amount).getNano() / 1000000; if (ms > 0) buf.append(ms).append(" ms"); } return buf.toString().trim(); } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); }
TimeParser { public static String format(final TemporalAmount amount) { final StringBuilder buf = new StringBuilder(); if (amount instanceof Period) { final Period period = (Period) amount; if (period.isZero()) return NOW; if (period.getYears() == 1) buf.append("1 year "); else if (period.getYears() > 1) buf.append(period.getYears()).append(" years "); if (period.getMonths() == 1) buf.append("1 month "); else if (period.getMonths() > 0) buf.append(period.getMonths()).append(" months "); if (period.getDays() == 1) buf.append("1 day"); else if (period.getDays() > 0) buf.append(period.getDays()).append(" days"); } else { long secs = ((Duration) amount).getSeconds(); if (secs == 0) return NOW; int p = (int) (secs / (24*60*60)); if (p > 0) { if (p == 1) buf.append("1 day "); else buf.append(p).append(" days "); secs -= p * (24*60*60); } p = (int) (secs / (60*60)); if (p > 0) { if (p == 1) buf.append("1 hour "); else buf.append(p).append(" hours "); secs -= p * (60*60); } p = (int) (secs / (60)); if (p > 0) { if (p == 1) buf.append("1 minute "); else buf.append(p).append(" minutes "); secs -= p * (60); } if (secs > 0) if (secs == 1) buf.append("1 second "); else buf.append(secs).append(" seconds "); final int ms = ((Duration)amount).getNano() / 1000000; if (ms > 0) buf.append(ms).append(" ms"); } return buf.toString().trim(); } @Deprecated static Instant getInstant(String time); @Deprecated static TimeInterval getTimeInterval(String time); @Deprecated static Duration parseDuration(String string); static TemporalAmount parseTemporalAmount(final String string); static String format(final TemporalAmount amount); static Object parseInstantOrTemporalAmount(final String text); static final String NOW; }
@Test public void testCommandSplit() throws Exception { List<String> cmd = CommandExecutor.splitCmd("path/cmd"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd"))); cmd = CommandExecutor.splitCmd("path/cmd arg1"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "arg1"))); cmd = CommandExecutor.splitCmd("path/cmd arg1 arg2"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "arg1", "arg2"))); cmd = CommandExecutor.splitCmd("path/cmd \"one arg\""); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "one arg"))); cmd = CommandExecutor.splitCmd("path/cmd \"one arg\" arg2 arg3"); System.out.println(cmd); assertThat(cmd, equalTo(Arrays.asList("path/cmd", "one arg", "arg2", "arg3"))); }
public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(line.toString()); line.delete(0, line.length()); do ++i; while (i < len && (cmd.charAt(i) == ' ' || cmd.charAt(i) == '\t')); } else if (c == '"') { ++i; while (i < len && cmd.charAt(i) != '"') line.append(cmd.charAt(i++)); if (i < len && cmd.charAt(i) == '"') ++i; } else { line.append(c); ++i; } } if (line.length() > 0) items.add(line.toString()); return items; }
CommandExecutor implements Callable<Integer> { public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(line.toString()); line.delete(0, line.length()); do ++i; while (i < len && (cmd.charAt(i) == ' ' || cmd.charAt(i) == '\t')); } else if (c == '"') { ++i; while (i < len && cmd.charAt(i) != '"') line.append(cmd.charAt(i++)); if (i < len && cmd.charAt(i) == '"') ++i; } else { line.append(c); ++i; } } if (line.length() > 0) items.add(line.toString()); return items; } }
CommandExecutor implements Callable<Integer> { public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(line.toString()); line.delete(0, line.length()); do ++i; while (i < len && (cmd.charAt(i) == ' ' || cmd.charAt(i) == '\t')); } else if (c == '"') { ++i; while (i < len && cmd.charAt(i) != '"') line.append(cmd.charAt(i++)); if (i < len && cmd.charAt(i) == '"') ++i; } else { line.append(c); ++i; } } if (line.length() > 0) items.add(line.toString()); return items; } CommandExecutor(final String cmd, final File directory); }
CommandExecutor implements Callable<Integer> { public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(line.toString()); line.delete(0, line.length()); do ++i; while (i < len && (cmd.charAt(i) == ' ' || cmd.charAt(i) == '\t')); } else if (c == '"') { ++i; while (i < len && cmd.charAt(i) != '"') line.append(cmd.charAt(i++)); if (i < len && cmd.charAt(i) == '"') ++i; } else { line.append(c); ++i; } } if (line.length() > 0) items.add(line.toString()); return items; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }
CommandExecutor implements Callable<Integer> { public static List<String> splitCmd(final String cmd) { final List<String> items = new ArrayList<>(); final int len = cmd.length(); int i = 0; final StringBuilder line = new StringBuilder(); while (i < len) { char c = cmd.charAt(i); if (c == ' ' || c == '\t') { items.add(line.toString()); line.delete(0, line.length()); do ++i; while (i < len && (cmd.charAt(i) == ' ' || cmd.charAt(i) == '\t')); } else if (c == '"') { ++i; while (i < len && cmd.charAt(i) != '"') line.append(cmd.charAt(i++)); if (i < len && cmd.charAt(i) == '"') ++i; } else { line.append(c); ++i; } } if (line.length() > 0) items.add(line.toString()); return items; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }
@Test public void testShortCommand() throws Exception { if (is_windows) return; final String cmd = "./cmd_short.sh \"With one arg\" another_arg"; final Integer status = new CommandExecutor(cmd, examples_dir).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Example warning")); assertThat(log, containsString("2 arguments")); assertThat(log, containsString("Finished OK")); assertThat(status, equalTo(0)); }
@Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }
@Test public void testErrorCommand() throws Exception { if (is_windows) return; final Integer status = new CommandExecutor("cmds/cmd_short.sh", examples_dir.getParentFile()).call(); final String log = getLoggedMessages(); assertThat(log, containsString("Wrong directory")); assertThat(log, containsString("exited with status 2")); assertThat(status, equalTo(2)); }
@Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }
CommandExecutor implements Callable<Integer> { @Override public Integer call() throws Exception { String cmd = process_builder.command().get(0); final int sep = cmd.lastIndexOf('/'); if (sep >= 0) cmd = cmd.substring(sep+1); process = process_builder.start(); final Thread stdout = new LogWriter(process.getInputStream(), cmd, Level.INFO); final Thread stderr = new LogWriter(process.getErrorStream(), cmd, Level.WARNING); stdout.start(); stderr.start(); if (process.waitFor(WAIT_SECONDS, TimeUnit.SECONDS)) { stderr.join(); stdout.join(); final int status = process.exitValue(); if (status != 0) logger.log(Level.WARNING, "Command {0} exited with status {1}", new Object[] { process_builder.command(), status }); return status; } return null; } CommandExecutor(final String cmd, final File directory); static List<String> splitCmd(final String cmd); @Override Integer call(); boolean isActive(); @Override String toString(); }
@Test public void checkWebToURI() throws Exception { URI uri = createResourceURI("http: System.out.println(uri); assertThat(uri.getScheme(), equalTo("http")); assertThat(uri.getHost(), equalTo("some.site")); assertThat(uri.getPath(), equalTo("/file/path")); }
public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } }
ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } } }
ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } } }
ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } } static URI createResourceURI(final String resource); static File getFile(final URI resource); static URI getURI(final File file); static InputStream getContent(final URI resource); static List<String> parsePVs(final URI resource); static String getAppName(final URI resource); static String getTargetName(final URI resource); static Stream<Map.Entry<String, String>> getQueryItemStream(final URI resource); static Map<String, List<String>> parseQueryArgs(final URI resource); static String encode(final String text); }
ResourceParser { public static URI createResourceURI(final String resource) throws Exception { try { final URI uri = URI.create(resource); if (uri.getScheme() != null) return uri; else { final Path fileResource = Paths.get(resource); return fileResource.toUri(); } } catch (Throwable ex) { try { return new File(resource).toURI(); } catch (Exception file_ex) { throw new Exception("Cannot create URI for '" + resource + "'", ex); } } } static URI createResourceURI(final String resource); static File getFile(final URI resource); static URI getURI(final File file); static InputStream getContent(final URI resource); static List<String> parsePVs(final URI resource); static String getAppName(final URI resource); static String getTargetName(final URI resource); static Stream<Map.Entry<String, String>> getQueryItemStream(final URI resource); static Map<String, List<String>> parseQueryArgs(final URI resource); static String encode(final String text); static final String PV_SCHEMA; }
@Test public void testSimProposal() { Proposal proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sine"), equalTo("sim: assertThat(proposal.apply("sim: equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2)"), equalTo("sim: assertThat(proposal.apply("sin(-10, 10, 2"), equalTo("sim: proposal = new SimProposal("sim: assertThat(proposal.getDescription(), equalTo("sim: assertThat(proposal.apply("sin(-10,10, 0.1, 2 )"), equalTo("sim: }
public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; }
SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } }
SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } SimProposal(final String name, final String... arguments); }
SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
SimProposal extends Proposal { public SimProposal(final String name, final String... arguments) { super(name); this.arguments = arguments; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testMatch() { Proposal proposal = new SimProposal("sim: List<MatchSegment> match = proposal.getMatch("sine"); assertThat(match, equalTo(List.of(MatchSegment.normal("sim: MatchSegment.match("sine"), MatchSegment.comment("(min, max, update_seconds)")))); match = proposal.getMatch("sim: assertThat(match, equalTo(List.of(MatchSegment.match("sim: MatchSegment.comment("(min, max, update_seconds)")))); match = proposal.getMatch("sine(2, 4,"); System.out.println("sine(2, 4,"); for (MatchSegment m : match) System.out.println(m); assertThat(match, equalTo(List.of(MatchSegment.normal("sim: MatchSegment.match("sine"), MatchSegment.match("(2,", "(min,"), MatchSegment.match(" 4,", "max,"), MatchSegment.comment("update_seconds)")))); match = proposal.getMatch("sim: System.out.println("sim: for (MatchSegment m : match) System.out.println(m); assertThat(match, equalTo(List.of(MatchSegment.match("sim: MatchSegment.match("(-10,", "(min,"), MatchSegment.match(" 10,", "max,"), MatchSegment.match(" 2)", "update_seconds)")))); }
@Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value.indexOf(noparm_text); if (match < 0) segs.add(MatchSegment.normal(value)); else { if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); segs.add(MatchSegment.match(noparm_text)); final int rest = match + noparm_text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); } final int common = Math.min(split.size()-1, arguments.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < arguments.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+1) + another, "(" + arguments[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+1) + another, arguments[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < arguments.length) { if (parm == 0) buf.append('('); for (; parm<arguments.length; ++parm) { buf.append(arguments[parm]); if (parm < arguments.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; }
SimProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value.indexOf(noparm_text); if (match < 0) segs.add(MatchSegment.normal(value)); else { if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); segs.add(MatchSegment.match(noparm_text)); final int rest = match + noparm_text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); } final int common = Math.min(split.size()-1, arguments.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < arguments.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+1) + another, "(" + arguments[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+1) + another, arguments[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < arguments.length) { if (parm == 0) buf.append('('); for (; parm<arguments.length; ++parm) { buf.append(arguments[parm]); if (parm < arguments.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } }
SimProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value.indexOf(noparm_text); if (match < 0) segs.add(MatchSegment.normal(value)); else { if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); segs.add(MatchSegment.match(noparm_text)); final int rest = match + noparm_text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); } final int common = Math.min(split.size()-1, arguments.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < arguments.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+1) + another, "(" + arguments[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+1) + another, arguments[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < arguments.length) { if (parm == 0) buf.append('('); for (; parm<arguments.length; ++parm) { buf.append(arguments[parm]); if (parm < arguments.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } SimProposal(final String name, final String... arguments); }
SimProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value.indexOf(noparm_text); if (match < 0) segs.add(MatchSegment.normal(value)); else { if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); segs.add(MatchSegment.match(noparm_text)); final int rest = match + noparm_text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); } final int common = Math.min(split.size()-1, arguments.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < arguments.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+1) + another, "(" + arguments[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+1) + another, arguments[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < arguments.length) { if (parm == 0) buf.append('('); for (; parm<arguments.length; ++parm) { buf.append(arguments[parm]); if (parm < arguments.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
SimProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final List<String> split = splitNameAndParameters(text); if (split.isEmpty()) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); final String noparm_text = split.get(0); final int match = value.indexOf(noparm_text); if (match < 0) segs.add(MatchSegment.normal(value)); else { if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); segs.add(MatchSegment.match(noparm_text)); final int rest = match + noparm_text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); } final int common = Math.min(split.size()-1, arguments.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < arguments.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+1) + another, "(" + arguments[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+1) + another, arguments[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < arguments.length) { if (parm == 0) buf.append('('); for (; parm<arguments.length; ++parm) { buf.append(arguments[parm]); if (parm < arguments.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } SimProposal(final String name, final String... arguments); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testHistory() { final History history = new History(); List<Proposal> proposals = history.lookup("test"); assertThat(proposals.size(), equalTo(0)); history.add(new Proposal("Test1")); history.add(new Proposal("Other")); history.add(new Proposal("Test2")); proposals = history.lookup("test"); assertThat(getValues(proposals), hasItems("Test1", "Test2")); assertThat(getValues(proposals), equalTo(List.of("Test2", "Test1"))); proposals = history.lookup("ther"); assertThat(getValues(proposals), equalTo(List.of("Other"))); assertThat(proposals.get(0).apply("ther"), equalTo("Other")); }
public History() { this(10); }
History implements ProposalProvider { public History() { this(10); } }
History implements ProposalProvider { public History() { this(10); } History(); History(final int max_size); }
History implements ProposalProvider { public History() { this(10); } History(); History(final int max_size); @Override String getName(); synchronized void add(final Proposal proposal); @Override synchronized List<Proposal> lookup(String text); }
History implements ProposalProvider { public History() { this(10); } History(); History(final int max_size); @Override String getName(); synchronized void add(final Proposal proposal); @Override synchronized List<Proposal> lookup(String text); }
@Test public void testMatch() { Proposal proposal = new FormulaFunctionProposal(new Sin()); List<MatchSegment> match = proposal.getMatch("=sin("); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.comment("", "angle")))); match = proposal.getMatch("=sin(2)"); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.match("2", "angle"), MatchSegment.match(")")))); match = proposal.getMatch("=2 + sin(1-1) + 3"); assertThat(match, equalTo(List.of(MatchSegment.normal("=2 + "), MatchSegment.match("sin"), MatchSegment.match("("), MatchSegment.match("1-1", "angle"), MatchSegment.match(")"), MatchSegment.normal(" + 3")))); }
@Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testVarArg() { Proposal proposal = new FormulaFunctionProposal(new StringFunction()); List<MatchSegment> match = proposal.getMatch("=concat(a, b) + 2"); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("concat"), MatchSegment.match("(a, b)"), MatchSegment.normal(" + 2")))); match = proposal.getMatch("=concat(a, b + 2"); assertThat(match, equalTo(List.of(MatchSegment.normal("="), MatchSegment.match("concat"), MatchSegment.match("(a, b + 2"), MatchSegment.comment(")")))); }
@Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
FormulaFunctionProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { final int match = text.indexOf(function.getName()); if (match < 0) return List.of(MatchSegment.normal(getDescription())); final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(text.substring(0, match))); segs.add(MatchSegment.match(function.getName())); final int len = text.length(); int pos = match + function.getName().length(); if (pos < len && text.charAt(pos) == '(') { if (function.isVarArgs()) { int end = SimProposal.findClosingParenthesis(text, pos); if (end < len) { segs.add(MatchSegment.match(text.substring(pos, end+1))); pos = end+1; } else { segs.add(MatchSegment.match(text.substring(pos, end))); segs.add(MatchSegment.comment(")")); pos = end; } } else { segs.add(MatchSegment.match("(")); ++pos; int end = SimProposal.nextSep(text, pos); for (int i=0; i<function.getArguments().size(); ++i) { if (i > 0) segs.add(MatchSegment.normal(",")); if (pos > 0) { if (end > pos) { segs.add(MatchSegment.match(text.substring(pos, end), function.getArguments().get(i))); if (text.charAt(end) == ')') { segs.add(MatchSegment.match(")")); pos = end + 1; break; } else { pos = end + 1; end = SimProposal.nextSep(text, pos); } } else { segs.add(MatchSegment.comment(text.substring(pos), function.getArguments().get(i))); pos = end = -1; } } else segs.add(MatchSegment.comment(function.getArguments().get(i))); } } } else { for (int i=0; i<function.getArguments().size(); ++i) { if (i == 0) segs.add(MatchSegment.comment("(")); else segs.add(MatchSegment.comment(",")); segs.add(MatchSegment.comment(function.getArguments().get(i))); } segs.add(MatchSegment.comment(")")); } if (pos >= 0 && pos < len) segs.add(MatchSegment.normal(text.substring(pos))); return segs; } FormulaFunctionProposal(final FormulaFunction function); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testGetConfigPvs() { when(nodeDAO.getConfigPvs("a")).thenReturn(Arrays.asList(ConfigPv.builder().build())); assertNotNull(services.getConfigPvs("a")); }
@Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); }
Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } }
Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } }
Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public List<ConfigPv> getConfigPvs(String configUniqueId) { logger.info("Getting config pvs config id id {}", configUniqueId); return nodeDAO.getConfigPvs(configUniqueId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test public void testImplementation() throws Exception { final ScanCommand cmd = new CommentCommand("Test"); final ScanCommandImpl<ScanCommand> impl = ScanCommandImplTool.implement(cmd, null); System.out.println(impl); assertThat(impl, instanceOf(CommentCommandImpl.class)); }
@SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); }
ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); } }
ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); } }
ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); } @SuppressWarnings("unchecked") static ScanCommandImpl<C> implement(final C command, final JythonSupport jython); static List<ScanCommandImpl<?>> implement(final List<ScanCommand> commands, final JythonSupport jython); }
ScanCommandImplTool { @SuppressWarnings("unchecked") public static <C extends ScanCommand> ScanCommandImpl<C> implement(final C command, final JythonSupport jython) throws Exception { for (ScanCommandImplFactory factory : factories) { ScanCommandImpl<?> impl = factory.createImplementation(command, jython); if (impl != null) return (ScanCommandImpl<C>)impl; } throw new Exception("Unknown command " + command.getClass().getName()); } @SuppressWarnings("unchecked") static ScanCommandImpl<C> implement(final C command, final JythonSupport jython); static List<ScanCommandImpl<?>> implement(final List<ScanCommand> commands, final JythonSupport jython); }
@Test public void testPlainProposal() { Proposal proposal = new Proposal("Test1"); assertThat(proposal.apply("est"), equalTo("Test1")); assertThat(proposal.apply("anything"), equalTo("Test1")); }
public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); }
Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } }
Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } Proposal(final String value); }
Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }
Proposal { public String apply(final String text) { final StringBuilder result = new StringBuilder(); final List<MatchSegment> match = getMatch(text); for (MatchSegment seg : match) if (seg.getType() != MatchSegment.Type.COMMENT) result.append(seg.getText()); return result.toString(); } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }
@Test public void testMatch() { Proposal proposal = new Proposal("Test1"); List<MatchSegment> match = proposal.getMatch("es"); assertThat(match, equalTo(List.of(MatchSegment.normal("T"), MatchSegment.match("es"), MatchSegment.normal("t1")))); match = proposal.getMatch("Tes"); assertThat(match, equalTo(List.of(MatchSegment.match("Tes"), MatchSegment.normal("t1")))); }
public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } }
Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } } }
Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } } Proposal(final String value); }
Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }
Proposal { public List<MatchSegment> getMatch(final String text) { final int match = value.indexOf(text); if (match < 0) return List.of(MatchSegment.normal(value)); else { final List<MatchSegment> segs = new ArrayList<>(); if (match > 0) segs.add(MatchSegment.normal(value.substring(0, match))); if (! text.isEmpty()) segs.add(MatchSegment.match(text)); final int rest = match + text.length(); if (value.length() > rest) segs.add(MatchSegment.normal(value.substring(rest))); return segs; } } Proposal(final String value); String getValue(); String getDescription(); List<MatchSegment> getMatch(final String text); String apply(final String text); @Override String toString(); }
@Test public void testArguments() { List<String> split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: split = LocProposal.splitNameTypeAndInitialValues("loc: assertThat(split, equalTo(Arrays.asList("loc: }
static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; }
LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; } }
LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; } LocProposal(final String name, final String type, final String... initial_values); }
LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
LocProposal extends Proposal { static List<String> splitNameTypeAndInitialValues(final String text) { final List<String> result = new ArrayList<>(); int sep = text.indexOf('<'); if (sep >= 0) { result.add(text.substring(0, sep).trim()); int pos = text.indexOf('>', sep+1); if (pos < 0) result.add(text.substring(sep+1).trim()); else { result.add(text.substring(sep+1, pos).trim()); sep = text.indexOf('(', pos); if (sep >= 0) addInitialValues(result, text.substring(sep+1)); } } else { sep = text.indexOf('('); if (sep >= 0) { result.add(text.substring(0, sep).trim()); result.add(null); addInitialValues(result, text.substring(sep+1)); } else { result.add(text.trim()); result.add(null); } } return result; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testLocProposal() { Proposal proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: proposal = new LocProposal("loc: assertThat(proposal.getDescription(), equalTo("loc: }
public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; }
LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } }
LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } LocProposal(final String name, final String type, final String... initial_values); }
LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
LocProposal extends Proposal { public LocProposal(final String name, final String type, final String... initial_values) { super(name); this.type = type; this.initial_values = initial_values; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testMatch() { Proposal proposal = new LocProposal("loc: List<MatchSegment> match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.comment("<VType>"), MatchSegment.comment("(initial value)")))); match = proposal.getMatch(""); assertThat(match, equalTo(List.of( MatchSegment.normal("loc: match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.normal("<Type>"), MatchSegment.comment("(initial value)")))); match = proposal.getMatch("loc: assertThat(match, equalTo(List.of( MatchSegment.match("loc: MatchSegment.comment("<VType>"), MatchSegment.match("(42)", "(initial value)")))); }
@Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); String name = split.get(0).trim(); if (name.equals("loc: { segs.add(MatchSegment.match(name)); segs.add(MatchSegment.normal("name")); } else segs.addAll(super.getMatch(name)); if (split.get(1) == null) segs.add(MatchSegment.comment("<VType>")); else if (type.toLowerCase().indexOf(split.get(1).toLowerCase()) >= 0) segs.add(MatchSegment.match("<" + type + ">")); else segs.add(MatchSegment.normal("<" + type + ">")); final int common = Math.min(split.size()-2, initial_values.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < initial_values.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+2) + another, "(" + initial_values[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+2) + another, initial_values[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < initial_values.length) { if (parm == 0) buf.append('('); for (; parm<initial_values.length; ++parm) { buf.append(initial_values[parm]); if (parm < initial_values.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; }
LocProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); String name = split.get(0).trim(); if (name.equals("loc: { segs.add(MatchSegment.match(name)); segs.add(MatchSegment.normal("name")); } else segs.addAll(super.getMatch(name)); if (split.get(1) == null) segs.add(MatchSegment.comment("<VType>")); else if (type.toLowerCase().indexOf(split.get(1).toLowerCase()) >= 0) segs.add(MatchSegment.match("<" + type + ">")); else segs.add(MatchSegment.normal("<" + type + ">")); final int common = Math.min(split.size()-2, initial_values.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < initial_values.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+2) + another, "(" + initial_values[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+2) + another, initial_values[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < initial_values.length) { if (parm == 0) buf.append('('); for (; parm<initial_values.length; ++parm) { buf.append(initial_values[parm]); if (parm < initial_values.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } }
LocProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); String name = split.get(0).trim(); if (name.equals("loc: { segs.add(MatchSegment.match(name)); segs.add(MatchSegment.normal("name")); } else segs.addAll(super.getMatch(name)); if (split.get(1) == null) segs.add(MatchSegment.comment("<VType>")); else if (type.toLowerCase().indexOf(split.get(1).toLowerCase()) >= 0) segs.add(MatchSegment.match("<" + type + ">")); else segs.add(MatchSegment.normal("<" + type + ">")); final int common = Math.min(split.size()-2, initial_values.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < initial_values.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+2) + another, "(" + initial_values[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+2) + another, initial_values[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < initial_values.length) { if (parm == 0) buf.append('('); for (; parm<initial_values.length; ++parm) { buf.append(initial_values[parm]); if (parm < initial_values.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } LocProposal(final String name, final String type, final String... initial_values); }
LocProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); String name = split.get(0).trim(); if (name.equals("loc: { segs.add(MatchSegment.match(name)); segs.add(MatchSegment.normal("name")); } else segs.addAll(super.getMatch(name)); if (split.get(1) == null) segs.add(MatchSegment.comment("<VType>")); else if (type.toLowerCase().indexOf(split.get(1).toLowerCase()) >= 0) segs.add(MatchSegment.match("<" + type + ">")); else segs.add(MatchSegment.normal("<" + type + ">")); final int common = Math.min(split.size()-2, initial_values.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < initial_values.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+2) + another, "(" + initial_values[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+2) + another, initial_values[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < initial_values.length) { if (parm == 0) buf.append('('); for (; parm<initial_values.length; ++parm) { buf.append(initial_values[parm]); if (parm < initial_values.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
LocProposal extends Proposal { @Override public List<MatchSegment> getMatch(final String text) { if (! text.startsWith("loc")) return List.of(MatchSegment.normal(getDescription())); final List<String> split = splitNameTypeAndInitialValues(text); if (split.size() < 1) return List.of(); final List<MatchSegment> segs = new ArrayList<>(split.size()); String name = split.get(0).trim(); if (name.equals("loc: { segs.add(MatchSegment.match(name)); segs.add(MatchSegment.normal("name")); } else segs.addAll(super.getMatch(name)); if (split.get(1) == null) segs.add(MatchSegment.comment("<VType>")); else if (type.toLowerCase().indexOf(split.get(1).toLowerCase()) >= 0) segs.add(MatchSegment.match("<" + type + ">")); else segs.add(MatchSegment.normal("<" + type + ">")); final int common = Math.min(split.size()-2, initial_values.length); int parm; for (parm = 0; parm < common; ++parm) { final String another = parm < initial_values.length-1 ? "," : ")"; if (parm == 0) segs.add(MatchSegment.match("(" + split.get(parm+2) + another, "(" + initial_values[parm] + another)); else segs.add(MatchSegment.match(split.get(parm+2) + another, initial_values[parm] + another)); } final StringBuilder buf = new StringBuilder(); if (parm < initial_values.length) { if (parm == 0) buf.append('('); for (; parm<initial_values.length; ++parm) { buf.append(initial_values[parm]); if (parm < initial_values.length-1) buf.append(", "); } buf.append(')'); } if (buf.length() > 0) segs.add(MatchSegment.comment(buf.toString())); return segs; } LocProposal(final String name, final String type, final String... initial_values); @Override String getDescription(); @Override List<MatchSegment> getMatch(final String text); }
@Test public void testProperties() { System.out.println(PreferencesReader.replaceProperties("Running on Java $(java.version) in $(java.home)")); System.out.println("Expect warning about undefined property"); assertThat(PreferencesReader.replaceProperties("$(VeryUnlikelyToExist)"), equalTo("$(VeryUnlikelyToExist)")); System.setProperty("test", "OK"); assertThat(PreferencesReader.replaceProperties("$(test)"), equalTo("OK")); assertThat(PreferencesReader.replaceProperties("This is $(test)"), equalTo("This is OK")); }
static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; }
PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; } }
PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; } PreferencesReader(final Class<?> package_class, final String preferences_properties_filename); }
PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; } PreferencesReader(final Class<?> package_class, final String preferences_properties_filename); Set<String> getKeys(final String regex); String get(final String key); boolean getBoolean(final String key); int getInt(final String key); double getDouble(final String key); }
PreferencesReader { static String replaceProperties(final String value) { if (value == null) return value; String result = value; Matcher matcher = PROP_PATTERN.matcher(value); while (matcher.find()) { final String prop_spec = matcher.group(); final String prop_name = prop_spec.substring(2, prop_spec.length()-1); final int start = matcher.start(); final int end = matcher.end(); String prop = System.getProperty(prop_name); if (prop == null) prop = System.getenv(prop_name); if (prop == null) { Logger.getLogger(PreferencesReader.class.getPackageName()) .log(Level.SEVERE, "Reading Preferences: Java system property or Environment variable'" + prop_spec + "' is not defined"); break; } else result = result.substring(0, start) + prop + result.substring(end); matcher = PROP_PATTERN.matcher(result); } return result; } PreferencesReader(final Class<?> package_class, final String preferences_properties_filename); Set<String> getKeys(final String regex); String get(final String key); boolean getBoolean(final String key); int getInt(final String key); double getDouble(final String key); }
@Test(timeout=5000) public void testUpdateThrottle() throws Exception { final Runnable update = new Runnable() { @Override public void run() { System.out.println("<- Update!"); updates.incrementAndGet(); synchronized (this) { notifyAll(); } } }; final UpdateThrottle throttle = new UpdateThrottle(1L, TimeUnit.SECONDS, update); assertThat(updates.get(), equalTo(0)); System.out.println("-> Trigger.."); throttle.trigger(); Thread.sleep(100); assertThat(updates.get(), equalTo(1)); System.out.println("-> Trigger.."); throttle.trigger(); System.out.println("-> Trigger.."); throttle.trigger(); System.out.println("-> Trigger.."); throttle.trigger(); assertThat(updates.get(), equalTo(1)); TimeUnit.SECONDS.sleep(2); assertThat(updates.get(), equalTo(2)); throttle.setDormantTime(500, TimeUnit.MILLISECONDS); throttle.trigger(); TimeUnit.MILLISECONDS.sleep(100); assertThat(updates.get(), equalTo(3)); throttle.trigger(); TimeUnit.MILLISECONDS.sleep(100); assertThat(updates.get(), equalTo(3)); TimeUnit.MILLISECONDS.sleep(500); assertThat(updates.get(), equalTo(4)); }
public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); }
UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } }
UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update); UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update, final ScheduledExecutorService timer); }
UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update); UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update, final ScheduledExecutorService timer); void setDormantTime(final long dormant_time, final TimeUnit unit); void trigger(); void dispose(); }
UpdateThrottle { public UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update) { this(dormant_time, unit, update, TIMER); } UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update); UpdateThrottle(final long dormant_time, final TimeUnit unit, final Runnable update, final ScheduledExecutorService timer); void setDormantTime(final long dormant_time, final TimeUnit unit); void trigger(); void dispose(); static final ScheduledExecutorService TIMER; }
@Test public void testNaNInf() throws Exception { VType number = VDouble.of(Double.NaN, Alarm.none(), Time.now(), display); String text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("NaN V")); number = VDouble.of(Double.POSITIVE_INFINITY, Alarm.none(), Time.now(), display); text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("Infinity V")); number = VDouble.of(Double.NEGATIVE_INFINITY, Alarm.none(), Time.now(), display); text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("-Infinity V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testDecimal() throws Exception { VType number = VDouble.of(3.16, Alarm.none(), Time.now(), display); assertThat(fmt.format(3.16), equalTo("3.16")); String text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("3.160 V")); text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, false); System.out.println(text); assertThat(text, equalTo("3.160")); text = FormatOptionHandler.format(number, FormatOption.DECIMAL, 4, true); System.out.println(text); assertThat(text, equalTo("3.1600 V")); text = FormatOptionHandler.format(number, FormatOption.DECIMAL, 1, true); System.out.println(text); assertThat(text, equalTo("3.2 V")); text = FormatOptionHandler.format(number, FormatOption.DECIMAL, 4, true); System.out.println(text); assertThat(text, equalTo("3.1600 V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testEnum() throws Exception { final VEnum value = VEnum.of(1, EnumDisplay.of("One", "Two"), Alarm.none(), Time.now()); String text = FormatOptionHandler.format(value, FormatOption.DECIMAL, 4, true); System.out.println(text); assertThat(text, equalTo("1")); text = FormatOptionHandler.format(value, FormatOption.DEFAULT, -4, true); System.out.println(text); assertThat(text, equalTo("Two")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testSaveSnapshot() { when(nodeDAO.saveSnapshot("a", Collections.emptyList(), "b", "c", "d")).thenReturn(Node.builder().nodeType(NodeType.SNAPSHOT).build()); assertNotNull(services.saveSnapshot("a", Collections.emptyList(), "b", "d", "c")); }
@Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); }
Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); } }
Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); } }
Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment) { logger.info("Saving snapshot for config id {}", configUniqueId); logger.info("Snapshot name: {}, values:", snapshotName); for (SnapshotItem snapshotItem : snapshotItems) { logger.info(snapshotItem.toString()); } return nodeDAO.saveSnapshot(configUniqueId, snapshotItems, snapshotName, comment, userName); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test public void testExponential() throws Exception { VType number = VDouble.of(3.16, Alarm.none(), Time.now(), display); String text = FormatOptionHandler.format(number, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("3.160 V")); text = FormatOptionHandler.format(number, FormatOption.EXPONENTIAL, 3, true); System.out.println(text); assertThat(text, equalTo("3.160E0 V")); text = FormatOptionHandler.format(number, FormatOption.EXPONENTIAL, 1, true); System.out.println(text); assertThat(text, equalTo("3.2E0 V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testEngineering() throws Exception { VType number = VDouble.of(0.0316, Alarm.none(), Time.now(), display); String text = FormatOptionHandler.format(number, FormatOption.ENGINEERING, 1, true); System.out.println(text); assertThat(text, equalTo("31.6E-3 V")); text = FormatOptionHandler.format(number, FormatOption.ENGINEERING, 3, false); System.out.println(text); assertThat(text, equalTo("31.600E-3")); text = FormatOptionHandler.format(number, FormatOption.ENGINEERING, 4, true); System.out.println(text); assertThat(text, equalTo("31.6000E-3 V")); number = VDouble.of(12345678.0, Alarm.none(), Time.now(), display); text = FormatOptionHandler.format(number, FormatOption.ENGINEERING, 2, true); System.out.println(text); assertThat(text, equalTo("12.35E6 V")); text = FormatOptionHandler.format(number, FormatOption.ENGINEERING, 3, true); System.out.println(text); assertThat(text, equalTo("12.346E6 V")); number = VDouble.of(3.14, Alarm.none(), Time.now(), display); text = FormatOptionHandler.format(number, FormatOption.ENGINEERING, 10, true); System.out.println(text); assertThat(text, equalTo("3.1400000000E0 V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testHexFormat() throws Exception { VType number = VDouble.of(65535.0, Alarm.none(), Time.now(), display); String text = FormatOptionHandler.format(number, FormatOption.HEX, 4, true); System.out.println(text); assertThat(text, equalTo("0xFFFF V")); text = FormatOptionHandler.format(number, FormatOption.HEX, 8, true); System.out.println(text); assertThat(text, equalTo("0x0000FFFF V")); text = FormatOptionHandler.format(number, FormatOption.HEX, 16, true); System.out.println(text); assertThat(text, equalTo("0x000000000000FFFF V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testHexParse() throws Exception { final VType number = VDouble.of(65535.0, Alarm.none(), Time.now(), display); Object parsed = FormatOptionHandler.parse(number, "0xFF", FormatOption.HEX); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), equalTo(255)); parsed = FormatOptionHandler.parse(number, "0x7777", FormatOption.DEFAULT); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), equalTo(30583)); parsed = FormatOptionHandler.parse(number, "0xFFFF", FormatOption.HEX); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), equalTo(65535)); }
public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testString() throws Exception { VType value = VString.of("Test1", Alarm.none(), Time.now()); String text = FormatOptionHandler.format(value, FormatOption.DEFAULT, -1, true); System.out.println(text); assertThat(text, equalTo("Test1")); text = FormatOptionHandler.format(value, FormatOption.STRING, -1, true); System.out.println(text); assertThat(text, equalTo("Test1")); text = FormatOptionHandler.format(value, FormatOption.EXPONENTIAL, -1, true); System.out.println(text); assertThat(text, equalTo("Test1")); value = VDouble.of(65.0, Alarm.none(), Time.now(), display); text = FormatOptionHandler.format(value, FormatOption.STRING, -1, true); System.out.println(text); assertThat(text, equalTo("A V")); ListNumber data = ArrayInteger.of(72, 101, 108, 108, 111); value = VIntArray.of(data, Alarm.none(), Time.now(), display); System.out.println(value); text = FormatOptionHandler.format(value, FormatOption.STRING, -1, true); System.out.println(text); assertThat(text, equalTo("Hello")); data = ArrayInteger.of( 0x24, 0xE2, 0x82, 0xAC); value = VIntArray.of(data, Alarm.none(), Time.now(), display); System.out.println(value); text = FormatOptionHandler.format(value, FormatOption.STRING, -1, true); System.out.println(text); assertThat(text, equalTo("$€")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testCompact() throws Exception { String text = FormatOptionHandler.format(VDouble.of(65.43, Alarm.none(), Time.now(), display), FormatOption.COMPACT, 2, true); System.out.println(text); assertThat(text, equalTo("65.43 V")); text = FormatOptionHandler.format(VDouble.of(0.00006543, Alarm.none(), Time.now(), display), FormatOption.COMPACT, 2, true); System.out.println(text); assertThat(text, equalTo("6.54E-5 V")); text = FormatOptionHandler.format(VDouble.of(65430000.0, Alarm.none(), Time.now(), display), FormatOption.COMPACT, 2, true); System.out.println(text); assertThat(text, equalTo("6.54E7 V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testBinary() throws Exception { String text = FormatOptionHandler.format(VLong.of(0b101010, Alarm.none(), Time.now(), display), FormatOption.BINARY, 10, true); System.out.println(text); assertThat(text, equalTo("0b0000101010 V")); text = FormatOptionHandler.format(VLong.of(0b101010, Alarm.none(), Time.now(), display), FormatOption.BINARY, 0, false); System.out.println(text); assertThat(text, equalTo("0b101010")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testBinaryParse() throws Exception { final VType number = VLong.of(0b101010, Alarm.none(), Time.now(), display); Object parsed = FormatOptionHandler.parse(number, "0b0000101010", FormatOption.BINARY); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), equalTo(42)); parsed = FormatOptionHandler.parse(number, "0b1111111111111111", FormatOption.DEFAULT); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), equalTo(65535)); parsed = FormatOptionHandler.parse(number, "0000101010", FormatOption.BINARY); System.out.println(parsed); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).intValue(), equalTo(42)); }
public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testArray() throws Exception { final ListNumber data = ArrayDouble.of(1.0, 2.0, 3.0, 4.0); VType value = VNumberArray.of(data, Alarm.none(), Time.now(), display); System.out.println(value); String text = FormatOptionHandler.format(value, FormatOption.DEFAULT, 0, true); System.out.println(text); assertThat(text, equalTo("[1, 2, 3, 4] V")); text = FormatOptionHandler.format(value, FormatOption.DECIMAL, 2, true); System.out.println(text); assertThat(text, equalTo("[1.00, 2.00, 3.00, 4.00] V")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testSexagesimalFormat() throws Exception { final VType sexaPositiveValue = VDouble.of(12.5824414, Alarm.none(), Time.now(), display), sexaNegativeValue = VDouble.of(-12.5824414, Alarm.none(), Time.now(), display), sexaRoundedValue = VDouble.of(12.9999999, Alarm.none(), Time.now(), display); assertThat(FormatOptionHandler.format(sexaPositiveValue, FormatOption.SEXAGESIMAL, 7, false), equalTo("12:34:56.789")); assertThat(FormatOptionHandler.format(sexaPositiveValue, FormatOption.SEXAGESIMAL, 2, false), equalTo("12:35")); assertThat(FormatOptionHandler.format(sexaPositiveValue, FormatOption.SEXAGESIMAL, 4, false), equalTo("12:34:57")); assertThat(FormatOptionHandler.format(sexaNegativeValue, FormatOption.SEXAGESIMAL, 7, false), equalTo("-12:34:56.789")); assertThat(FormatOptionHandler.format(sexaRoundedValue, FormatOption.SEXAGESIMAL, 7, false), equalTo("13:00:00.000")); assertThat(FormatOptionHandler.format(sexaRoundedValue, FormatOption.SEXAGESIMAL, 8, false), equalTo("12:59:59.9996")); assertThat(FormatOptionHandler.format(VDouble.of(2*Math.PI, Alarm.none(), Time.now(), display), FormatOption.SEXAGESIMAL_HMS, 7, false), equalTo("24:00:00.000")); assertThat(FormatOptionHandler.format(sexaPositiveValue, FormatOption.SEXAGESIMAL_HMS, 7, false), equalTo("48:03:40.989")); assertThat(FormatOptionHandler.format(sexaNegativeValue, FormatOption.SEXAGESIMAL_HMS, 7, false), equalTo("-48:03:40.989")); assertThat(FormatOptionHandler.format(VDouble.of(2*Math.PI, Alarm.none(), Time.now(), display), FormatOption.SEXAGESIMAL_DMS, 7, false), equalTo("360:00:00.000")); assertThat(FormatOptionHandler.format(sexaPositiveValue, FormatOption.SEXAGESIMAL_DMS, 7, false), equalTo("720:55:14.837")); assertThat(FormatOptionHandler.format(sexaNegativeValue, FormatOption.SEXAGESIMAL_DMS, 7, false), equalTo("-720:55:14.837")); assertThat(FormatOptionHandler.format(sexaRoundedValue, FormatOption.SEXAGESIMAL_DMS, 7, false), equalTo("744:50:42.461")); }
public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static String format(final VType value, final FormatOption option, int precision, final boolean show_units) { precision = actualPrecision(value, precision); if (value == null) return "<null>"; if (value instanceof VNumber) { final VNumber number = (VNumber) value; final String text = formatNumber(number.getValue(), number.getDisplay(), option, precision); if (show_units && !number.getDisplay().getUnit().isEmpty()) return text + " " + number.getDisplay().getUnit(); return text; } else if (value instanceof VString) return ((VString)value).getValue(); else if (value instanceof VEnum) return formatEnum((VEnum) value, option); else if (value instanceof VBoolean) return formatBoolean((VBoolean)value); else if (value instanceof VNumberArray) { final VNumberArray array = (VNumberArray) value; if (option == FormatOption.STRING) return LongString.fromArray(array); final ListNumber data = array.getData(); if (data.size() <= 0) return "[]"; final StringBuilder buf = new StringBuilder("["); buf.append(formatNumber(data.getDouble(0), array.getDisplay(), option, precision)); final int show = Math.min(data.size(), Preferences.max_array_formatting); for (int i=1; i<show; ++i) { buf.append(", "); buf.append(formatNumber(data.getDouble(i), array.getDisplay(), option, precision)); } if (data.size() > show) buf.append(", ..."); buf.append("]"); if (show_units && !array.getDisplay().getUnit().isEmpty()) buf.append(" ").append(array.getDisplay().getUnit()); return buf.toString(); } else if (value instanceof VEnumArray) { final List<String> labels = ((VEnumArray)value).getDisplay().getChoices(); final StringBuilder buf = new StringBuilder("["); for (int i=0; i<labels.size(); ++i) { if (i > 0) buf.append(", "); buf.append(labels.get(i)); } buf.append("]"); return buf.toString(); } else if (value instanceof VStringArray) return StringList.join(((VStringArray)value).getData()); else if (value instanceof VImage) { final VImage image = (VImage) value; return "VImage(" + image.getWidth() + " x " + image.getHeight() + ")"; } else if (value instanceof VTable) return formatTable((VTable) value); return "<" + value.getClass().getName() + ">"; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testGetFromPath(){ Node node = Node.builder().name("SomeFolder").build(); when(nodeDAO.getFromPath("path")).thenReturn(Arrays.asList(node)); assertEquals("SomeFolder", services.getFromPath("path").get(0).getName()); }
@Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); }
Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } }
Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } }
Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public List<Node> getFromPath(String path){ return nodeDAO.getFromPath(path); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test public void testSexagesimalParser() throws Exception { final VType number = VDouble.of(0.0, Alarm.none(), Time.now(), display); assertEquals(12.5824414, (Double)FormatOptionHandler.parse(number, "12:34:56.789", FormatOption.SEXAGESIMAL), 0.0000001); assertEquals(Math.PI, (Double)FormatOptionHandler.parse(number, "12:00:00.000", FormatOption.SEXAGESIMAL_HMS), 0.0000001); assertEquals(12.5824414, (Double)FormatOptionHandler.parse(number, "48:03:40.989", FormatOption.SEXAGESIMAL_HMS), 0.0000001); assertEquals(Math.PI, (Double)FormatOptionHandler.parse(number, "180:00:00.000", FormatOption.SEXAGESIMAL_DMS), 0.0000001); assertEquals(12.5824414, (Double)FormatOptionHandler.parse(number, "720:55:14.837", FormatOption.SEXAGESIMAL_DMS), 0.0000001); }
public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testNumberParsing() throws Exception { VType value = VDouble.of(3.16, Alarm.none(), Time.now(), display); Object parsed = FormatOptionHandler.parse(value, "42.5 Socks", FormatOption.DEFAULT); assertThat(parsed, instanceOf(Number.class)); assertThat(((Number)parsed).doubleValue(), equalTo(42.5)); }
public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void testNumberArrayParsing() throws Exception { final ListNumber data = ArrayDouble.of(1.0, 2.0, 3.0, 4.0); final VType value = VNumberArray.of(data, Alarm.none(), Time.now(), display); Object parsed = FormatOptionHandler.parse(value, " [ 1, 2.5 , 3 ] ", FormatOption.DEFAULT); assertThat(parsed, instanceOf(double[].class)); final double[] numbers = (double[]) parsed; assertThat(numbers, equalTo(new double[] { 1.0, 2.5, 3.0 })); }
public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
FormatOptionHandler { public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0X")) text = text.substring(2); return Long.parseLong(text, 16); } case BINARY: { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); text = text.toUpperCase(); if (text.startsWith("0B")) text = text.substring(2); return Long.parseLong(text, 2); } case SEXAGESIMAL: return SexagesimalFormat.parse(text); case SEXAGESIMAL_HMS: return SexagesimalFormat.parse(text) * Math.PI / 12.0; case SEXAGESIMAL_DMS: return SexagesimalFormat.parse(text) * Math.PI / 180.0; default: if (value instanceof VNumber) { text = text.trim(); final int sep = text.lastIndexOf(' '); if (sep > 0) text = text.substring(0, sep).trim(); if (text.startsWith("0x") || text.startsWith("0X")) { text = text.substring(2).toUpperCase(); return Long.parseLong(text, 16); } if (text.startsWith("0b") || text.startsWith("0B")) { text = text.substring(2); return Long.parseLong(text, 2); } if (value instanceof VDouble) return Double.parseDouble(text); return Long.parseLong(text); } if (value instanceof VEnum) { final List<String> labels = ((VEnum)value).getDisplay().getChoices(); text = text.trim(); for (int i=0; i<labels.size(); ++i) if (labels.get(i).equals(text)) return i; return text; } if (value instanceof VNumberArray) { text = text.trim(); if (text.startsWith("[")) text = text.substring(1); if (text.endsWith("]")) text = text.substring(0, text.length()-1); final String[] items = text.split(" *, *"); final double[] array = new double[items.length]; for (int i=0; i<array.length; ++i) array[i] = Double.parseDouble(items[i].trim()); return array; } if (value instanceof VStringArray) { final List<String> items = StringList.split(text); return items.toArray(new String[items.size()]); } } } catch (Throwable ex) { Logger.getLogger(FormatOptionHandler.class.getPackageName()) .log(Level.WARNING, "Error parsing value from '" + text + "', will use as is", ex); } return text; } static int actualPrecision(final VType value, int precision); static String format(final VType value, final FormatOption option, int precision, final boolean show_units); static Object parse(final VType value, String text, final FormatOption format); }
@Test public void compute(){ ArrayScalarDivisionFunction arrayScalarDivisionFunction = new ArrayScalarDivisionFunction(); assertEquals("arrayDivScalar", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayScalarDivisionFunction.compute(array, factor); assertEquals(3, result.getData().size()); assertEquals(1, result.getData().getInt(0)); assertEquals(5, result.getData().getInt(1)); assertEquals(15, result.getData().getInt(2)); result = (VNumberArray)arrayScalarDivisionFunction.compute(array, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array1 = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; return VNumberArray.of( ListMath.rescale(array1.getData(), 1d / factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { ArrayMinFunction arrayMinFunction = new ArrayMinFunction(); assertEquals("arrayMin", arrayMinFunction.getName()); assertEquals("array", arrayMinFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(-1.0, 0, 1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Display.none()); VDouble min = (VDouble) arrayMinFunction.compute(doubleArray); assertEquals("arrayMin Failed to calculate min for double array", Double.valueOf(-1.0), min.getValue()); VNumberArray intArray = VNumberArray.of(ArrayInteger.of(-1, 0, 1, 2, 3, 4, 5), Alarm.none(), Time.now(), Display.none()); min = (VDouble) arrayMinFunction.compute(intArray); assertEquals("arrayMin Failed to calculate min for int array", Double.valueOf(-1), min.getValue()); }
@Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayMinFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMin(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void computeString() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VStringArray.of(List.of("a", "b", "c")); VString vString = (VString) elementAtNumberFunction.compute(array, index); assertEquals("c", vString.getValue()); vString = (VString)elementAtNumberFunction.compute(array, array); assertEquals("", vString.getValue()); }
@Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test(expected = Exception.class) public void invalidArguments1() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(8.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); elementAtNumberFunction.compute(array, index); }
@Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test(expected = Exception.class) public void invalidArguments2() throws Exception{ ElementAtNumberFunction elementAtNumberFunction = new ElementAtNumberFunction(); VType index = VDouble.of(-1.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); elementAtNumberFunction.compute(array, index); }
@Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ElementAtNumberFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { boolean isStringArray = args[0] instanceof VStringArray; if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray numberArray = (VNumberArray)args[0]; int index = ((VNumber)args[1]).getValue().intValue(); if(index < 0 || index > numberArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VDouble.of(numberArray.getData().getDouble(index), Alarm.none(), Time.now(), Display.none()); } else if(isStringArray && args[1] instanceof VNumber){ VStringArray stringArray = (VStringArray)args[0]; int index = ((VDouble)args[1]).getValue().intValue(); if(index < 0 || index > stringArray.getData().size() - 1){ throw new Exception(String.format("Array index %d invalid", index)); } return VString.of(stringArray.getData().get(index), stringArray.getAlarm(), stringArray.getTime()); } else{ return isStringArray ? DEFAULT_EMPTY_STRING : DEFAULT_NAN_DOUBLE; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { ArrayOfFunction arrayOfFunction = new ArrayOfFunction(); assertEquals("arrayOf", arrayOfFunction.getName()); assertEquals("array", arrayOfFunction.getCategory()); VString a = VString.of("a", Alarm.none(), Time.now()); VString b = VString.of("b", Alarm.none(), Time.now()); VString c = VString.of("c", Alarm.none(), Time.now()); VStringArray vStringArray = (VStringArray)arrayOfFunction.compute(a, b, c); assertEquals(3, vStringArray.getData().size()); assertEquals("a", vStringArray.getData().get(0)); assertEquals("b", vStringArray.getData().get(1)); assertEquals("c", vStringArray.getData().get(2)); VInt d0 = VInt.of(1, Alarm.none(), Time.now(), Display.none()); VInt d1 = VInt.of(2, Alarm.none(), Time.now(), Display.none()); VInt d2 = VInt.of(3, Alarm.none(), Time.now(), Display.none()); VNumberArray vNumberArray = (VNumberArray)arrayOfFunction.compute(d0, d1, d2); assertEquals(3, vNumberArray.getData().size()); assertEquals(1, vNumberArray.getData().getInt(0)); assertEquals(2, vNumberArray.getData().getInt(1)); assertEquals(3, vNumberArray.getData().getInt(2)); VEnum vEnum = VEnum.of(0, EnumDisplay.of(), Alarm.none(), Time.now()); vNumberArray = (VNumberArray)arrayOfFunction.compute(vEnum); assertTrue(Double.valueOf(vNumberArray.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
ArrayOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VString){ List<String> data = new ArrayList<>(); for (Object arg : args) { if(arg == null){ data.add(null); } else { data.add(((VString)arg).getValue()); } } return VStringArray.of(data, Alarm.none(), Time.now()); } else if(args[0] instanceof VNumber){ List<VNumber> elements = Arrays.asList(args).stream().map(arg -> (VNumber)arg).collect(Collectors.toList()); ListDouble data = new ListDouble() { @Override public double getDouble(int index) { VNumber number = elements.get(index); if (number == null || number.getValue() == null) return Double.NaN; else return number.getValue().doubleValue(); } @Override public int size() { return elements.size(); } }; return VNumberArray.of(data, Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@Test public void compute() throws Exception{ ArrayDivisionFunction arrayDivisionFunction = new ArrayDivisionFunction(); assertEquals("arrayDiv", arrayDivisionFunction.getName()); assertEquals("array", arrayDivisionFunction.getCategory()); VType array1 = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 30.0), Alarm.none(), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 5.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayDivisionFunction.compute(array1, array2); assertEquals(3, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(5, result.getData().getInt(1)); assertEquals(6, result.getData().getInt(2)); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); result = (VNumberArray)arrayDivisionFunction.compute(array1, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void testGetFullPath(){ when(nodeDAO.getFullPath("nodeId")).thenReturn("/a/b/c"); assertEquals("/a/b/c", nodeDAO.getFullPath("nodeId")); }
@Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); }
Services implements IServices { @Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); } }
Services implements IServices { @Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); } }
Services implements IServices { @Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
Services implements IServices { @Override public String getFullPath(String uniqueNodeId){ return nodeDAO.getFullPath(uniqueNodeId); } @Override Node getParentNode(String uniqueNodeId); @Override List<Node> getSnapshots(String configUniqueId); @Override Node getSnapshot(String snapshotUniqueId); @Override Node createNode(String parentsUniqueId, Node node); @Override @Transactional Node moveNode(String nodeId, String targetNodeId, String userName); @Override @Transactional void deleteNode(String nodeId); @Override @Transactional Node updateConfiguration(Node configToUpdate, List<ConfigPv> configPvs); @Override Node updateNode(Node nodeToUpdate); @Override Node updateNode(Node nodeToUpdate, boolean customTimeForMigration); @Override Node getNode(String nodeId); @Override List<Node> getChildNodes(String nodeUniqueId); @Override Node getRootNode(); @Override List<ConfigPv> getConfigPvs(String configUniqueId); @Override List<SnapshotItem> getSnapshotItems(String snapshotUniqueId); @Override Node saveSnapshot(String configUniqueId, List<SnapshotItem> snapshotItems, String snapshotName, String userName, String comment); @Override List<Tag> getTags(String snapshotUniqueId); @Override List<Tag> getAllTags(); @Override List<Node> getFromPath(String path); @Override String getFullPath(String uniqueNodeId); }
@Test(expected = Exception.class) public void testWrongArguments() throws Exception{ ArrayDivisionFunction arrayDivisionFunction = new ArrayDivisionFunction(); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0), Alarm.none(), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.none(), Time.now(), Display.none()); arrayDivisionFunction.compute(array1, array2); }
@Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(VTypeHelper.isNumericArray(args[0]) && VTypeHelper.isNumericArray(args[1])){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.divide(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { ArrayMaxFunction arrayMaxFunction = new ArrayMaxFunction(); assertEquals("arrayMax", arrayMaxFunction.getName()); assertEquals("array", arrayMaxFunction.getCategory()); VNumberArray doubleArray = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0, 4.0, 5), Alarm.none(), Time.now(), Display.none()); VDouble max = (VDouble) arrayMaxFunction.compute(doubleArray); assertEquals("arrayMax Failed to calculate max for double array", Double.valueOf(5), max.getValue()); VNumberArray intArray = VNumberArray.of(ArrayInteger.of(1, 2, 3, 4, 5), Alarm.none(), Time.now(), Display.none()); max = (VDouble) arrayMaxFunction.compute(intArray); assertEquals("arrayMax Failed to calculate max for int array", Double.valueOf(5), max.getValue()); }
@Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayMaxFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMaxFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMaxFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayMaxFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { return VDouble.of(Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics().getMax(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() throws Exception{ ArrayMultiplicationFunction arrayMultiplicationFunction = new ArrayMultiplicationFunction(); assertEquals("arrayMult", arrayMultiplicationFunction.getName()); assertEquals("array", arrayMultiplicationFunction.getCategory()); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.of(AlarmSeverity.MINOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayMultiplicationFunction.compute(array1, array2); assertEquals(3, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(10, result.getData().getInt(1)); assertEquals(21, result.getData().getInt(2)); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); result = (VNumberArray)arrayMultiplicationFunction.compute(array1, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test(expected = Exception.class) public void testWrongArguments() throws Exception{ ArrayMultiplicationFunction arrayMultiplicationFunction = new ArrayMultiplicationFunction(); VType array1 = VNumberArray.of(ArrayDouble.of(1.0, 2.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType array2 = VNumberArray.of(ArrayDouble.of(2.0, 5.0, 7.0), Alarm.of(AlarmSeverity.MINOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); arrayMultiplicationFunction.compute(array1, array2); }
@Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayMultiplicationFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { if(args[0] instanceof VNumberArray && args[1] instanceof VNumberArray){ VNumberArray array1 = (VNumberArray)args[0]; VNumberArray array2 = (VNumberArray)args[1]; if(array1.getData().size() != array2.getData().size()){ throw new Exception(String.format("Function %s cannot compute as specified arrays are of different length", getName())); } return VNumberArray.of( ListMath.multiply(array1.getData(), array2.getData()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { ArrayRangeOfFunction arrayRangeOfFunction = new ArrayRangeOfFunction(); assertEquals("arrayRangeOf", arrayRangeOfFunction.getName()); assertEquals("array", arrayRangeOfFunction.getCategory()); Display display = Display.of(Range.of(1d, 10d), Range.of(10d, 20d), Range.of(20d, 30d), Range.of(30d, 40d), "N", new DecimalFormat("")); VNumberArray numberArray = VNumberArray.of(ArrayDouble.of(1d, 2d), Alarm.none(), Time.now(), display); VNumberArray range = (VNumberArray)arrayRangeOfFunction.compute(numberArray); assertEquals(1, range.getData().getInt(0)); assertEquals(10, range.getData().getInt(1)); }
@Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayRangeOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayRangeOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayRangeOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayRangeOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumberArray){ VNumberArray array = (VNumberArray)args[0]; Range range = array.getDisplay().getDisplayRange(); double min = range.getMinimum(); double max = range.getMaximum(); return VNumberArray.of( ArrayDouble.of(min, max), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); assertEquals("scale", scaleArray.getName()); assertEquals("array", scaleArray.getCategory()); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VType offset = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)scaleArray.compute(array, factor, offset); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 3); assertTrue(result.getData().getDouble(1) == 5); assertTrue(result.getData().getDouble(2) == 7); result = (VNumberArray)scaleArray.compute(array, factor); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 2); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 6); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 2); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 6); result = (VNumberArray)scaleArray.compute(factor, factor, offset); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@Test(expected = Exception.class) public void testWrongNnumberOfArgumenst1() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); VType factor = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VType offset = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); scaleArray.compute(array, factor, offset, offset); }
@Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@Test(expected = Exception.class) public void testWrongNnumberOfArgumenst2() throws Exception{ ScaleArrayFormulaFunction scaleArray = new ScaleArrayFormulaFunction(); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); scaleArray.compute(array); }
@Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
ScaleArrayFormulaFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception{ if(args.length != 2 && args.length != 3){ throw new Exception(String.format("Function %s takes 2 or 3 aruments, got %d", getName(), args.length)); } if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; VNumber factor = (VNumber) args[1]; double offset = args.length == 3 ? ((VNumber)args[2]).getValue().doubleValue() : 0.0; return VNumberArray.of( ListMath.rescale(array.getData(), factor.getValue().doubleValue(), offset), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@Test public void compute() { ArrayStatsFunction arrayStatsFunction = new ArrayStatsFunction(); assertEquals("arrayStats", arrayStatsFunction.getName()); assertEquals("array", arrayStatsFunction.getCategory()); VNumberArray numberArray = VNumberArray.of(ArrayDouble.of(1d, 2d), Alarm.none(), Time.now(), Display.none()); VStatistics stats = (VStatistics) arrayStatsFunction.compute(numberArray); assertEquals("arrayStats Failed to calculate min", Double.valueOf(1), stats.getMin()); assertEquals("arrayStats Failed to calculate max", Double.valueOf(2), stats.getMax()); }
@Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayStatsFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayStatsFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayStatsFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayStatsFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { DoubleSummaryStatistics stats = Arrays.stream(VTypeHelper.toDoubles(args[0])).summaryStatistics(); return VStatistics.of(stats.getAverage(), Double.NaN, stats.getMin(), stats.getMax(), (int) stats.getCount(), Alarm.none(), Time.now(), Display.none()); } else { return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { ArraySumFunction scaleArrayFunction = new ArraySumFunction(); assertEquals("arraySum", scaleArrayFunction.getName()); assertEquals("array", scaleArrayFunction.getCategory()); VType offset = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)scaleArrayFunction.compute(array, offset); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 3); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 5); result = (VNumberArray)scaleArrayFunction.compute(offset, offset); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); result = (VNumberArray)scaleArrayFunction.compute(offset, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArraySumFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArraySumFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArraySumFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArraySumFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber offset = (VNumber)args[1]; return VNumberArray.of( ListMath.rescale(array.getData(), 1, offset.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void testGetDataType() { VByte vByte = VByte.of(new Byte((byte) 1), alarm, time, display); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vByte)); VUByte vUByte = VUByte.of(new UByte((byte) 1), alarm, time, display); assertEquals(SnapshotPvDataType.UBYTE, SnapshotDataConverter.getDataType(vUByte)); VShort vShort = VShort.of(new Short((short) 1), alarm, time, display); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vShort)); VUShort vUShort = VUShort.of(new UShort((short) 1), alarm, time, display); assertEquals(SnapshotPvDataType.USHORT, SnapshotDataConverter.getDataType(vUShort)); VInt vInt = VInt.of(new Integer(1), alarm, time, display); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vInt)); VUInt vUInt = VUInt.of(new UInteger(1), alarm, time, display); assertEquals(SnapshotPvDataType.UINTEGER, SnapshotDataConverter.getDataType(vUInt)); VLong vLong = VLong.of(new Long(1), alarm, time, display); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vLong)); VULong vULong = VULong.of(new ULong(1), alarm, time, display); assertEquals(SnapshotPvDataType.ULONG, SnapshotDataConverter.getDataType(vULong)); VFloat vFloat = VFloat.of(new Float(1.1), alarm, time, display); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vFloat)); VDouble vDouble = VDouble.of(new Double(1), alarm, time, display); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vDouble)); VString vString = VString.of("string", alarm, time); assertEquals(SnapshotPvDataType.STRING, SnapshotDataConverter.getDataType(vString)); VEnum vEnum = VEnum.of(0, EnumDisplay.of("choice1"), alarm, time); assertEquals(SnapshotPvDataType.ENUM, SnapshotDataConverter.getDataType(vEnum)); VByteArray vByteArray = VByteArray.of(new ArrayByte(CollectionNumbers.toListByte((byte) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vByteArray)); VNumberArray vNumberArray = VNumberArray.of(CollectionNumbers.toList(new byte[] { (byte) 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vNumberArray)); ListByte listByte = new ListByte() { @Override public int size() { return 1; } @Override public byte getByte(int index) { return (byte) 1; } }; vByteArray = VByteArray.of(listByte, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.BYTE, SnapshotDataConverter.getDataType(vByteArray)); VUByteArray vUByteArray = VUByteArray.of(new ArrayUByte(CollectionNumbers.toListUByte((byte) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.UBYTE, SnapshotDataConverter.getDataType(vUByteArray)); ListUByte listUByte = new ListUByte() { @Override public int size() { return 1; } @Override public byte getByte(int index) { return (byte) 1; } }; vUByteArray = VUByteArray.of(listUByte, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.UBYTE, SnapshotDataConverter.getDataType(vUByteArray)); VShortArray vShortArray = VShortArray.of(new ArrayShort(CollectionNumbers.toListShort((short) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vShortArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new short[] { (short) 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vNumberArray)); ListShort listShort = new ListShort() { @Override public int size() { return 1; } @Override public short getShort(int index) { return (short) 1; } }; vShortArray = VShortArray.of(listShort, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.SHORT, SnapshotDataConverter.getDataType(vShortArray)); VUShortArray vUShortArray = VUShortArray.of(new ArrayUShort(CollectionNumbers.toListUShort((short) 1)), alarm, time, display); assertEquals(SnapshotPvDataType.USHORT, SnapshotDataConverter.getDataType(vUShortArray)); ListUShort listUShort = new ListUShort() { @Override public int size() { return 1; } @Override public short getShort(int index) { return (short) 1; } }; vUShortArray = VUShortArray.of(listUShort, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.USHORT, SnapshotDataConverter.getDataType(vUShortArray)); VIntArray vIntArray = VIntArray.of(new ArrayInteger(CollectionNumbers.toListInt(1)), alarm, time, display); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vIntArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new int[] { 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vNumberArray)); ListInteger listInteger = new ListInteger() { @Override public int size() { return 1; } @Override public int getInt(int index) { return 1; } }; vIntArray = VIntArray.of(listInteger, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.INTEGER, SnapshotDataConverter.getDataType(vIntArray)); VUIntArray vUIntArray = VUIntArray.of(new ArrayUInteger(CollectionNumbers.toListUInt(1)), alarm, time, display); assertEquals(SnapshotPvDataType.UINTEGER, SnapshotDataConverter.getDataType(vUIntArray)); ListUInteger listUInteger = new ListUInteger() { @Override public int size() { return 1; } @Override public int getInt(int index) { return 1; } }; vUIntArray = VUIntArray.of(listUInteger, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.UINTEGER, SnapshotDataConverter.getDataType(vUIntArray)); VLongArray vLongArray = VLongArray.of(new ArrayLong(CollectionNumbers.toListLong(1L)), alarm, time, display); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vLongArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new long[] { 1 }), alarm, time, display); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vNumberArray)); ListLong listLong = new ListLong() { @Override public int size() { return 1; } @Override public long getLong(int index) { return 1L; } }; vLongArray = VLongArray.of(listLong, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.LONG, SnapshotDataConverter.getDataType(vLongArray)); VULongArray vULongArray = VULongArray.of(new ArrayULong(CollectionNumbers.toListULong(1L)), alarm, time, display); assertEquals(SnapshotPvDataType.ULONG, SnapshotDataConverter.getDataType(vULongArray)); ListULong listULong = new ListULong() { @Override public int size() { return 1; } @Override public long getLong(int index) { return 1L; } }; vULongArray = VULongArray.of(listULong, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.ULONG, SnapshotDataConverter.getDataType(vULongArray)); VFloatArray vFloatArray = VFloatArray.of(new ArrayFloat(CollectionNumbers.toListFloat(1.1f)), alarm, time, display); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vFloatArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new float[] { 1.1f }), alarm, time, display); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vNumberArray)); ListFloat listFloat = new ListFloat() { @Override public int size() { return 1; } @Override public float getFloat(int index) { return 1.1f; } }; vFloatArray = VFloatArray.of(listFloat, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.FLOAT, SnapshotDataConverter.getDataType(vFloatArray)); VDoubleArray vDoubleArray = VDoubleArray.of(new ArrayDouble(CollectionNumbers.toListDouble(1.1)), alarm, time, display); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vDoubleArray)); vNumberArray = VNumberArray.of(CollectionNumbers.toList(new double[] { 1.1 }), alarm, time, display); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vNumberArray)); ListDouble listDouble = new ListDouble() { @Override public int size() { return 1; } @Override public double getDouble(int index) { return 1.1; } }; vDoubleArray = VDoubleArray.of(listDouble, alarm, time, Display.none()); assertEquals(SnapshotPvDataType.DOUBLE, SnapshotDataConverter.getDataType(vDoubleArray)); }
protected static SnapshotPvDataType getDataType(VType vType) { if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Class<?> clazz = vNumber.getValue().getClass(); if(clazz.equals(Byte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(UByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(Short.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(UShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(Integer.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(UInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(Long.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(Float.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(Double.class)){ return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumber.getValue().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Class<?> clazz = vNumberArray.getData().getClass(); if(clazz.equals(ArrayByte.class) || clazz.getSuperclass().equals(ListByte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(ArrayUByte.class) || clazz.getSuperclass().equals(ListUByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(ArrayShort.class) || clazz.getSuperclass().equals(ListShort.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(ArrayUShort.class) || clazz.getSuperclass().equals(ListUShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(ArrayInteger.class) || clazz.getSuperclass().equals(ListInteger.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(ArrayUInteger.class) || clazz.getSuperclass().equals(ListUInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(ArrayLong.class) || clazz.getSuperclass().equals(ListLong.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ArrayULong.class) || clazz.getSuperclass().equals(ListULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(ArrayFloat.class) || clazz.getSuperclass().equals(ListFloat.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(ArrayDouble.class) || clazz.getSuperclass().equals(ListDouble.class)) { return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumberArray.getData().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VString) { return SnapshotPvDataType.STRING; } else if(vType instanceof VEnum){ return SnapshotPvDataType.ENUM; } else if(vType instanceof VStringArray){ return SnapshotPvDataType.STRING; } throw new PVConversionException(String.format("Unable to perform data conversion on type %s", vType.getClass().getCanonicalName())); }
SnapshotDataConverter { protected static SnapshotPvDataType getDataType(VType vType) { if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Class<?> clazz = vNumber.getValue().getClass(); if(clazz.equals(Byte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(UByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(Short.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(UShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(Integer.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(UInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(Long.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(Float.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(Double.class)){ return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumber.getValue().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Class<?> clazz = vNumberArray.getData().getClass(); if(clazz.equals(ArrayByte.class) || clazz.getSuperclass().equals(ListByte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(ArrayUByte.class) || clazz.getSuperclass().equals(ListUByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(ArrayShort.class) || clazz.getSuperclass().equals(ListShort.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(ArrayUShort.class) || clazz.getSuperclass().equals(ListUShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(ArrayInteger.class) || clazz.getSuperclass().equals(ListInteger.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(ArrayUInteger.class) || clazz.getSuperclass().equals(ListUInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(ArrayLong.class) || clazz.getSuperclass().equals(ListLong.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ArrayULong.class) || clazz.getSuperclass().equals(ListULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(ArrayFloat.class) || clazz.getSuperclass().equals(ListFloat.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(ArrayDouble.class) || clazz.getSuperclass().equals(ListDouble.class)) { return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumberArray.getData().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VString) { return SnapshotPvDataType.STRING; } else if(vType instanceof VEnum){ return SnapshotPvDataType.ENUM; } else if(vType instanceof VStringArray){ return SnapshotPvDataType.STRING; } throw new PVConversionException(String.format("Unable to perform data conversion on type %s", vType.getClass().getCanonicalName())); } }
SnapshotDataConverter { protected static SnapshotPvDataType getDataType(VType vType) { if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Class<?> clazz = vNumber.getValue().getClass(); if(clazz.equals(Byte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(UByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(Short.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(UShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(Integer.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(UInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(Long.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(Float.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(Double.class)){ return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumber.getValue().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Class<?> clazz = vNumberArray.getData().getClass(); if(clazz.equals(ArrayByte.class) || clazz.getSuperclass().equals(ListByte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(ArrayUByte.class) || clazz.getSuperclass().equals(ListUByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(ArrayShort.class) || clazz.getSuperclass().equals(ListShort.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(ArrayUShort.class) || clazz.getSuperclass().equals(ListUShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(ArrayInteger.class) || clazz.getSuperclass().equals(ListInteger.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(ArrayUInteger.class) || clazz.getSuperclass().equals(ListUInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(ArrayLong.class) || clazz.getSuperclass().equals(ListLong.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ArrayULong.class) || clazz.getSuperclass().equals(ListULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(ArrayFloat.class) || clazz.getSuperclass().equals(ListFloat.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(ArrayDouble.class) || clazz.getSuperclass().equals(ListDouble.class)) { return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumberArray.getData().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VString) { return SnapshotPvDataType.STRING; } else if(vType instanceof VEnum){ return SnapshotPvDataType.ENUM; } else if(vType instanceof VStringArray){ return SnapshotPvDataType.STRING; } throw new PVConversionException(String.format("Unable to perform data conversion on type %s", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); }
SnapshotDataConverter { protected static SnapshotPvDataType getDataType(VType vType) { if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Class<?> clazz = vNumber.getValue().getClass(); if(clazz.equals(Byte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(UByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(Short.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(UShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(Integer.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(UInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(Long.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(Float.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(Double.class)){ return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumber.getValue().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Class<?> clazz = vNumberArray.getData().getClass(); if(clazz.equals(ArrayByte.class) || clazz.getSuperclass().equals(ListByte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(ArrayUByte.class) || clazz.getSuperclass().equals(ListUByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(ArrayShort.class) || clazz.getSuperclass().equals(ListShort.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(ArrayUShort.class) || clazz.getSuperclass().equals(ListUShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(ArrayInteger.class) || clazz.getSuperclass().equals(ListInteger.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(ArrayUInteger.class) || clazz.getSuperclass().equals(ListUInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(ArrayLong.class) || clazz.getSuperclass().equals(ListLong.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ArrayULong.class) || clazz.getSuperclass().equals(ListULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(ArrayFloat.class) || clazz.getSuperclass().equals(ListFloat.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(ArrayDouble.class) || clazz.getSuperclass().equals(ListDouble.class)) { return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumberArray.getData().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VString) { return SnapshotPvDataType.STRING; } else if(vType instanceof VEnum){ return SnapshotPvDataType.ENUM; } else if(vType instanceof VStringArray){ return SnapshotPvDataType.STRING; } throw new PVConversionException(String.format("Unable to perform data conversion on type %s", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
SnapshotDataConverter { protected static SnapshotPvDataType getDataType(VType vType) { if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Class<?> clazz = vNumber.getValue().getClass(); if(clazz.equals(Byte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(UByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(Short.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(UShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(Integer.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(UInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(Long.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(Float.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(Double.class)){ return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumber.getValue().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Class<?> clazz = vNumberArray.getData().getClass(); if(clazz.equals(ArrayByte.class) || clazz.getSuperclass().equals(ListByte.class)) { return SnapshotPvDataType.BYTE; } else if(clazz.equals(ArrayUByte.class) || clazz.getSuperclass().equals(ListUByte.class)) { return SnapshotPvDataType.UBYTE; } else if(clazz.equals(ArrayShort.class) || clazz.getSuperclass().equals(ListShort.class)) { return SnapshotPvDataType.SHORT; } else if(clazz.equals(ArrayUShort.class) || clazz.getSuperclass().equals(ListUShort.class)) { return SnapshotPvDataType.USHORT; } else if(clazz.equals(ArrayInteger.class) || clazz.getSuperclass().equals(ListInteger.class)) { return SnapshotPvDataType.INTEGER; } else if(clazz.equals(ArrayUInteger.class) || clazz.getSuperclass().equals(ListUInteger.class)) { return SnapshotPvDataType.UINTEGER; } else if(clazz.equals(ArrayLong.class) || clazz.getSuperclass().equals(ListLong.class)) { return SnapshotPvDataType.LONG; } else if(clazz.equals(ArrayULong.class) || clazz.getSuperclass().equals(ListULong.class)) { return SnapshotPvDataType.ULONG; } else if(clazz.equals(ArrayFloat.class) || clazz.getSuperclass().equals(ListFloat.class)) { return SnapshotPvDataType.FLOAT; } else if(clazz.equals(ArrayDouble.class) || clazz.getSuperclass().equals(ListDouble.class)) { return SnapshotPvDataType.DOUBLE; } throw new PVConversionException("Data class " + vNumberArray.getData().getClass().getCanonicalName() + " not supported"); } else if(vType instanceof VString) { return SnapshotPvDataType.STRING; } else if(vType instanceof VEnum){ return SnapshotPvDataType.ENUM; } else if(vType instanceof VStringArray){ return SnapshotPvDataType.STRING; } throw new PVConversionException(String.format("Unable to perform data conversion on type %s", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@Test public void compute() { ArrayInverseScalarDivisionFunction arrayScalarDivisionFunction = new ArrayInverseScalarDivisionFunction(); assertEquals("arrayDivScalarInv", arrayScalarDivisionFunction.getName()); assertEquals("array", arrayScalarDivisionFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(2.0, 10.0, 20.0), Alarm.of(AlarmSeverity.MAJOR, AlarmStatus.NONE, ""), Time.now(), Display.none()); VType factor = VDouble.of(100.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayScalarDivisionFunction.compute(factor, array); assertEquals(3, result.getData().size()); assertEquals(50, result.getData().getInt(0)); assertEquals(10, result.getData().getInt(1)); assertEquals(5, result.getData().getInt(2)); result = (VNumberArray)arrayScalarDivisionFunction.compute(array, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayInverseScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayInverseScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayInverseScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayInverseScalarDivisionFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(args[0] instanceof VNumber && VTypeHelper.isNumericArray(args[1])){ VNumberArray array = (VNumberArray)args[1]; VNumber factor = (VNumber) args[0]; return VNumberArray.of( ListMath.inverseRescale(array.getData(), factor.getValue().doubleValue(), 0), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { ArrayPowFunction arrayPowFunction = new ArrayPowFunction(); assertEquals("arrayPow", arrayPowFunction.getName()); assertEquals("array", arrayPowFunction.getCategory()); VType exponent = VDouble.of(2.0, Alarm.none(), Time.now(), Display.none()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0), Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)arrayPowFunction.compute(array, exponent); assertEquals(3, result.getData().size()); assertTrue(result.getData().getDouble(0) == 1); assertTrue(result.getData().getDouble(1) == 4); assertTrue(result.getData().getDouble(2) == 9); result = (VNumberArray)arrayPowFunction.compute(exponent, exponent); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); result = (VNumberArray)arrayPowFunction.compute(exponent, array); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
ArrayPowFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayPowFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
ArrayPowFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
ArrayPowFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if(VTypeHelper.isNumericArray(args[0]) && args[1] instanceof VNumber){ VNumberArray array = (VNumberArray)args[0]; VNumber exponent = (VNumber)args[1]; return VNumberArray.of( ListMath.pow(array.getData(), exponent.getValue().doubleValue()), Alarm.none(), Time.now(), Display.none()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void compute() { HistogramOfFunction function = new HistogramOfFunction(); assertEquals("histogramOf", function.getName()); assertEquals("array", function.getCategory()); double[] data = new double[1000]; for(int i = 0; i < 1000; i++){ data[i] = 1.0 * i; } VDoubleArray vDoubleArray = VDoubleArray.of(ArrayDouble.of(data), Alarm.none(), Time.now(), Display.none()); VNumberArray vNumberArray = (VNumberArray)function.compute(vDoubleArray); assertEquals(100, vNumberArray.getData().size()); assertEquals(10, vNumberArray.getData().getInt(0)); assertEquals(10, (int)vNumberArray.getDisplay().getDisplayRange().getMaximum()); VNumber vNumber = VInt.of(200, Alarm.none(), Time.now(), Display.none()); vNumberArray = (VNumberArray)function.compute(vDoubleArray, vNumber); assertEquals(200, vNumberArray.getData().size()); assertEquals(5, vNumberArray.getData().getInt(0)); assertEquals(5, (int)vNumberArray.getDisplay().getDisplayRange().getMaximum()); vNumberArray = (VNumberArray)function.compute(vNumber); assertTrue(Double.valueOf(vNumberArray.getData().getDouble(0)).equals(Double.NaN)); }
@Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } }
HistogramOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } } }
HistogramOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } } }
HistogramOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
HistogramOfFunction extends BaseArrayFunction { @Override public VType compute(VType... args) { if (VTypeHelper.isNumericArray(args[0])) { VNumberArray numberArray = (VNumberArray) args[0]; if (numberArray == null) { return null; } VNumberArray previousValue = null; VNumberArray previousResult = null; Range previousXRange = null; if (previousValue == numberArray) { return previousResult; } Statistics stats = StatisticsUtil.statisticsOf(numberArray.getData()); int nBins = args.length == 1 ? 100 : ((VNumber) args[1]).getValue().intValue(); Range aggregatedRange = aggregateRange(stats.getRange(), previousXRange); Range xRange; if (Ranges.overlap(aggregatedRange, stats.getRange()) >= 0.75) { xRange = aggregatedRange; } else { xRange = stats.getRange(); } IteratorNumber newValues = numberArray.getData().iterator(); double previousMaxCount = Double.MIN_VALUE; int[] binData = new int[nBins]; double maxCount = 0; while (newValues.hasNext()) { double value = newValues.nextDouble(); if (xRange.contains(value)) { int bin = (int) Math.floor(xRange.normalize(value) * nBins); if (bin == nBins) { bin--; } binData[bin]++; if (binData[bin] > maxCount) { maxCount = binData[bin]; } } } if (previousMaxCount > maxCount && previousMaxCount < maxCount * 2.0) { maxCount = previousMaxCount; } Display display = Display.of(Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), Range.of(0.0, maxCount), "count", NumberFormats.precisionFormat(0)); return VNumberArray.of(ArrayInteger.of(binData), Alarm.none(), Time.now(), display); } else { return BaseArrayFunction.DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override boolean isVarArgs(); @Override VType compute(VType... args); }
@Test public void compute() throws Exception{ SubArrayFunction subArrayFunction = new SubArrayFunction(); assertEquals("subArray", subArrayFunction.getName()); assertEquals("array", subArrayFunction.getCategory()); VType array = VNumberArray.of(ArrayDouble.of(1.0, 2.0, 3.0, 4.0, 5.0), Alarm.none(), Time.now(), Display.none()); VType from = VDouble.of(1.0, Alarm.none(), Time.now(), Display.none()); VType to = VDouble.of(3.0, Alarm.none(), Time.now(), Display.none()); VNumberArray result = (VNumberArray)subArrayFunction.compute(array, from, to); assertEquals(2, result.getData().size()); assertEquals(2, result.getData().getInt(0)); assertEquals(3, result.getData().getInt(1)); result = (VNumberArray)subArrayFunction.compute(from, from, to); assertTrue(Double.valueOf(result.getData().getDouble(0)).equals(Double.NaN)); VStringArray stringArray = VStringArray.of(List.of("a", "b", "c", "d", "e")); VStringArray stringResult = (VStringArray) subArrayFunction.compute(stringArray, from, to); assertEquals(2, stringResult.getData().size()); assertEquals("b", stringResult.getData().get(0)); assertEquals("c", stringResult.getData().get(1)); }
@Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } }
SubArrayFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
SubArrayFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } }
SubArrayFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
SubArrayFunction extends BaseArrayFunction { @Override public VType compute(VType... args) throws Exception { VNumber fromIndex = (VNumber) args[1]; VNumber toIndex = (VNumber) args[2]; if(VTypeHelper.isNumericArray(args[0])){ VNumberArray array = (VNumberArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VNumberArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now(), Display.none()); } else if(args[0] instanceof VStringArray){ VStringArray array = (VStringArray)args[0]; if(fromIndex.getValue().intValue() < 0 || (fromIndex.getValue().intValue() > toIndex.getValue().intValue()) || (toIndex.getValue().intValue() - fromIndex.getValue().intValue() > array.getData().size())){ throw new Exception("Limits for sub array invalid"); } return VStringArray.of( array.getData().subList(fromIndex.getValue().intValue(), toIndex.getValue().intValue()), Alarm.none(), Time.now()); } else{ return DEFAULT_NAN_DOUBLE_ARRAY; } } @Override String getName(); @Override String getDescription(); @Override List<String> getArguments(); @Override VType compute(VType... args); }
@Test public void testEmpty() throws Exception { FieldRequest request = new FieldRequest(""); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); }
public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
@Test public void testPlainFields() throws Exception { FieldRequest request = new FieldRequest("field(proton_charge,pixel)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); }
public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
@Test public void testSubFields() throws Exception { FieldRequest request = new FieldRequest("field(value, timeStamp.userTag)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); request = new FieldRequest("field(proton_charge,pixel,timeStamp.userTag)"); System.out.println(request); buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); PVATypeRegistry registry = new PVATypeRegistry(); final PVAData decoded = registry.decodeType("", buffer); System.out.println(decoded.formatType()); }
public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
@Test public void testPipeline() throws Exception { FieldRequest request = new FieldRequest(10, "field(value)"); System.out.println(request); ByteBuffer buffer = encode(request); System.out.println(Hexdump.toHexdump(buffer)); }
public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
FieldRequest { public void encode(final ByteBuffer buffer) throws Exception { desc.encode(buffer); } FieldRequest(final String request); FieldRequest(final int pipeline, final String request); void encodeType(final ByteBuffer buffer); void encode(final ByteBuffer buffer); @Override String toString(); }
@Test public void testToDouble(){ VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleValue); assertEquals(7.7, result, 0); VString stringValue = VString.of("7.7", Alarm.none(), Time.now()); result = VTypeHelper.toDouble(doubleValue); assertEquals(7.7, result, 0); stringValue = VString.of("NotANumber", Alarm.none(), Time.now()); result = VTypeHelper.toDouble(stringValue); assertEquals(Double.NaN, result, 0); VEnum enumValue = VEnum.of(7, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); result = VTypeHelper.toDouble(enumValue); assertEquals(7.0, result, 0); VStatistics statisticsValue = VStatistics.of(7.7, 0.1, 0.0, 10.0, 5, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDouble(statisticsValue); assertEquals(7.7, result, 0); VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDouble(doubleArray); assertEquals(7.7, result, 0); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); result = VTypeHelper.toDouble(enumArray); assertEquals(0.0, result, 0); VBoolean booleanValue = VBoolean.of(true, Alarm.none(), Time.now()); assertEquals(1.0, VTypeHelper.toDouble(booleanValue), 0); booleanValue = VBoolean.of(false, Alarm.none(), Time.now()); assertEquals(0.0, VTypeHelper.toDouble(booleanValue), 0); }
final public static double toDouble(final VType value) { return toDouble(value, 0); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
@Test public void testArrayToDoubleWithValidIndex(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleArray, 0); assertEquals(7.7, result, 0); result = VTypeHelper.toDouble(doubleArray, 1); assertEquals(8.8, result, 0); VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); result = VTypeHelper.toDouble(enumArray); assertEquals(0.0, result, 0); assertEquals(1.0, result, 1); VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDouble(doubleValue, 0); assertEquals(7.7, result, 0); }
final public static double toDouble(final VType value) { return toDouble(value, 0); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
@Test(expected = RuntimeException.class) public void testUnsupportedType() { VEnumArray vEnumArray = VEnumArray.of(ArrayInteger.of(1, 2, 3), EnumDisplay.of("a", "b", "c"), Alarm.none(), Time.now()); SnapshotDataConverter.fromVType(vEnumArray); }
public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); }
SnapshotDataConverter { public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); } }
SnapshotDataConverter { public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); }
SnapshotDataConverter { public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
SnapshotDataConverter { public static SnapshotPv fromVType(VType vType) { SnapshotPvDataType dataType = getDataType(vType); if(vType instanceof VNumber) { VNumber vNumber = (VNumber)vType; Alarm alarm = vNumber.getAlarm(); Instant instant = vNumber.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vNumber.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VNumberArray) { VNumberArray vNumberArray = (VNumberArray)vType; Alarm alarm = vNumberArray.getAlarm(); Instant instant = vNumberArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getNumberArrayValueString(vNumberArray)) .dataType(dataType) .sizes(getDimensionString(vNumberArray)) .build(); } else if(vType instanceof VString){ VString vString = (VString)vType; Alarm alarm = vString.getAlarm(); Instant instant = vString.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getScalarValueString(vString.getValue())) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } else if(vType instanceof VStringArray){ VStringArray vStringArray = (VStringArray) vType; Alarm alarm = vStringArray.getAlarm(); Instant instant = vStringArray.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getStringArrayValueString(vStringArray)) .dataType(dataType) .sizes(getDimensionString(vStringArray)) .build(); } else if(vType instanceof VEnum){ VEnum vEnum = (VEnum)vType; Alarm alarm = vEnum.getAlarm(); Instant instant = vEnum.getTime().getTimestamp(); return SnapshotPv.builder() .alarmSeverity(alarm.getSeverity()) .alarmName(alarm.getName()) .alarmStatus(alarm.getStatus()) .time(instant.getEpochSecond()) .timens(instant.getNano()) .value(getEnumValueString(vEnum)) .dataType(dataType) .sizes(SCALAR_AS_JSON) .build(); } throw new PVConversionException(String.format("VType \"%s\" not supported", vType.getClass().getCanonicalName())); } private SnapshotDataConverter(); static SnapshotItem fromSnapshotPv(SnapshotPv snapshotPv, SnapshotPv readback); static SnapshotPv fromVType(VType vType); static VType toVType(SnapshotPv snapshotPv); }
@Test public void testArrayToDoubleWithInvalidIndex1(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleArray, 7); assertEquals(result, Double.NaN, 0); }
final public static double toDouble(final VType value) { return toDouble(value, 0); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
@Test public void testArrayToDoubleWithInvalidIndex2(){ VEnumArray enumArray = VEnumArray.of(ArrayInteger.of(0, 1), EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); double result = VTypeHelper.toDouble(enumArray, 7); assertEquals(result, Double.NaN, 0); }
final public static double toDouble(final VType value) { return toDouble(value, 0); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
@Test public void testArrayToDoubleWithInvalidIndex3(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double result = VTypeHelper.toDouble(doubleArray, -1); assertEquals(result, Double.NaN, 0); }
final public static double toDouble(final VType value) { return toDouble(value, 0); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { final public static double toDouble(final VType value) { return toDouble(value, 0); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
@Test public void testToDoubles(){ VDoubleArray doubleArray = VDoubleArray.of(ArrayDouble.of(7.7, 8.8), Alarm.none(), Time.now(), Display.none()); double[] result = VTypeHelper.toDoubles(doubleArray); assertEquals(2, result.length); assertEquals(7.7, result[0], 0); assertEquals(8.8, result[1], 0); VDouble doubleValue = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); result = VTypeHelper.toDoubles(doubleValue); assertEquals(0, result.length); }
public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; }
VTypeHelper { public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; } }
VTypeHelper { public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; } }
VTypeHelper { public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { public static double[] toDoubles(final VType value) { final double[] array; if (value instanceof VNumberArray) { final ListNumber list = ((VNumberArray) value).getData(); array = new double[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.getDouble(i); } } else array = new double[0]; return array; } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
@Test public void testGetString(){ assertEquals("null", VTypeHelper.toString(null)); VTable table = VTable.of(Arrays.asList(VDouble.class), Arrays.asList("name"), Arrays.asList(ArrayDouble.of(7.7))); assertNotNull(VTypeHelper.toString(table)); VDouble vDouble = VDouble.of(7.7, Alarm.disconnected(), Time.now(), Display.none()); assertNull(VTypeHelper.toString(vDouble)); vDouble = VDouble.of(7.7, Alarm.none(), Time.now(), Display.none()); assertEquals("7.7", VTypeHelper.toString(vDouble)); VEnum enumValue = VEnum.of(0, EnumDisplay.of("a", "b"), Alarm.none(), Time.now()); assertEquals("a", VTypeHelper.toString(enumValue)); assertEquals("b", VTypeHelper.toString(VString.of("b", Alarm.none(), Time.now()))); }
public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VString) { return ((VString) value).getValue(); } return value.toString(); }
VTypeHelper { public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VString) { return ((VString) value).getValue(); } return value.toString(); } }
VTypeHelper { public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VString) { return ((VString) value).getValue(); } return value.toString(); } }
VTypeHelper { public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VString) { return ((VString) value).getValue(); } return value.toString(); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }
VTypeHelper { public static String toString(final VType value) { if (value == null) { return "null"; } if (isDisconnected(value)) { return null; } if (value instanceof VNumber) { return ((VNumber) value).getValue().toString(); } if (value instanceof VEnum) { return ((VEnum) value).getValue(); } if (value instanceof VString) { return ((VString) value).getValue(); } return value.toString(); } final static double toDouble(final VType value); static double[] toDoubles(final VType value); static String toString(final VType value); static double toDouble(final VType value, final int index); static boolean isNumericArray(final VType value); static int getArraySize(final VType value); static Alarm highestAlarmOf(final VType a, VType b); static Time lastestTimeOf(final VType a, final VType b); final static Instant getTimestamp(final VType value); static VType transformTimestamp(final VType value, final Instant time); static VType transformTimestampToNow(final VType value); static boolean isDisconnected(final VType value); static AlarmSeverity getSeverity(final VType value); static String formatArray(Array array, int maxElements); }