// Loads traffic from file public final void load() { sessionInTraffic = 0; sessionOutTraffic = 0; savedCost = 0; lastTimeUsed = new Date(1); costPerDaySum = 0; savedSince = new Date(); Storage traffic = new Storage("traffic"); try { traffic.open(false); byte[] buf = traffic.getRecord(2); ByteArrayInputStream bais = new ByteArrayInputStream(buf); DataInputStream dis = new DataInputStream(bais); allInTraffic = dis.readInt(); allOutTraffic = dis.readInt(); savedSince.setTime(dis.readLong()); lastTimeUsed.setTime(dis.readLong()); savedCost = dis.readInt(); } catch (Exception e) { savedSince.setTime(new Date().getTime()); allInTraffic = 0; sessionOutTraffic = 0; savedCost = 0; } traffic.close(); }
// Reset the saved value public void reset() { allInTraffic = 0; allOutTraffic = 0; savedCost = 0; savedSince.setTime(new Date().getTime()); try { safeSave(); } catch (Exception e) { // Do nothing } }
// Saves traffic from file private synchronized void save() throws IOException, RecordStoreException { // Open record store Storage traffic = new Storage("traffic"); traffic.open(true); // Add empty records if necessary traffic.initRecords(2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); // Add traffic amount and savedSince to record store dos.writeInt(allInTraffic + sessionInTraffic); dos.writeInt(allOutTraffic + sessionOutTraffic); dos.writeLong(savedSince.getTime()); dos.writeLong(lastTimeUsed.getTime()); generateCostSum(0, 0, false); dos.writeInt(savedCost); traffic.setRecord(2, baos.toByteArray()); traffic.close(); }
// Generates int of money amount spent on connection protected int generateCostSum(int in, int out, boolean thisSession) { int cost = 0; int costOf1M = Options.getInt(Options.OPTION_COST_OF_1M) * 100; int costPacketLength = Math.max(Options.getInt(Options.OPTION_COST_PACKET_LENGTH), 1); long packets = 0; if (0 != in) { packets += (in + costPacketLength - 1) / costPacketLength; } if (0 != out) { packets += (out + costPacketLength - 1) / costPacketLength; } cost += (int) (packets * costPacketLength * costOf1M / (1024 * 1024)); if (!usedToday() && (0 != sessionInTraffic) && (0 == costPerDaySum)) { costPerDaySum = costPerDaySum + Options.getInt(Options.OPTION_COST_PER_DAY); lastTimeUsed.setTime(new Date().getTime()); } return cost + costPerDaySum; }