001package org.nasdanika.rag.core; 002 003import java.io.ByteArrayOutputStream; 004import java.io.IOException; 005import java.io.InputStream; 006import java.util.Enumeration; 007import java.util.Map.Entry; 008import java.util.zip.ZipEntry; 009import java.util.zip.ZipFile; 010import java.util.zip.ZipInputStream; 011import java.util.zip.ZipOutputStream; 012 013/** 014 * Entry store loaded from and stored to a zip archive. 015 * Value is a zip entry comment - 64 k characters limit. 016 * This class leaves distance computation as well as in-memory storage to subclasses 017 * @param <D> 018 */ 019public abstract class ZipEntryStore<D> extends AbstractEntryStore<byte[], String, D> { 020 021 public ZipEntryStore(ZipInputStream in) throws IOException { 022 try (in) { 023 ZipEntry entry; 024 while ((entry = in.getNextEntry()) != null) { 025 loadEntry(in, entry); 026 } 027 } 028 } 029 030 protected void loadEntry(InputStream in, ZipEntry entry) throws IOException { 031 if (!entry.isDirectory()) { 032 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 033 try (baos) { 034 int b; 035 while ((b = in.read()) != -1) { 036 baos.write(b); 037 } 038 } 039 loadEntry(baos.toByteArray(), getValue(entry)); 040 } 041 } 042 043 public ZipEntryStore(ZipFile in) throws IOException { 044 try (in) { 045 Enumeration<? extends ZipEntry> entries = in.entries(); 046 047 while(entries.hasMoreElements()){ 048 ZipEntry entry = entries.nextElement(); 049 loadEntry(entry.isDirectory() ? null : in.getInputStream(entry) , entry); 050 } 051 } 052 } 053 054 public ZipEntryStore() { 055 056 } 057 058 protected String getValue(ZipEntry entry) { 059 return entry.getName(); 060 } 061 062 protected ZipEntry createZipEntry(byte[] key, String value) { 063 return new ZipEntry(value); 064 } 065 066 protected abstract void loadEntry(byte[] key, String value) throws IOException; 067 068 public void save(ZipOutputStream out) throws IOException { 069 try (out) { 070 for (Entry<byte[], String> entry: getEntries()) { 071 out.putNextEntry(createZipEntry(entry.getKey(), entry.getValue())); 072 out.write(entry.getKey()); 073 out.closeEntry(); 074 } 075 } 076 } 077 078}