Skip to content

Commit

Permalink
#22 optimized a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
Yegor Bugayenko committed Nov 20, 2016
1 parent 1f906cc commit 5fc9917
Showing 1 changed file with 34 additions and 15 deletions.
49 changes: 34 additions & 15 deletions src/main/java/io/jare/dynamo/DyUsage.java
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,8 @@ public DyUsage(final Item itm) {

@Override
public void add(final Date date, final long bytes) throws IOException {
if (!this.item.has("usage")) {
this.save("<usage/>");
}
final int day = DyUsage.asNumber(date);
final XML xml = new XMLDocument(this.item.get("usage").getS());
final XML xml = this.xml();
final String xpath = String.format("/usage/day[@id='%d']/text()", day);
final List<String> items = xml.xpath(xpath);
final long before;
Expand All @@ -98,27 +95,23 @@ public void add(final Date date, final long bytes) throws IOException {
)
).remove()
).applyQuietly(node);
this.save(new XMLDocument(node).toString());
this.item.put(
"total",
new AttributeValueUpdate().withValue(
new AttributeValue().withN(
new XMLDocument(node).xpath("sum(/usage/day)").get(0)
)
).withAction(AttributeAction.PUT)
);
final XML after = new XMLDocument(node);
this.save(after.toString());
this.save(Long.parseLong(after.xpath("sum(/usage/day)").get(0)));
}

@Override
public long total() throws IOException {
if (!this.item.has("total")) {
this.save(0L);
}
return Long.parseLong(this.item.get("total").getN());
}

@Override
public SortedMap<Date, Long> history() throws IOException {
final XML xml = new XMLDocument(this.item.get("usage").getS());
final SortedMap<Date, Long> map = new TreeMap<>();
for (final XML day : xml.nodes("/usage/day")) {
for (final XML day : this.xml().nodes("/usage/day")) {
map.put(
DyUsage.asDate(Integer.parseInt(day.xpath("@id").get(0))),
Long.parseLong(day.xpath("text()").get(0))
Expand All @@ -127,6 +120,18 @@ public SortedMap<Date, Long> history() throws IOException {
return map;
}

/**
* Load XML.
* @return The XML with usage
* @throws IOException If fails
*/
private XML xml() throws IOException {
if (!this.item.has("usage")) {
this.save("<usage/>");
}
return new XMLDocument(this.item.get("usage").getS());
}

/**
* Save XML.
* @param xml The XML to save
Expand All @@ -141,6 +146,20 @@ private void save(final String xml) throws IOException {
);
}

/**
* Save total.
* @param total Total usage
* @throws IOException If fails
*/
private void save(final long total) throws IOException {
this.item.put(
"total",
new AttributeValueUpdate()
.withValue(new AttributeValue().withN(Long.toString(total)))
.withAction(AttributeAction.PUT)
);
}

/**
* Convert date to number.
* @param date The date
Expand Down

0 comments on commit 5fc9917

Please sign in to comment.