Example usage for java.util.zip ZipInputStream read

List of usage examples for java.util.zip ZipInputStream read

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream read.

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads from the current ZIP entry into an array of bytes.

Usage

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

/**
 * //  w  w w.java 2  s. c  om
 * @param zip_file
 * @param directory
 */
public void extractZipFiles(String zip_file, String directory) {
    byte[] data = new byte[BUFFER];
    String name, path, zipDir;
    ZipEntry entry;
    ZipInputStream zipstream;

    if (!(directory.charAt(directory.length() - 1) == '/'))
        directory += "/";

    if (zip_file.contains("/")) {
        path = zip_file;
        name = path.substring(path.lastIndexOf("/") + 1, path.length() - 4);
        zipDir = directory + name + "/";

    } else {
        path = directory + zip_file;
        name = path.substring(path.lastIndexOf("/") + 1, path.length() - 4);
        zipDir = directory + name + "/";
    }

    new File(zipDir).mkdir();

    try {
        zipstream = new ZipInputStream(new FileInputStream(path));

        while ((entry = zipstream.getNextEntry()) != null) {
            String buildDir = zipDir;
            String[] dirs = entry.getName().split("/");

            if (dirs != null && dirs.length > 0) {
                for (int i = 0; i < dirs.length - 1; i++) {
                    buildDir += dirs[i] + "/";
                    new File(buildDir).mkdir();
                }
            }

            int read = 0;
            FileOutputStream out = new FileOutputStream(zipDir + entry.getName());
            while ((read = zipstream.read(data, 0, BUFFER)) != -1)
                out.write(data, 0, read);

            zipstream.closeEntry();
            out.close();
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.squirrel_sql.client.update.UpdateUtilImpl.java

/**
 * TODO: Move this to IOUtilities Extracts the specified zip file to the specified output directory.
 * /*w w w .  j av  a 2  s  .c  o m*/
 * @param zipFile
 * @param outputDirectory
 * @throws IOException
 */
public void extractZipFile(FileWrapper zipFile, FileWrapper outputDirectory) throws IOException {
    if (!outputDirectory.isDirectory()) {
        s_log.error("Output directory specified (" + outputDirectory.getAbsolutePath()
                + ") doesn't appear to be a directory");
        return;
    }
    FileInputStream fis = null;
    ZipInputStream zis = null;
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(zipFile.getAbsolutePath());
        zis = new ZipInputStream(fis);
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            String name = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                checkDir(outputDirectory, name);
            } else {
                FileWrapper newFile = _fileWrapperFactory.create(outputDirectory, name);
                if (newFile.exists()) {
                    if (s_log.isInfoEnabled()) {
                        s_log.info("Deleting extraction file that already exists:" + newFile.getAbsolutePath());
                    }
                    newFile.delete();
                }
                fos = new FileOutputStream(newFile.getAbsolutePath());
                byte[] buffer = new byte[ZIP_EXTRACTION_BUFFER_SIZE];
                int n = 0;
                while ((n = zis.read(buffer, 0, ZIP_EXTRACTION_BUFFER_SIZE)) > -1) {
                    fos.write(buffer, 0, n);
                }
                fos.close();
            }
            zipEntry = zis.getNextEntry();
        }
    } finally {
        _iou.closeOutputStream(fos);
        _iou.closeInputStream(fis);
        _iou.closeInputStream(zis);
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private void unzipFile(File file) {
    String zipFileFullPath = file.getPath();// path contains file name
    String zipFilePath = zipFileFullPath.substring(0, zipFileFullPath.indexOf(file.getName()));// path without file
                                                                                               // name
    ZipInputStream zin = null;
    try {/*from  w  w  w  .ja  v a  2s .  c o m*/
        zin = new ZipInputStream(new FileInputStream(zipFileFullPath));
        ZipEntry zipEntry = null;
        byte[] buf = new byte[1024];

        while ((zipEntry = zin.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();
            String newPath = zipFilePath + File.separator
                    + file.getName().substring(0, file.getName().lastIndexOf(".")) + File.separator
                    + zipEntryName;// original path +
                                                                                                                                                                 // zipfile Name + entry
                                                                                                                                                                 // name
            File outfile = new File(newPath);
            if (zipEntry.isDirectory()) {
                outfile.mkdirs();
                continue;
            } else {
                if (!outfile.getParentFile().exists()) {
                    outfile.getParentFile().mkdirs();
                }
            }

            OutputStream os = new BufferedOutputStream(new FileOutputStream(outfile));
            int readLen = 0;
            try {
                readLen = zin.read(buf, 0, 1024);
            } catch (IOException ioe) {
                readLen = -1;
            }
            while (readLen != -1) {
                os.write(buf, 0, readLen);
                try {
                    readLen = zin.read(buf, 0, 1024);
                } catch (IOException ioe) {
                    readLen = -1;
                }
            }
            os.close();
        }
    } catch (IOException e) {
        s_logger.error("unzip file error.", e);
    } finally {
        if (zin != null) {
            try {
                zin.close();
            } catch (IOException e) {
                s_logger.error("Error occurs.", e);
            }
        }
    }
}

From source file:org.apache.stratos.autoscaler.service.impl.AutoscalerServiceImpl.java

/**
* unzips the payload file//from   w  w  w.j av  a 2  s.  c o m
* 
* @param file
 * @param tempfileName 
*/
private void unzipFile(File file, String tempfileName) {

    int buffer = 2048;
    BufferedOutputStream dest = null;
    ZipInputStream zis = null;

    try {
        FileInputStream fis = new FileInputStream(file);
        zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;

        while ((entry = zis.getNextEntry()) != null) {

            log.debug("Extracting: " + entry);

            int count;
            byte data[] = new byte[buffer];
            String outputFilename = tempfileName + File.separator + entry.getName();
            createDirIfNeeded(tempfileName, entry);

            // write the files to the disk
            if (!entry.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(outputFilename);
                dest = new BufferedOutputStream(fos, buffer);
                while ((count = zis.read(data, 0, buffer)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }

    } catch (Exception e) {
        log.error("Exception is occurred in unzipping payload file. Reason:" + e.getMessage());
        throw new AutoscalerServiceException(e.getMessage(), e);
    } finally {
        closeStream(zis);
        closeStream(dest);
    }
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void LoadAstrid() {
    // Look for a zip file in the proper location
    String loc = Environment.getExternalStorageDirectory() + "/AstridImport/";
    AlertDialog.Builder errorBuilder = new AlertDialog.Builder(this);
    errorBuilder.setTitle("Error reading Astrid Import!");
    ZipInputStream zipStream = null;
    InputStream stream = null;/*from   ww w  .  j a  v a  2 s .  c  o  m*/
    try {
        // Try to safely open the file
        String errText = "Cannot find Astrid file in " + loc;
        File astridDir = new File(loc);
        if (!astridDir.isDirectory()) {
            throw new Exception(errText);
        }

        File[] files = astridDir.listFiles();
        if (files.length != 1) {
            throw new Exception(errText);
        }

        File astridFile = files[0];
        if (!astridFile.isFile()) {
            throw new Exception(errText);
        }

        // Try to unzip the file and unpack the tasks
        errText = "Could not unzip file " + astridFile.getAbsolutePath();
        stream = new FileInputStream(astridFile);
        zipStream = new ZipInputStream(stream);

        ZipEntry tasksEntry = null;
        while ((tasksEntry = zipStream.getNextEntry()) != null) {
            if (tasksEntry.getName().equals("tasks.csv")) {
                break;
            }
        }
        if (tasksEntry == null) {
            throw new Exception(errText);
        }

        int size = (int) tasksEntry.getSize();
        byte tasksContent[] = new byte[size];
        int offset = 0;
        while (size != 0) {
            int read = zipStream.read(tasksContent, offset, size);
            if (read == 0) {
                throw new Exception(errText);
            }
            offset += read;
            size -= read;
        }

        String tasksString = new String(tasksContent, "UTF-8");

        // Parse the tasks in the task list
        errText = "Could not parse task list";
        List<String> taskLines = new LinkedList<String>(Arrays.asList(tasksString.split("\n")));
        // Remove the header row
        taskLines.remove(0);
        // Some tasks have newlines in quotes, so we have to adjust for that.
        ListIterator<String> it = taskLines.listIterator();
        while (it.hasNext()) {
            String task = it.next();
            while (CountQuotes(task) % 2 == 1) {
                it.remove();
                task += it.next();
            }
            it.set(task);
        }
        for (String taskLine : taskLines) {
            List<String> taskFields = new LinkedList<String>(Arrays.asList(taskLine.split(",", -1)));
            // Some tasks have commas in quotes, so we have to adjust for that.
            it = taskFields.listIterator();
            while (it.hasNext()) {
                String field = it.next();
                while (CountQuotes(field) % 2 == 1) {
                    it.remove();
                    field += it.next();
                }
                it.set(field);
            }

            Task taskElement = new Task();
            taskElement.mName = taskFields.get(0);
            taskElement.mDescription = taskFields.get(8);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

            taskElement.mDueDate = Calendar.getInstance();
            taskElement.mDueDate.setTime(dateFormat.parse(taskFields.get(4)));
            String completedString = taskFields.get(9);
            taskElement.mCompletedDate = Calendar.getInstance();
            if (completedString.equals("")) {
                taskElement.mCompletedDate.setTimeInMillis(0);
            } else {
                taskElement.mCompletedDate.setTime(dateFormat.parse(completedString));
            }
            taskElement.mRepeatUnit = Task.RepeatUnit.NONE;
            taskElement.mRepeatTime = 0;
            taskElement.mRepeatFromComplete = false;
            String repeatString = taskFields.get(6);
            String repeatFields[] = repeatString.split(":");
            if (repeatFields[0].equals("RRULE")) {
                repeatFields = repeatFields[1].split(";");
                String freqFields[] = repeatFields[0].split("=");
                if (freqFields[0].equals("FREQ")) {
                    if (freqFields[1].equals("YEARLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.YEARS;
                    } else if (freqFields[1].equals("MONTHLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.MONTHS;
                    } else if (freqFields[1].equals("WEEKLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.WEEKS;
                    } else if (freqFields[1].equals("DAILY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.DAYS;
                    }
                }
                freqFields = repeatFields[1].split("=");
                if (freqFields[0].equals("INTERVAL")) {
                    taskElement.mRepeatTime = Integer.valueOf(freqFields[1]);
                }
                if (repeatFields.length > 2 && repeatFields[2] != null) {
                    freqFields = repeatFields[2].split("=");
                    if (freqFields[0].equals("FROM") && freqFields[1].equals("COMPLETION")) {
                        taskElement.mRepeatFromComplete = true;
                    }
                }
            }
            mDB.AddTask(taskElement);
        }

        RefreshView();
    } catch (Exception e) {
        AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
        dlg.show();
    } finally {

        try {
            if (zipStream != null) {
                zipStream.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (Exception e) {
            AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
            dlg.show();
        }
    }
}

From source file:eu.optimis.ics.ImageCreationServiceREST.java

/**
 * Uncompresses the given zip file. Unfortunately, the files' permission is not
 * preserved, especially with regards to an executable file.
 * @param zipFile       the zip file/*from  www. j a v a 2 s  .  c o  m*/
 * @param destination   the directory location
 * @throws IOException  IO Exception
 */
private void unzipFile(File zipFile, String destination) throws IOException {
    LOGGER.debug("ics.REST.unzipFile(): Unzipping " + zipFile + " to directory " + destination);
    //LOGGER.debug("ics.REST.unzipFile(): Opening input streams");
    FileInputStream fis = new FileInputStream(zipFile);
    ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    File destinationDirectory = new File(destination);

    while ((entry = zin.getNextEntry()) != null) {
        //LOGGER.debug("ics.REST.unzipFile(): Extracting: " + entry);

        if (entry.isDirectory()) {
            //LOGGER.debug("ics.REST.unzipFile(): Directory found, will be created");
            File targetDirectory = new File(destinationDirectory, entry.getName());
            targetDirectory.mkdir();
        } else {
            // extract data
            // open output streams
            int BUFFER = 2048;

            File destinationFile = new File(destinationDirectory, entry.getName());
            destinationFile.getParentFile().mkdirs();

            //LOGGER.debug("ics.REST.unzipFile(): Creating parent file of destination: "
            //        + destinationFile.getParent());
            //boolean parentDirectoriesCreated = destinationFile.getParentFile().mkdirs();                
            //LOGGER.debug("ics.REST.unzipFile(): Result of creating parents: "
            //        + parentDirectoriesCreated);

            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];

            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zin.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    }

    LOGGER.debug("ics.REST.unzipFile(): Unzipping file is done");
    zin.close();
    fis.close();
}

From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

/**
 * Estrae il contenuto di un archivio in formato ZIP.
 *
 * @param archiveInputStream L'input stream da cui leggere il contenuto dell'archivio.
 * @param path Il path della directory in cui estrarre il contenuto dell'archivio.
 *
 * @throws Exception//from w  w  w . j ava2  s .com
 */
// TODO: verificare come mai se il file non e' ZIP non va in errore
private void extractZip(InputStream archiveInputStream, String path) throws Exception {
    logger.debug("[ArchiveImporterJob::extractZip] BEGIN");
    ZipInputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        inputStream = new ZipInputStream(archiveInputStream);
        String entryName = null;
        byte[] buffer = new byte[1024];
        int n = 0;
        for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry()) {
            entryName = entry.getName();
            File entryFile = new File(path + File.separator + entryName);
            if (entry.isDirectory()) {
                if (!entryFile.mkdirs()) {
                    throw new EcmEngineException("cannot create directory: " + entryFile.getAbsolutePath());
                }
            } else {
                File parentDir = entryFile.getParentFile();
                if (!parentDir.exists()) {
                    if (!parentDir.mkdirs()) {
                        throw new EcmEngineException("cannot create directory: " + parentDir.getAbsolutePath());
                    }
                }
                fileOutputStream = new FileOutputStream(entryFile);
                while ((n = inputStream.read(buffer, 0, buffer.length)) > -1) {
                    fileOutputStream.write(buffer, 0, n);
                }
                fileOutputStream.close();
            }
            inputStream.closeEntry();
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
            }
            try {
                fileOutputStream.close();
            } catch (Exception e) {
            }
        }
        logger.debug("[ArchiveImporterJob::extractZip] END");
    }
}

From source file:org.wso2.carbon.bridge.EquinoxFrameworkLauncher.java

/**
 * Extract an archive to the target location
 *
 * @param compressFilePath - Archive path
 * @param target           - Location to extract
 *///w w w  .  j ava  2 s.c  o m
protected void extractResource(String compressFilePath, File target) {
    try {
        byte[] buf = new byte[1024];
        ZipInputStream zipinputstream;
        ZipEntry zipentry;
        zipinputstream = new ZipInputStream(context.getResourceAsStream(compressFilePath));

        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            String entryName = zipentry.getName();
            int n;
            FileOutputStream fileoutputstream;
            File newFile = new File(entryName);
            String directory = newFile.getParent();

            if (directory == null) {
                if (newFile.isDirectory())
                    break;
            }

            if (zipentry.isDirectory()) {
                zipinputstream.closeEntry();
                zipentry = zipinputstream.getNextEntry();
                continue;
            }

            if (newFile.isDirectory())
                break;
            File outputFile = new File(target.getPath(), entryName);
            if (outputFile.getParentFile() != null && !outputFile.getParentFile().mkdirs()) {
                throw new IOException(
                        "Fail to create the directory: " + outputFile.getParentFile().getAbsolutePath());
            }
            fileoutputstream = new FileOutputStream(outputFile);

            while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
                fileoutputstream.write(buf, 0, n);

            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();

        }

        zipinputstream.close();
    } catch (Exception ignored) {
        //ignore invalid compress file
        context.log(ignored.getMessage(), ignored);
    }
}

From source file:org.codehaus.mojo.jsimport.JsFileArtifactHandler.java

private List<File> expandWwwZipIntoTargetFolder(Artifact artifact, File wwwZipFile, File targetFolder,
        File workFolder) throws IOException {
    List<File> jsFiles = new ArrayList<File>();

    // FIXME: Need to consider scope here i.e. don't create a compile www-zip file for a test run.
    expansionFolder = new File(workFolder, "www-zip" + File.separator + wwwZipFile.getName());

    // Don't expand if it is already expanded.
    if (wwwZipFile.lastModified() > expansionFolder.lastModified()) {
        String gavPath = artifact.getGroupId().replace('.', File.separatorChar) + File.separator
                + artifact.getArtifactId() + File.separator + artifact.getVersion();
        File jsExpansionFolder = new File(expansionFolder, gavPath);

        FileInputStream fis = new FileInputStream(wwwZipFile);
        try {/*from  ww  w.j  ava2s  . c  o m*/
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
            ZipEntry entry;
            boolean firstEntryProcessed = false;
            int rootFolderPrefixPosn = 0;
            while ((entry = zis.getNextEntry()) != null) {
                // Any non-js files are simply copied into the target folder. js files are copied to a temporary
                // folder as something else needs to put them into the target folder (there may be processing a js
                // file along the way). However we ignore minified files when inflating as by convention, we don't
                // want them as part of the project - projects can minify later.

                String entryName = entry.getName().substring(rootFolderPrefixPosn);
                File entryFile = null;
                if (!entryName.endsWith("js")) {
                    if (!entry.isDirectory()) {
                        entryFile = new File(targetFolder, entryName);
                    } else if (!firstEntryProcessed) {
                        // Its a directory and it is the first thing in the zip file. We don't want to bother with
                        // this directory when creating files as we're more interested in merging it into the
                        // existing target folder.
                        rootFolderPrefixPosn = entryName.length();
                    }
                } else if (!entryName.endsWith("-min.js")) {
                    entryFile = new File(jsExpansionFolder, entryName);
                    jsFiles.add(entryFile);
                }

                // If we have something interesting to inflate.
                if (entryFile != null) {
                    entryFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(entryFile);
                    BufferedOutputStream dest = null;
                    try {
                        int count;
                        final int bufferSize = 2048;
                        byte data[] = new byte[bufferSize];
                        dest = new BufferedOutputStream(fos, bufferSize);
                        while ((count = zis.read(data, 0, bufferSize)) != -1) {
                            dest.write(data, 0, count);
                        }
                        dest.flush();
                    } finally {
                        dest.close();
                    }
                }

                firstEntryProcessed = true;
            }
        } finally {
            fis.close();
        }

        // Override the directory's mod time as that will equal the time it was compressed initially. We're not
        // interested in that - we're interested to learn whether the source zip file is newer that the directory we
        // expand into.
        expansionFolder.setLastModified(wwwZipFile.lastModified());
    } else {
        // Nothing changed. Just return a list of files that were previously expanded.
        Collection<File> existingFiles = FileUtils.listFiles(expansionFolder, new String[] { "js" }, true);
        for (File file : existingFiles) {
            if (!file.getName().endsWith("-min.js")) {
                jsFiles.add(file);
            }
        }
    }

    return jsFiles;
}

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

private BrandingResult extractBranding(final BrandedItem item, final File encryptedBrandingFile,
        final File tmpDecryptedBrandingFile, final File tmpBrandingDir) throws BrandingFailureException {
    try {/*from  ww  w  . j a  v  a 2 s.co m*/
        L.i("Extracting " + tmpDecryptedBrandingFile + " (" + item.brandingKey + ")");
        File brandingFile = new File(tmpBrandingDir, "branding.html");
        File watermarkFile = null;
        Integer backgroundColor = null;
        Integer menuItemColor = null;
        ColorScheme scheme = ColorScheme.light;
        boolean showHeader = true;
        String contentType = null;
        boolean wakelockEnabled = false;
        ByteArrayOutputStream brandingBos = new ByteArrayOutputStream();
        try {
            MessageDigest digester = MessageDigest.getInstance("SHA256");
            DigestInputStream dis = new DigestInputStream(
                    new BufferedInputStream(new FileInputStream(tmpDecryptedBrandingFile)), digester);
            try {
                ZipInputStream zis = new ZipInputStream(dis);
                try {
                    byte data[] = new byte[BUFFER_SIZE];
                    ZipEntry entry;
                    while ((entry = zis.getNextEntry()) != null) {
                        L.d("Extracting: " + entry);
                        int count = 0;
                        if (entry.getName().equals("branding.html")) {
                            while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                                brandingBos.write(data, 0, count);
                            }
                        } else {
                            if (entry.isDirectory()) {
                                L.d("Skipping branding dir " + entry.getName());
                                continue;
                            }
                            File destination = new File(tmpBrandingDir, entry.getName());
                            destination.getParentFile().mkdirs();
                            if ("__watermark__".equals(entry.getName())) {
                                watermarkFile = destination;
                            }
                            final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination),
                                    BUFFER_SIZE);
                            try {
                                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                                    fos.write(data, 0, count);
                                }
                            } finally {
                                fos.close();
                            }
                        }
                    }
                    while (dis.read(data) >= 0)
                        ;
                } finally {
                    zis.close();
                }
            } finally {
                dis.close();
            }
            String hexDigest = com.mobicage.rogerthat.util.TextUtils.toHex(digester.digest());
            if (!hexDigest.equals(item.brandingKey)) {
                encryptedBrandingFile.delete();
                SystemUtils.deleteDir(tmpBrandingDir);
                throw new BrandingFailureException("Branding cache was invalid!");
            }
            brandingBos.flush();
            byte[] brandingBytes = brandingBos.toByteArray();
            if (brandingBytes.length == 0) {
                encryptedBrandingFile.delete();
                SystemUtils.deleteDir(tmpBrandingDir);
                throw new BrandingFailureException("Invalid branding package!");
            }
            String brandingHtml = new String(brandingBytes, "UTF8");

            switch (item.type) {
            case BrandedItem.TYPE_MESSAGE:
                MessageTO message = (MessageTO) item.object;
                brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE,
                        TextUtils.htmlEncode(message.message).replace("\r", "").replace("\n", "<br>"));

                brandingHtml = brandingHtml.replace(NUNTIUZ_TIMESTAMP,
                        TimeUtils.getDayTimeStr(mContext, message.timestamp * 1000));

                FriendsPlugin friendsPlugin = mMainService.getPlugin(FriendsPlugin.class);
                brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME,
                        TextUtils.htmlEncode(friendsPlugin.getName(message.sender)));
                break;
            case BrandedItem.TYPE_FRIEND:
                FriendTO friend = (FriendTO) item.object;
                // In this case Friend is fully populated
                brandingHtml = brandingHtml.replace(NUNTIUZ_MESSAGE,
                        TextUtils.htmlEncode(friend.description).replace("\r", "").replace("\n", "<br>"));

                brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME, TextUtils.htmlEncode(friend.name));

                break;
            case BrandedItem.TYPE_GENERIC:
                if (item.object instanceof FriendTO) {
                    brandingHtml = brandingHtml.replace(NUNTIUZ_IDENTITY_NAME,
                            TextUtils.htmlEncode(((FriendTO) item.object).name));
                }
                break;
            }

            Matcher matcher = RegexPatterns.BRANDING_BACKGROUND_COLOR.matcher(brandingHtml);
            if (matcher.find()) {
                String bg = matcher.group(1);
                if (bg.length() == 4) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("#");
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(3));
                    sb.append(bg.charAt(3));
                    bg = sb.toString();
                }
                backgroundColor = Color.parseColor(bg);
            }

            matcher = RegexPatterns.BRANDING_MENU_ITEM_COLOR.matcher(brandingHtml);
            if (matcher.find()) {
                String bg = matcher.group(1);
                if (bg.length() == 4) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("#");
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(1));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(2));
                    sb.append(bg.charAt(3));
                    sb.append(bg.charAt(3));
                    bg = sb.toString();
                }
                menuItemColor = Color.parseColor(bg);
            }

            matcher = RegexPatterns.BRANDING_COLOR_SCHEME.matcher(brandingHtml);
            if (matcher.find()) {
                String schemeStr = matcher.group(1);
                scheme = "dark".equalsIgnoreCase(schemeStr) ? ColorScheme.dark : ColorScheme.light;
            }

            matcher = RegexPatterns.BRANDING_SHOW_HEADER.matcher(brandingHtml);
            if (matcher.find()) {
                String showHeaderStr = matcher.group(1);
                showHeader = "true".equalsIgnoreCase(showHeaderStr);
            }

            matcher = RegexPatterns.BRANDING_CONTENT_TYPE.matcher(brandingHtml);
            if (matcher.find()) {
                String contentTypeStr = matcher.group(1);
                L.i("Branding content-type: " + contentTypeStr);
                if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentTypeStr)) {
                    File tmpBrandingFile = new File(tmpBrandingDir, "embed.pdf");
                    if (tmpBrandingFile.exists()) {
                        contentType = AttachmentViewerActivity.CONTENT_TYPE_PDF;
                    }
                }
            }

            Dimension dimension1 = null;
            Dimension dimension2 = null;
            matcher = RegexPatterns.BRANDING_DIMENSIONS.matcher(brandingHtml);
            if (matcher.find()) {
                String dimensionsStr = matcher.group(1);
                L.i("Branding dimensions: " + dimensionsStr);
                String[] dimensions = dimensionsStr.split(",");
                try {
                    dimension1 = new Dimension(Integer.parseInt(dimensions[0]),
                            Integer.parseInt(dimensions[1]));
                    dimension2 = new Dimension(Integer.parseInt(dimensions[2]),
                            Integer.parseInt(dimensions[3]));
                } catch (Exception e) {
                    L.bug("Invalid branding dimension: " + matcher.group(), e);
                }
            }

            matcher = RegexPatterns.BRANDING_WAKELOCK_ENABLED.matcher(brandingHtml);
            if (matcher.find()) {
                String wakelockEnabledStr = matcher.group(1);
                wakelockEnabled = "true".equalsIgnoreCase(wakelockEnabledStr);
            }

            final List<String> externalUrlPatterns = new ArrayList<String>();
            matcher = RegexPatterns.BRANDING_EXTERNAL_URLS.matcher(brandingHtml);
            while (matcher.find()) {
                externalUrlPatterns.add(matcher.group(1));
            }

            FileOutputStream fos = new FileOutputStream(brandingFile);

            try {
                fos.write(brandingHtml.getBytes("UTF8"));
            } finally {
                fos.close();
            }
            if (contentType != null
                    && AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(contentType)) {
                brandingFile = new File(tmpBrandingDir, "embed.pdf");
            }
            return new BrandingResult(tmpBrandingDir, brandingFile, watermarkFile, backgroundColor,
                    menuItemColor, scheme, showHeader, dimension1, dimension2, contentType, wakelockEnabled,
                    externalUrlPatterns);
        } finally {
            brandingBos.close();
        }
    } catch (IOException e) {
        L.e(e);
        throw new BrandingFailureException("Error copying cached branded file to private space", e);
    } catch (NoSuchAlgorithmException e) {
        L.e(e);
        throw new BrandingFailureException("Cannot validate ", e);
    }
}