Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.nhindirect.xd.common;
  
  import java.io.File;
 import java.util.UUID;
 
 
 
 public class XdmPackage {
 
     private String messageId;
     private DirectDocuments documents;
     @Deprecated
     private static final String SUFFIX = ".xml";
     private static final int BUFFER = 2048;
     private static final String XDM_SUB_FOLDER = "SUBSET01/";
     private static final String XDM_METADATA_FILE = "METADATA.xml";
     private static final Log LOGGER = LogFactory.getFactory().getInstance(XdmPackage.class);
 
     public XdmPackage() {
         this(UUID.randomUUID().toString());
     }
 
     public XdmPackage(String messageId) {
         this. = messageId;
         this. = new DirectDocuments();
     }
 
     public void setDocuments(DirectDocuments documents) {
         this. = documents;
     }
 
     public DirectDocuments getDocuments() {
         return this.;
     }
 
     public File toFile() {
         File xdmFile = null;
 
         try {
             xdmFile = new File( + "-xdm.zip");
 
             FileOutputStream dest = new FileOutputStream(xdmFile);
 
             ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(dest));
             zipOutputStream.setMethod(.);
 
             for (DirectDocument2 document : .getDocuments()) {
                 if (document.getData() != null) {
                     addEntry(zipOutputStreamdocument.getData(),  + document.getMetadata().getId() + getSuffix(document.getMetadata().getMimeType()));
                 }
             }
 
             addEntry(zipOutputStream.getSubmitObjectsRequestAsString().getBytes(),  + );
 
             addEntry(zipOutputStreamgetIndex().getBytes(), "INDEX.htm");
 
             addEntry(zipOutputStreamgetReadme().getBytes(), "README.txt");
 
             if (.equals(".xml")) {
                 addEntry(zipOutputStreamgetXsl().getBytes(),  + "CCD.xsl");
             }
 
             zipOutputStream.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
 
         return xdmFile;
     }
 
     private void addEntry(ZipOutputStream zipOutputStreambyte[] dataString fileNamethrows IOException {
         InputStream inputStream = new ByteArrayInputStream(data);
         BufferedInputStream outputStream = new BufferedInputStream(inputStream);
 
         ZipEntry zipEntry = new ZipEntry(fileName);
         zipOutputStream.putNextEntry(zipEntry);
 
         int count = 0;
         byte dataOut[] = new byte[];
         while ((count = outputStream.read(dataOut, 0, )) != -1) {
             zipOutputStream.write(dataOut, 0, count);
        }
    }
    /*
     * Get the index file.
     */
    public String getIndex() throws Exception {
        String data;
        byte[] bytes;
        try {
            bytes = readFile("INDEX_head.txt");
            data = new String(bytes);
            for (DirectDocument2 document : .getDocuments()) {
                if (document.getData() != null) {
                    String file =  + document.getMetadata().getId() + getSuffix(document.getMetadata().getMimeType());
                    data += "<li><a href=\"" + file + "\">" + file + "</a> - " + document.getMetadata().getDescription() + "</li>";
                }
            }
            bytes = readFile("INDEX_tail.txt");
            data += new String(bytes);
        } catch (Exception e) {
            .error("Unable to access index file."e);
            throw e;
        }
        return data;
    }
    /*
     * Get the readme file.
     */
    public String getReadme() throws Exception {
        byte[] bytes;
        try {
            bytes = readFile("README.txt");
        } catch (Exception e) {
            .error("Unable to access readme file."e);
            throw e;
        }
        return new String(bytes);
    }
    /*
     * Get the xsl file.
     */
    public String getXsl() throws Exception {
        byte[] bytes;
        try {
            bytes = readFile("CCD.xsl");
        } catch (Exception e) {
            .error("Unable to access xsl file."e);
            throw e;
        }
        return new String(bytes);
    }
    public static XdmPackage fromXdmZipDataHandler(DataHandler dataHandlerthrows Exception {
        File file = null;
        try {
            // Create a temporary work file
            file = fileFromDataHandler(dataHandler);
        } catch (Exception e) {
            if (.isErrorEnabled()) {
                .error("Error creating temporary work file, unable to complete transformation."e);
            }
            throw new Exception("Error creating temporary work file, unable to complete transformation."e);
        }
        XdmPackage xdmPackage = fromXdmZipFile(file);
        boolean delete = file.delete();
        if (delete) {
            if (.isTraceEnabled()) {
                .trace("Deleted temporary work file " + file.getAbsolutePath());
            }
        } else {
            if (.isWarnEnabled()) {
                .warn("Unable to delete temporary work file " + file.getAbsolutePath());
            }
        }
        return xdmPackage;
    }
    public static XdmPackage fromXdmZipFile(File filethrows Exception {
        DirectDocuments documents = new DirectDocuments();
        ZipFile zipFile = new ZipFile(file.);
        Enumeration<? extends ZipEntryzipEntries = zipFile.entries();
        ZipEntry zipEntry = null;
        // Load metadata
        while (zipEntries.hasMoreElements()) {
            zipEntry = zipEntries.nextElement();
            String zname = zipEntry.getName();
            .info("Processing a ZipEntry named " + zname);
            if (!zipEntry.isDirectory()) {
                String subsetDirspec = getSubmissionSetDirspec(zipEntry.getName());
                // Read metadata
                if (matchName(znamesubsetDirspec)) {
                    ByteArrayOutputStream byteArrayOutputStream = readData(zipFilezipEntry);
                    documents.setValues(byteArrayOutputStream.toString());
                }
            }
        }
        zipEntries = zipFile.entries();
        // load data
        while (zipEntries.hasMoreElements()) {
            .trace("Processing a ZipEntry");
            zipEntry = zipEntries.nextElement();
            String zname = zipEntry.getName();
            if (!zipEntry.isDirectory()) {
                String subsetDirspec = getSubmissionSetDirspec(zipEntry.getName());
                // Read data
                if (StringUtils.contains(subsetDirspec, StringUtils.remove("/"))
                        && !StringUtils.contains(zname".xsl") && !StringUtils.contains(zname)) {
                    ByteArrayOutputStream byteArrayOutputStream = readData(zipFilezipEntry);
                    String digest = DirectDocument2.getSha1Hash(byteArrayOutputStream.toString());
                    ..println(digest);
                    DirectDocument2 document = documents.getDocumentByHash(digest);
                    if (document == null) {
                        .warn("Unable to find metadata for document by hash. Creating document with no supporting metadata.");
                        document = new DirectDocument2();
                        documents.getDocuments().add(document);
                    }
                    document.setData(byteArrayOutputStream.toByteArray());
                }
            }
        }
        zipFile.close();
        XdmPackage xdmPackage = new XdmPackage();
        xdmPackage.setDocuments(documents);
        return xdmPackage;
    }

    
Given a full ZipEntry filespec, extracts the name of the folder (if present) under the IHE_XDM root specified by IHE XDM.

Parameters:
zipEntryName The ZIP entry name.
Returns:
the name of the folder.
    private static String getSubmissionSetDirspec(String zipEntryName) {
        if (zipEntryName == null) {
            return null;
        }
        String[] components = StringUtils.split(zipEntryName"\\/");
        return components[0];
    }

    
Determine whether a filename matches the subset directory and file name.

Parameters:
zname The name to compare.
subsetDirspec The subset directory name.
subsetFilespec The subset file name.
Returns:
true if the names match, false otherwise.
    private static boolean matchName(String znameString subsetDirspecString subsetFilespec) {
        String zipFilespec = subsetDirspec + "\\" + subsetFilespec.replace('/''\\');
        boolean ret = StringUtils.equalsIgnoreCase(znamezipFilespec);
        if (!ret) {
            zipFilespec = zipFilespec.replace('\\''/');
            ret = StringUtils.equalsIgnoreCase(znamezipFilespec);
        }
        return ret;
    }

    
Read data the data of a zipEntry within a zipFile.

Parameters:
zipFile The ZipFile object.
zipEntry The ZipEntry object.
Returns:
a ByteArrayOutputStream representing the data.
Throws:
java.io.IOException
    private static ByteArrayOutputStream readData(ZipFile zipFileZipEntry zipEntrythrows IOException {
        InputStream in = zipFile.getInputStream(zipEntry);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int bytesRead = 0;
        byte[] buffer = new byte[2048];
        while ((bytesRead = in.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        in.close();
        return baos;
    }
    /*
     * Read a file and return the bytes.
     */
    private byte[] readFile(String filenamethrows IOException {
        byte[] bytes;
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(filename);
        bytes = new byte[is.available()];
        is.read(bytes);
        is.close();
        return bytes;
    }
    private static File fileFromDataHandler(DataHandler dhthrows Exception {
        File f = null;
        OutputStream out = null;
        InputStream inputStream = null;
        final String fileName = UUID.randomUUID().toString() + ".zip";
        try {
            f = new File(fileName);
            inputStream = dh.getInputStream();
            out = new FileOutputStream(f);
            byte buf[] = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (FileNotFoundException e) {
            if (.isErrorEnabled()) {
                .error("File not found - " + fileNamee);
            }
            throw e;
        } catch (IOException e) {
            if (.isErrorEnabled()) {
                .error("Exception thrown while trying to read file from DataHandler object"e);
            }
            throw e;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (out != null) {
                out.close();
            }
        }
        if (.isTraceEnabled()) {
            .trace("Created temporary work file " + f.getAbsolutePath());
        }
        return f;
    }
    private String getSuffix(String mimeType) {
        return "." + MimeType.lookup(mimeType).getSuffix();
    }
New to GrepCode? Check out our FAQ X