private List<MessageEntry> readFromFileGuarded() throws IOException, NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, EncryptionException { byte[] bytes = Encryptor.readFromEncryptedFile(encryptionKey, file); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); DataInputStream dis = new DataInputStream(bis); byte version = dis.readByte(); if (version != VERSION) { throw new IOException("Unsupported binary version: " + version); } int entryCount = dis.readInt(); List<MessageEntry> entries = new ArrayList<>(); for (int i = 0; i < entryCount; ++i) { entries.add(new MessageEntry(dis)); } return entries; }
private void writeToFileGuarded() throws IOException, NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, EncryptionException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); dos.writeByte(VERSION); dos.writeInt(messageEntries.size()); for (MessageEntry entry : messageEntries) { entry.writeExternal(dos); } long start = System.currentTimeMillis(); Encryptor.writeToEncryptedFile(encryptionKey, file, bos.toByteArray()); ApptentiveLog.v(MESSAGES, "Messages saved. Took %d ms", System.currentTimeMillis() - start); }
@Override public synchronized void addOrUpdateMessages(ApptentiveMessage... apptentiveMessages) { fetchEntries(); for (ApptentiveMessage apptentiveMessage : apptentiveMessages) { MessageEntry existing = findMessageEntry(apptentiveMessage); if (existing != null) { // Update existing.id = apptentiveMessage.getId(); existing.state = apptentiveMessage.getState().name(); if (apptentiveMessage.isRead()) { // A message can't be unread after being read. existing.isRead = true; } existing.json = apptentiveMessage.getJsonObject().toString(); } else { // Insert MessageEntry entry = new MessageEntry(); entry.id = apptentiveMessage.getId(); entry.clientCreatedAt = apptentiveMessage.getClientCreatedAt(); entry.nonce = apptentiveMessage.getNonce(); entry.state = apptentiveMessage.getState().name(); entry.isRead = apptentiveMessage.isRead(); entry.json = apptentiveMessage.getJsonObject().toString(); messageEntries.add(entry); } } writeToFile(); }
private static List<MessageEntry> readFromLegacyFile(File file) throws IOException { DataInputStream dis = null; try { dis = new DataInputStream(new FileInputStream(file)); byte version = dis.readByte(); if (version != VERSION) { throw new IOException("Unsupported binary version: " + version); } int entryCount = dis.readInt(); List<MessageEntry> entries = new ArrayList<>(); for (int i = 0; i < entryCount; ++i) { entries.add(new MessageEntry(dis)); } return entries; } finally { Util.ensureClosed(dis); } }