Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:com.baasbox.service.dbmanager.DbManagerService.java

public static void importDb(String appcode, ZipInputStream zis) throws FileFormatException, Exception {
    File newFile = null;//w  w  w .  j a  va  2  s .co m
    FileOutputStream fout = null;
    try {
        //get the zipped file list entry
        ZipEntry ze = zis.getNextEntry();
        if (ze == null)
            throw new FileFormatException("Looks like the uploaded file is not a valid export.");
        if (ze.isDirectory()) {
            ze = zis.getNextEntry();
        }
        if (ze != null) {
            newFile = File.createTempFile("export", ".json");
            fout = new FileOutputStream(newFile);
            IOUtils.copy(zis, fout, BBConfiguration.getImportExportBufferSize());
            fout.close();
        } else {
            throw new FileFormatException("Looks like the uploaded file is not a valid export.");
        }
        ZipEntry manifest = zis.getNextEntry();
        if (manifest != null) {
            File manifestFile = File.createTempFile("manifest", ".txt");
            fout = new FileOutputStream(manifestFile);
            for (int c = zis.read(); c != -1; c = zis.read()) {
                fout.write(c);
            }
            fout.close();
            String manifestContent = FileUtils.readFileToString(manifestFile);
            manifestFile.delete();
            Pattern p = Pattern.compile(BBInternalConstants.IMPORT_MANIFEST_VERSION_PATTERN);
            Matcher m = p.matcher(manifestContent);
            if (m.matches()) {
                String version = m.group(1);
                if (version.compareToIgnoreCase("0.6.0") < 0) { //we support imports from version 0.6.0
                    throw new FileFormatException(String.format(
                            "Current baasbox version(%s) is not compatible with import file version(%s)",
                            BBConfiguration.getApiVersion(), version));
                } else {
                    if (BaasBoxLogger.isDebugEnabled())
                        BaasBoxLogger.debug("Version : " + version + " is valid");
                }
            } else {
                throw new FileFormatException("The manifest file does not contain a version number");
            }
        } else {
            throw new FileFormatException("Looks like zip file does not contain a manifest file");
        }
        if (newFile != null) {
            DbHelper.importData(appcode, newFile);
            zis.closeEntry();
            zis.close();
        } else {
            throw new FileFormatException("The import file is empty");
        }
    } catch (FileFormatException e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
        throw e;
    } catch (Throwable e) {
        BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
        throw new Exception("There was an error handling your zip import file.", e);
    } finally {
        try {
            if (zis != null) {
                zis.close();
            }
            if (fout != null) {
                fout.close();
            }
        } catch (IOException e) {
            // Nothing to do here
        }
    }
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Deploy a midlet archive file on PFS//w w w. ja  v a  2 s  . c o  m
 * @param midletFile The midlet file (ZIP file)
 */
@SuppressWarnings("unchecked")
public void deployMidlet(File midletFile) throws MMPException {
    try {
        File tmpDeployDir = new File(System.getProperty("java.io.tmpdir"), "tmpDeployDir");
        FileUtils.deleteDirectory(tmpDeployDir);
        FileUtils.forceMkdir(tmpDeployDir);

        ZipInputStream zip = new ZipInputStream(new FileInputStream(midletFile));
        ZipEntry entry;
        try {
            while ((entry = zip.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    File repFile = new File(tmpDeployDir, entry.getName());
                    repFile.mkdirs();
                } else {
                    String filename = entry.getName();
                    File entryFile = new File(tmpDeployDir, filename);
                    FileOutputStream fos = new FileOutputStream(entryFile);
                    try {
                        IOUtils.copy(zip, fos);
                    } finally {
                        fos.close();
                    }
                }
            }
        } finally {
            zip.closeEntry();
        }

        List<Midlet> midletList = new ArrayList<Midlet>();
        Collection<File> filesList = FileUtils.listFiles(tmpDeployDir, new String[] { "jar", "jad" }, true);

        for (File currentfile : filesList) {
            String midletType = null;
            String midletFilename = null;
            if (currentfile.getParentFile().getAbsolutePath().equals(tmpDeployDir.getAbsolutePath())) {
                midletType = currentfile.getName().split("\\.")[0];
            } else {
                midletType = currentfile.getParentFile().getName();
            }

            midletFilename = currentfile.getName();

            if (midletType != null) {
                boolean found = false;
                for (Midlet midlet : midletList) {
                    found = false;
                    if (midlet.getType().equals(midletType)) {
                        if (midlet.getJadLocation() == null)
                            midlet.setJadLocation(currentfile.toURI().toString());
                        else
                            midlet.setJarLocation(currentfile.toURI().toString());
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    Midlet midlet = new Midlet();
                    midlet.setType(midletType);
                    if (midletFilename.endsWith("jad"))
                        midlet.setJadLocation(currentfile.toURI().toString());
                    else
                        midlet.setJarLocation(currentfile.toURI().toString());
                    midletList.add(midlet);
                }
            }
        }

        for (Midlet midlet : midletList) {
            DaoManagerFactory.getInstance().getDaoManager().getDao("midlet").createOrUdpdate(midlet);
        }

        FileUtils.deleteDirectory(tmpDeployDir);
    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy PFM", ioe);
    }
}

From source file:edu.monash.merc.system.remote.HttpHpaFileGetter.java

public boolean importHPAXML(String remoteFile, String localFile) {
    //use httpclient to get the remote file
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(remoteFile);

    ZipInputStream zis = null;
    FileOutputStream fos = null;// ww  w . j a  va2s .co m
    try {
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream in = entity.getContent();
                zis = new ZipInputStream(in);
                ZipEntry zipEntry = zis.getNextEntry();
                while (zipEntry != null) {
                    String fileName = zipEntry.getName();
                    if (StringUtils.contains(fileName, HPA_FILE_NAME)) {
                        System.out.println("======= found file.");
                        File aFile = new File(localFile);
                        fos = new FileOutputStream(aFile);
                        byte[] buffer = new byte[BUFFER_SIZE];
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                        fos.flush();
                        break;
                    }
                }
            }
        } else {
            throw new DMRemoteException("can't get the file from " + remoteFile);
        }
    } catch (Exception ex) {
        throw new DMRemoteException(ex);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            if (zis != null) {
                zis.closeEntry();
                zis.close();
            }
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            //ignore whatever caught
        }
    }
    return true;
}

From source file:com.thinkbiganalytics.feedmgr.service.ExportImportTemplateService.java

private ImportTemplate openZip(String fileName, InputStream inputStream) throws IOException {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry entry;//ww  w. j a  va 2s  .  c o m
    // while there are entries I process them
    ImportTemplate importTemplate = new ImportTemplate(fileName);
    while ((entry = zis.getNextEntry()) != null) {
        log.info("zip file entry: " + entry.getName());
        // consume all the data from this entry
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        while ((len = zis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        String outString = new String(out.toByteArray(), "UTF-8");
        if (entry.getName().startsWith(NIFI_TEMPLATE_XML_FILE)) {
            importTemplate.setNifiTemplateXml(outString);
        } else if (entry.getName().startsWith(TEMPLATE_JSON_FILE)) {
            importTemplate.setTemplateJson(outString);
        } else if (entry.getName().startsWith(NIFI_CONNECTING_REUSABLE_TEMPLATE_XML_FILE)) {
            importTemplate.addNifiConnectingReusableTemplateXml(outString);
        }
    }
    zis.closeEntry();
    zis.close();
    if (!importTemplate.isValid()) {
        throw new UnsupportedOperationException(
                " The file you uploaded is not a valid archive.  Please ensure the Zip file has been exported from the system and has 2 valid files named: "
                        + NIFI_TEMPLATE_XML_FILE + ", and " + TEMPLATE_JSON_FILE);
    }
    importTemplate.setZipFile(true);
    return importTemplate;

}

From source file:org.dhatim.ect.formats.unedifact.UnEdifactSpecificationReader.java

private boolean readZipEntry(Map<String, byte[]> files, ZipInputStream folderZip, String entry)
        throws IOException {

    boolean result = false;

    ZipEntry fileEntry = folderZip.getNextEntry();
    while (fileEntry != null) {
        String fileName = fileEntry.getName();
        String fName = new File(fileName.toLowerCase()).getName().replaceFirst("tr", "ed");
        if (fName.startsWith(entry) || entry.equals("*")) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] bytes = new byte[2048];
            int size;
            while ((size = folderZip.read(bytes, 0, bytes.length)) != -1) {
                translatePseudoGraph(bytes);
                baos.write(bytes, 0, size);
            }/*from  w  w  w  .  j  ava2  s .  com*/

            File file = new File(fileName);
            String messageName = file.getName().toUpperCase();

            result = true;
            messages.add(messageName);
            if (entry.equals("*")) {
                Matcher match = entryFileName.matcher(messageName);
                if (match.matches()) {
                    String entryName = match.group(1);
                    files.put(entryName, baos.toByteArray());
                    versions.add((match.group(2) + match.group(3)).toLowerCase());
                }
            } else {
                files.put(entry, baos.toByteArray());
                break;
            }
        }
        folderZip.closeEntry();
        fileEntry = folderZip.getNextEntry();
    }

    return result;
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

public void importFromZipStep2(InputStream is) throws WPBIOException {
    ZipInputStream zis = new ZipInputStream(is);
    // we need to stop the notifications during import
    dataStorage.stopNotifications();// w  w w. j  a va2  s.c  o  m
    try {
        ZipEntry ze = null;
        while ((ze = zis.getNextEntry()) != null) {
            String name = ze.getName();
            if (name.indexOf(PATH_SITE_PAGES) >= 0) {
                if (name.indexOf("pageSource.txt") >= 0) {
                    importWebPageSource(zis, ze.getName());
                }
            } else if (name.indexOf(PATH_SITE_PAGES_MODULES) >= 0) {
                if (name.indexOf("moduleSource.txt") >= 0) {
                    importWebPageModuleSource(zis, ze.getName());
                }
            } else if (name.indexOf(PATH_ARTICLES) >= 0) {
                if (name.indexOf("articleSource.txt") >= 0) {
                    importArticleSource(zis, ze.getName());
                }
            } else if (name.indexOf(PATH_FILES) >= 0) {
                if (name.indexOf("/content/") >= 0 && !name.endsWith("/")) {
                    importFileContent(zis, ze.getName());
                }
            }
            zis.closeEntry();
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("cannot import from  zip step 2", e);
    } finally {
        dataStorage.startNotifications();
    }
    resetCache();
}

From source file:org.wso2.developerstudio.eclipse.test.automation.utils.server.CarbonServerManager.java

public void extractFile(String sourceFilePath, String extractedDir) throws IOException {
    FileOutputStream fileoutputstream = null;

    String fileDestination = extractedDir + File.separator;
    byte[] buf = new byte[1024];
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;//from w ww  .  java 2  s. c o m
    try {
        zipinputstream = new ZipInputStream(new FileInputStream(sourceFilePath));

        zipentry = zipinputstream.getNextEntry();

        while (zipentry != null) {
            // for each entry to be extracted
            String entryName = fileDestination + zipentry.getName();
            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);
            int n;

            File newFile = new File(entryName);
            boolean fileCreated = false;
            if (zipentry.isDirectory()) {
                if (!newFile.exists()) {
                    fileCreated = newFile.mkdirs();
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            } else {
                File resourceFile = new File(entryName.substring(0, entryName.lastIndexOf(File.separator)));
                if (!resourceFile.exists()) {
                    if (!resourceFile.mkdirs()) {
                        break;
                    }
                }
            }

            fileoutputstream = new FileOutputStream(entryName);

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

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

        }
        zipinputstream.close();
    } catch (IOException e) {
        WorkbenchElementsValidator.log.error("Error on archive extraction ", e);
        throw new IOException("Error on archive extraction ", e);

    } finally {
        if (fileoutputstream != null) {
            fileoutputstream.close();
        }
        if (zipinputstream != null) {
            zipinputstream.close();
        }
    }
}

From source file:org.forgerock.openicf.maven.DocBookResourceMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {//from   ww w . j a v a2  s  .  c  o  m
        getLog().info("Skipping DocBook generation");
        return;
    }

    if (!("pom".equalsIgnoreCase(project.getPackaging()))) {
        ArtifactHandler artifactHandler = project.getArtifact().getArtifactHandler();
        if (!"java".equals(artifactHandler.getLanguage())) {
            getLog().info(
                    "Not executing DocBook report as the project is not a Java classpath-capable package");
            return;
        }
    }

    try {

        if (!docbkxDirectory.exists()) {
            getLog().info("Not executing DocBook report as the project does not have DocBook source");
            return;
        }

        File rootDirectory = new File(buildDirectory,
                "openicf-docbkx/" + artifact.getArtifactId() + "-" + artifact.getVersion());
        try {
            FileUtils.mkdir(rootDirectory.getAbsolutePath());

            MavenResourcesExecution mre = new MavenResourcesExecution();
            mre.setMavenProject(getMavenProject());
            mre.setEscapeWindowsPaths(true);
            mre.setMavenSession(session);
            mre.setInjectProjectBuildFilters(true);

            List<FileUtils.FilterWrapper> filterWrappers = null;
            try {
                filterWrappers = fileFilter.getDefaultFilterWrappers(mre);
            } catch (MavenFilteringException e) {
                filterWrappers = Collections.emptyList();
            }

            if (docbkxDirectory.exists()) {
                final List<String> includes = FileUtils.getFileAndDirectoryNames(docbkxDirectory, "**",
                        StringUtils.join(DirectoryScanner.DEFAULTEXCLUDES, ",") + ",**/*.xml", true, false,
                        true, true);

                org.apache.commons.io.FileUtils.copyDirectory(docbkxDirectory, rootDirectory, new FileFilter() {
                    public boolean accept(File pathname) {
                        return includes.contains(pathname.getPath());
                    }
                });

                List<File> files = FileUtils.getFiles(docbkxDirectory, "**/*.xml", null);

                for (File file : files) {
                    try {
                        fileFilter.copyFile(file, new File(rootDirectory, file.getName()), true, filterWrappers,
                                getSourceEncoding());
                    } catch (MavenFilteringException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }
                }
            }

            File sharedRoot = rootDirectory.getParentFile();

            CodeSource src = getClass().getProtectionDomain().getCodeSource();
            if (src != null) {
                final ZipInputStream zip = new ZipInputStream(src.getLocation().openStream());
                ZipEntry entry = null;
                while ((entry = zip.getNextEntry()) != null) {
                    String name = entry.getName();
                    if (entry.getName().startsWith("shared")) {

                        File destination = new File(sharedRoot, name);
                        if (entry.isDirectory()) {
                            if (!destination.exists()) {
                                destination.mkdirs();
                            }
                        } else {
                            if (!destination.exists()) {
                                FileOutputStream output = null;
                                try {
                                    output = new FileOutputStream(destination);
                                    IOUtil.copy(zip, output);
                                } finally {
                                    IOUtil.close(output);
                                }
                            }
                        }
                    }
                }
                zip.closeEntry();
                zip.close();
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Error copy DocBook resources.", e);
        }

        // Generate Config and Schema DocBook Chapter
        CurrentLocale.set(Locale.ENGLISH);
        ConnectorDocBuilder generator = new ConnectorDocBuilder(this);
        generator.executeReport();

        // Look at the content of the resourcesDirectory and create a
        // manifest
        // of the files
        // so that velocity can easily process any resources inside the JAR
        // that
        // need to be processed.

        if (attach) {
            RemoteResourcesBundle remoteResourcesBundle = new RemoteResourcesBundle();
            remoteResourcesBundle.setSourceEncoding(getSourceEncoding());

            DirectoryScanner scanner = new DirectoryScanner();
            scanner.setBasedir(new File(buildDirectory, "openicf-docbkx/"));
            // scanner.setIncludes(new String[] { docFolder + "/**" });
            scanner.addDefaultExcludes();
            scanner.scan();

            List<String> includedFiles = Arrays.asList(scanner.getIncludedFiles());

            if (resourcesDirectory.exists()) {
                scanner = new DirectoryScanner();
                scanner.setBasedir(resourcesDirectory);
                if (includes != null && includes.length != 0) {
                    scanner.setIncludes(includes);
                } else {
                    scanner.setIncludes(DEFAULT_INCLUDES);
                }

                if (excludes != null && excludes.length != 0) {
                    scanner.setExcludes(excludes);
                }

                scanner.addDefaultExcludes();
                scanner.scan();
                includedFiles.addAll(Arrays.asList(scanner.getIncludedFiles()));
            }
            for (String resource : includedFiles) {
                remoteResourcesBundle.addRemoteResource(StringUtils.replace(resource, '\\', '/'));
            }

            RemoteResourcesBundleXpp3Writer w = new RemoteResourcesBundleXpp3Writer();

            try {
                File f = new File(buildDirectory,
                        "openicf-docbkx/" + BundleRemoteResourcesMojo.RESOURCES_MANIFEST);

                FileUtils.mkdir(f.getParentFile().getAbsolutePath());

                Writer writer = new FileWriter(f);

                w.write(writer, remoteResourcesBundle);
            } catch (IOException e) {
                throw new MojoExecutionException("Error creating remote resources manifest.", e);
            }

            File outputFile = generateArchive(new File(buildDirectory, "openicf-docbkx/"),
                    finalName + "-docbkx.jar");

            projectHelper.attachArtifact(project, "jar", "docbkx", outputFile);
        } else {
            getLog().info("NOT adding DocBook to attached artifacts list.");
        }
    } catch (ArchiverException e) {
        failOnError("ArchiverException: Error while creating archive", e);
    } catch (IOException e) {
        failOnError("IOException: Error while creating archive", e);
    } catch (RuntimeException e) {
        failOnError("RuntimeException: Error while creating archive", e);
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.BackupImportController.java

public void performImport(InputStream is) throws Exception {
    File working_dir = OmFileHelper.getUploadImportDir();
    if (!working_dir.exists()) {
        working_dir.mkdir();//from w w w .j  a  v a 2s .  co m
    }

    File f = OmFileHelper.getNewDir(working_dir, "import_" + CalendarPatterns.getTimeForStreamId(new Date()));

    log.debug("##### WRITE FILE TO: " + f);

    ZipInputStream zipinputstream = new ZipInputStream(is);
    ZipEntry zipentry = zipinputstream.getNextEntry();
    while (zipentry != null) {
        String fName = zipentry.getName();
        if (File.pathSeparatorChar != '\\' && fName.indexOf('\\') > -1) {
            fName = fName.replace('\\', '/');
        }
        // for each entry to be extracted
        File fentry = new File(f, fName);
        File dir = fentry.isDirectory() ? fentry : fentry.getParentFile();
        dir.mkdirs();
        if (fentry.isDirectory()) {
            zipentry = zipinputstream.getNextEntry();
            continue;
        }

        FileHelper.copy(zipinputstream, fentry);
        zipinputstream.closeEntry();
        zipentry = zipinputstream.getNextEntry();

    }
    zipinputstream.close();

    /*
     * ##################### Import Organizations
     */
    Serializer simpleSerializer = new Persister();
    {
        List<Organisation> list = readList(simpleSerializer, f, "organizations.xml", "organisations",
                Organisation.class);
        for (Organisation o : list) {
            long oldId = o.getOrganisation_id();
            o.setOrganisation_id(null);
            Long newId = organisationManager.addOrganisationObj(o);
            organisationsMap.put(oldId, newId);
        }
    }

    log.info("Organizations import complete, starting user import");
    /*
     * ##################### Import Users
     */
    {
        List<User> list = readUserList(f, "users.xml", "users");
        for (User u : list) {
            OmTimeZone tz = u.getOmTimeZone();
            if (tz == null || tz.getJname() == null) {
                String jNameTimeZone = configurationDao.getConfValue("default.timezone", String.class,
                        "Europe/Berlin");
                OmTimeZone omTimeZone = omTimeZoneDaoImpl.getOmTimeZone(jNameTimeZone);
                u.setOmTimeZone(omTimeZone);
                u.setForceTimeZoneCheck(true);
            } else {
                u.setForceTimeZoneCheck(false);
            }

            u.setStarttime(new Date());
            long userId = u.getUser_id();
            u.setUser_id(null);
            if (u.getSipUser() != null && u.getSipUser().getId() != 0) {
                u.getSipUser().setId(0);
            }
            usersDao.update(u, -1L);
            usersMap.put(userId, u.getUser_id());
        }
    }

    log.info("Users import complete, starting room import");
    /*
     * ##################### Import Rooms
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        RegistryMatcher matcher = new RegistryMatcher(); //TODO need to be removed in the later versions
        Serializer serializer = new Persister(strategy, matcher);

        matcher.bind(Long.class, LongTransform.class);
        matcher.bind(Integer.class, IntegerTransform.class);
        registry.bind(User.class, new UserConverter(usersDao, usersMap));
        registry.bind(RoomType.class, new RoomTypeConverter(roomManager));

        List<Room> list = readList(serializer, f, "rooms.xml", "rooms", Room.class);
        for (Room r : list) {
            Long roomId = r.getRooms_id();

            // We need to reset ids as openJPA reject to store them otherwise
            r.setRooms_id(null);
            if (r.getModerators() != null) {
                for (Iterator<RoomModerator> i = r.getModerators().iterator(); i.hasNext();) {
                    RoomModerator rm = i.next();
                    if (rm.getUser().getUser_id() == null) {
                        i.remove();
                    }
                }
            }
            r = roomDao.update(r, null);
            roomsMap.put(roomId, r.getRooms_id());
        }
    }

    log.info("Room import complete, starting room organizations import");
    /*
     * ##################### Import Room Organisations
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        Serializer serializer = new Persister(strategy);

        registry.bind(Organisation.class, new OrganisationConverter(orgDao, organisationsMap));
        registry.bind(Room.class, new RoomConverter(roomDao, roomsMap));

        List<RoomOrganisation> list = readList(serializer, f, "rooms_organisation.xml", "room_organisations",
                RoomOrganisation.class);
        for (RoomOrganisation ro : list) {
            if (!ro.getDeleted()) {
                // We need to reset this as openJPA reject to store them otherwise
                ro.setRooms_organisation_id(null);
                roomManager.addRoomOrganisation(ro);
            }
        }
    }

    log.info("Room organizations import complete, starting appointement import");
    /*
     * ##################### Import Appointements
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        Serializer serializer = new Persister(strategy);

        registry.bind(AppointmentCategory.class, new AppointmentCategoryConverter(appointmentCategoryDaoImpl));
        registry.bind(User.class, new UserConverter(usersDao, usersMap));
        registry.bind(AppointmentReminderTyps.class,
                new AppointmentReminderTypeConverter(appointmentReminderTypDaoImpl));
        registry.bind(Room.class, new RoomConverter(roomDao, roomsMap));
        registry.bind(Date.class, DateConverter.class);

        List<Appointment> list = readList(serializer, f, "appointements.xml", "appointments",
                Appointment.class);
        for (Appointment a : list) {
            Long appId = a.getAppointmentId();

            // We need to reset this as openJPA reject to store them otherwise
            a.setAppointmentId(null);
            if (a.getUserId() != null && a.getUserId().getUser_id() == null) {
                a.setUserId(null);
            }
            Long newAppId = appointmentDao.addAppointmentObj(a);
            appointmentsMap.put(appId, newAppId);
        }
    }

    log.info("Appointement import complete, starting meeting members import");
    /*
     * ##################### Import MeetingMembers
     * 
     * Reminder Invitations will be NOT send!
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        Serializer serializer = new Persister(strategy);

        registry.bind(User.class, new UserConverter(usersDao, usersMap));
        registry.bind(Appointment.class, new AppointmentConverter(appointmentDao, appointmentsMap));

        List<MeetingMember> list = readList(serializer, f, "meetingmembers.xml", "meetingmembers",
                MeetingMember.class);
        for (MeetingMember ma : list) {
            if (ma.getUserid() != null && ma.getUserid().getUser_id() == null) {
                ma.setUserid(null);
            }
            if (!ma.getDeleted()) {
                // We need to reset this as openJPA reject to store them otherwise
                ma.setMeetingMemberId(null);
                meetingMemberDao.addMeetingMemberByObject(ma);
            }
        }
    }

    log.info("Meeting members import complete, starting ldap config import");
    /*
     * ##################### Import LDAP Configs
     */
    {
        List<LdapConfig> list = readList(simpleSerializer, f, "ldapconfigs.xml", "ldapconfigs",
                LdapConfig.class, true);
        for (LdapConfig c : list) {
            ldapConfigDao.addLdapConfigByObject(c);
        }
    }

    log.info("Ldap config import complete, starting recordings import");
    /*
     * ##################### Import Recordings
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        RegistryMatcher matcher = new RegistryMatcher(); //TODO need to be removed in the later versions
        Serializer serializer = new Persister(strategy, matcher);

        matcher.bind(Long.class, LongTransform.class);
        matcher.bind(Integer.class, IntegerTransform.class);
        registry.bind(Date.class, DateConverter.class);

        List<FlvRecording> list = readList(serializer, f, "flvRecordings.xml", "flvrecordings",
                FlvRecording.class, true);
        for (FlvRecording fr : list) {
            fr.setFlvRecordingId(0);
            if (fr.getRoom_id() != null) {
                fr.setRoom_id(roomsMap.get(fr.getRoom_id()));
            }
            if (fr.getOwnerId() != null) {
                fr.setOwnerId(usersMap.get(fr.getOwnerId()));
            }
            if (fr.getFlvRecordingMetaData() != null) {
                for (FlvRecordingMetaData meta : fr.getFlvRecordingMetaData()) {
                    meta.setFlvRecordingMetaDataId(0);
                    meta.setFlvRecording(fr);
                }
            }
            flvRecordingDao.addFlvRecordingObj(fr);
        }
    }

    log.info("FLVrecording import complete, starting private message folder import");
    /*
     * ##################### Import Private Message Folders
     */
    {
        List<PrivateMessageFolder> list = readList(simpleSerializer, f, "privateMessageFolder.xml",
                "privatemessagefolders", PrivateMessageFolder.class, true);
        for (PrivateMessageFolder p : list) {
            Long folderId = p.getPrivateMessageFolderId();
            PrivateMessageFolder storedFolder = privateMessageFolderDao.getPrivateMessageFolderById(folderId);
            if (storedFolder == null) {
                p.setPrivateMessageFolderId(0);
                Long newFolderId = privateMessageFolderDao.addPrivateMessageFolderObj(p);
                messageFoldersMap.put(folderId, newFolderId);
            }
        }
    }

    log.info("Private message folder import complete, starting user contacts import");
    /*
     * ##################### Import User Contacts
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        Serializer serializer = new Persister(strategy);

        registry.bind(User.class, new UserConverter(usersDao, usersMap));

        List<UserContact> list = readList(serializer, f, "userContacts.xml", "usercontacts", UserContact.class,
                true);
        for (UserContact uc : list) {
            Long ucId = uc.getUserContactId();
            UserContact storedUC = userContactsDao.getUserContacts(ucId);

            if (storedUC == null && uc.getContact() != null && uc.getContact().getUser_id() != null) {
                uc.setUserContactId(0);
                Long newId = userContactsDao.addUserContactObj(uc);
                userContactsMap.put(ucId, newId);
            }
        }
    }

    log.info("Usercontact import complete, starting private messages item import");
    /*
     * ##################### Import Private Messages
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        Serializer serializer = new Persister(strategy);

        registry.bind(User.class, new UserConverter(usersDao, usersMap));
        registry.bind(Room.class, new RoomConverter(roomDao, roomsMap));
        registry.bind(Date.class, DateConverter.class);

        List<PrivateMessage> list = readList(serializer, f, "privateMessages.xml", "privatemessages",
                PrivateMessage.class, true);
        for (PrivateMessage p : list) {
            p.setPrivateMessageId(0);
            p.setPrivateMessageFolderId(getNewId(p.getPrivateMessageFolderId(), Maps.MESSAGEFOLDERS));
            p.setUserContactId(getNewId(p.getUserContactId(), Maps.USERCONTACTS));
            if (p.getRoom() != null && p.getRoom().getRooms_id() == null) {
                p.setRoom(null);
            }
            if (p.getTo() != null && p.getTo().getUser_id() == null) {
                p.setTo(null);
            }
            if (p.getFrom() != null && p.getFrom().getUser_id() == null) {
                p.setFrom(null);
            }
            if (p.getOwner() != null && p.getOwner().getUser_id() == null) {
                p.setOwner(null);
            }
            privateMessagesDao.addPrivateMessageObj(p);
        }
    }

    log.info("Private message import complete, starting file explorer item import");
    /*
     * ##################### Import File-Explorer Items
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        RegistryMatcher matcher = new RegistryMatcher(); //TODO need to be removed in the later versions
        Serializer serializer = new Persister(strategy, matcher);

        matcher.bind(Long.class, LongTransform.class);
        matcher.bind(Integer.class, IntegerTransform.class);
        registry.bind(Date.class, DateConverter.class);

        List<FileExplorerItem> list = readList(serializer, f, "fileExplorerItems.xml", "fileExplorerItems",
                FileExplorerItem.class, true);
        for (FileExplorerItem file : list) {
            // We need to reset this as openJPA reject to store them otherwise
            file.setFileExplorerItemId(0);
            Long roomId = file.getRoom_id();
            file.setRoom_id(roomsMap.containsKey(roomId) ? roomsMap.get(roomId) : null);
            fileExplorerItemDao.addFileExplorerItem(file);
        }
    }

    log.info("File explorer item import complete, starting file poll import");
    /*
     * ##################### Import Room Polls
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        Serializer serializer = new Persister(strategy);

        registry.bind(User.class, new UserConverter(usersDao, usersMap));
        registry.bind(Room.class, new RoomConverter(roomDao, roomsMap));
        registry.bind(PollType.class, new PollTypeConverter(pollManager));
        registry.bind(Date.class, DateConverter.class);

        List<RoomPoll> list = readList(serializer, f, "roompolls.xml", "roompolls", RoomPoll.class, true);
        for (RoomPoll rp : list) {
            pollManager.savePollBackup(rp);
        }
    }

    log.info("Poll import complete, starting configs import");
    /*
     * ##################### Import Configs
     */
    {
        Registry registry = new Registry();
        Strategy strategy = new RegistryStrategy(registry);
        RegistryMatcher matcher = new RegistryMatcher(); //TODO need to be removed in the later versions
        Serializer serializer = new Persister(strategy, matcher);

        matcher.bind(Long.class, LongTransform.class);
        registry.bind(Date.class, DateConverter.class);
        registry.bind(User.class, new UserConverter(usersDao, usersMap));

        List<Configuration> list = readList(serializer, f, "configs.xml", "configs", Configuration.class, true);
        for (Configuration c : list) {
            Configuration cfg = configurationDao.get(c.getConf_key());
            c.setConfiguration_id(cfg == null ? null : cfg.getConfiguration_id());
            if (c.getUser() != null && c.getUser().getUser_id() == null) {
                c.setUser(null);
            }
            if ("crypt_ClassName".equals(c.getConf_key())) {
                try {
                    Class.forName(c.getConf_value());
                } catch (ClassNotFoundException e) {
                    c.setConf_value(MD5Implementation.class.getCanonicalName());
                }
            }
            configurationDao.update(c, -1L);
        }
    }

    log.info("Configs import complete, starting copy of files and folders");
    /*
     * ##################### Import real files and folders
     */
    importFolders(f);

    log.info("File explorer item import complete, clearing temp files");

    FileHelper.removeRec(f);
}

From source file:edu.ku.brc.specify.config.ResourceImportExportDlg.java

/**
 * Imports a report resource from a zip file (see writeReportResToZipFile())
 * //from   w  ww .  ja  v a2s  . c om
 * If resource contains an SpReport, the SpReport's data source query will be imported
 * as well if an equivalent query does not exist in the database.
 *  
 * @param file
 * @param appRes
 * @param dirArg
 * @param newResName
 * @return
 */
protected SpAppResource importSpReportZipResource(final File file, final SpAppResource appRes,
        final SpAppResourceDir dirArg, final String newResName) {
    SpAppResourceDir dir = dirArg;

    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(file));

        //Assuming they come out in the order they were put in.
        ZipEntry entry = zin.getNextEntry();
        if (entry == null) {
            throw new Exception(getResourceString("RIE_ReportImportFileError"));
        }
        String app = readZipEntryToString(zin, entry);
        zin.closeEntry();

        entry = zin.getNextEntry();
        if (entry == null) {
            throw new Exception(getResourceString("RIE_ReportImportFileError"));
        }
        String data = readZipEntryToString(zin, entry);
        zin.closeEntry();

        Element appRoot = XMLHelper.readStrToDOM4J(app);
        Node metadata = appRoot.selectSingleNode("metadata");
        String metadataStr = metadata.getStringValue();
        if (!metadataStr.endsWith(";")) {
            metadataStr += ";";
        }
        Node mimeTypeNode = appRoot.selectSingleNode("mimetype");
        String mimeTypeStr = mimeTypeNode != null ? mimeTypeNode.getStringValue().trim() : null;

        entry = zin.getNextEntry();
        if (entry != null) {
            appRes.setDataAsString(data);
            appRes.setMetaData(metadataStr.trim());

            String repType = appRes.getMetaDataMap().getProperty("reporttype");
            String mimeType = mimeTypeStr != null ? mimeTypeStr
                    : repType != null && repType.equalsIgnoreCase("label") ? "jrxml/label" : "jrxml/report";

            appRes.setMimeType(mimeType);
            appRes.setLevel((short) 3);//XXX level?????????????????

            String spReport = readZipEntryToString(zin, entry);
            zin.closeEntry();
            zin.close();

            Element repElement = XMLHelper.readStrToDOM4J(spReport);

            SpReport report = new SpReport();
            report.initialize();
            report.setSpecifyUser(contextMgr.getClassObject(SpecifyUser.class));
            report.fromXML(repElement, newResName != null, contextMgr);

            if (newResName != null) {
                report.setName(newResName);
            }
            appRes.setName(report.getName());
            appRes.setDescription(appRes.getName());

            if (newResName != null && report.getQuery() != null) {
                showLocalizedMsg("RIE_ReportNewQueryTitle", "RIE_ReportNewQueryMsg",
                        report.getQuery().getName(), report.getName());
            }

            report.setAppResource((SpAppResource) appRes);
            ((SpAppResource) appRes).getSpReports().add(report);

            DataProviderSessionIFace session = null;
            try {
                session = DataProviderFactory.getInstance().createSession();
                session.beginTransaction();

                if (dir.getId() != null) {
                    dir = session.get(SpAppResourceDir.class, dir.getId());
                }

                dir.getSpPersistedAppResources().add(appRes);
                appRes.setSpAppResourceDir(dir);

                if (report.getReportObject() != null && report.getReportObject().getId() == null) {
                    session.saveOrUpdate(report.getReportObject());
                }
                session.saveOrUpdate(dir);
                session.saveOrUpdate(appRes);
                session.saveOrUpdate(report);

                session.commit();
                completeMsg = getLocalizedMessage("RIE_RES_IMPORTED", file.getName());

            } catch (Exception ex) {
                session.rollback();
                //ex.printStackTrace();
                throw ex;

            } finally {
                if (session != null)
                    session.close();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ResourceImportExportDlg.class, e);
        return null;
    }

    return appRes;
}