Example usage for org.apache.commons.io FileUtils copyDirectoryToDirectory

List of usage examples for org.apache.commons.io FileUtils copyDirectoryToDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyDirectoryToDirectory.

Prototype

public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException 

Source Link

Document

Copies a directory to within another directory preserving the file dates.

Usage

From source file:org.openmrs.module.chartsearch.server.EmbeddedSolrServerCreator.java

@Override
public SolrServer createSolrServer() {

    // If user has not setup solr config folder, set a default one
    // TODO use solr functions to determine config folder
    String configFolderPath = properties.getSolrHome() + File.separatorChar + "collection1" + File.separatorChar
            + "conf";
    File configFolder = new File(configFolderPath);
    if (configFolder.exists()) {
        try {/*from   www .  ja v a 2 s .  c  om*/
            FileUtils.deleteDirectory(configFolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    URL url = getClass().getClassLoader().getResource("collection1/conf");
    try {
        File file = new File(url.toURI());
        FileUtils.copyDirectoryToDirectory(file,
                new File(properties.getSolrHome() + File.separatorChar + "collection1"));
        setDataImportConnectionInfo(configFolderPath);
    } catch (IOException e) {
        log.error("Failed to copy Solr config folder", e);
    } catch (Exception e) {
        log.error("Failed to set dataImport connection info", e);
    }

    // Get the solr home folder
    // Tell solr that this is our home folder
    System.setProperty("solr.solr.home", properties.getSolrHome());

    log.info(String.format("solr.solr.home: %s", properties.getSolrHome()));

    /*CoreContainer.Initializer initializer = new CoreContainer.Initializer();
    CoreContainer coreContainer;
    try {
       coreContainer = initializer.initialize();
       solrServer = new EmbeddedSolrServer(coreContainer, "");
       return solrServer;
    }
    catch (FileNotFoundException e) {
       e.printStackTrace();
       return null;
    }
    catch (Exception e) {
       e.printStackTrace();
       return null;
    }*/

    CoreContainer coreContainer = new CoreContainer();
    try {
        coreContainer.load();
        solrServer = new EmbeddedSolrServer(coreContainer, "");
        return solrServer;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.openmrs.module.solr.SolrActivator.java

/**
 * @see Activator#startup()//  w ww. ja  va 2 s  .c om
 */
public void startup() {
    log.info("Starting Solr Module");

    try {
        //Get the solr home folder
        String solrHome = Context.getAdministrationService().getGlobalProperty("solr.home",
                new File(OpenmrsUtil.getApplicationDataDirectory(), "solr").getAbsolutePath());

        //Tell solr that this is our home folder
        System.setProperty("solr.solr.home", solrHome);

        //If user has not setup solr config folder, set a default one
        String configFolder = solrHome + File.separatorChar + "conf";
        if (!new File(configFolder).exists()) {
            URL url = OpenmrsClassLoader.getInstance().getResource("conf");
            File file = new File(url.getFile());
            FileUtils.copyDirectoryToDirectory(file, new File(solrHome));

            setDataImportConnectionInfo(configFolder);
        }
    } catch (Exception ex) {
        log.error("Failed to copy Solr config folder", ex);
    }
}

From source file:org.openmrs.steps.UniversalSteps.java

@AfterStories
public void copyFilesOver() throws URISyntaxException, IOException {
    try {/*w w  w  .  j  av a  2s  .  c o  m*/
        String style = "reports/style";
        File viewDirectory = createDirectoryIfDoesNotExist("view");
        URL styleResource = getClass().getClassLoader().getResource(style);

        if (styleResource != null) {
            FileUtils.copyDirectoryToDirectory(new File(styleResource.toURI()), viewDirectory);
        }

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

From source file:org.phenotips.variantstore.db.solr.SolrControllerTest.java

@Before
public void before() throws IOException {
    // copy resources
    FileUtils.copyDirectoryToDirectory(Paths.get(getClass().getResource("/tsvs").getPath()).toFile(),
            folder.getRoot());/*from ww  w.  j ava 2  s.  c om*/
    tsvs = folder.getRoot().toPath().resolve("tsvs");
    solr = folder.getRoot().toPath().resolve("solr");

    header = new VariantHeader("someId", true);
}

From source file:org.protocoderrunner.apprunner.api.PFileIO.java

@ProtoMethod(description = "Copy a file or directory", example = "")
@ProtoMethodParam(params = { "name", "destination" })
public void copyDirToDir(String name, String to) {
    File file = new File(AppRunnerSettings.get().project.getStoragePath() + File.separator + name);
    File dir = new File(AppRunnerSettings.get().project.getStoragePath() + File.separator + to);
    dir.mkdirs();/* w ww .ja  va2 s.c  om*/

    try {
        FileUtils.copyDirectoryToDirectory(file, dir);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.tolven.assembler.glassfish3.GlassFish3Assembler.java

protected void assembleDeployFiles() throws IOException {
    ExtensionPoint exnPt = getDescriptor().getExtensionPoint(EXNPT_DEPLOY);
    ExtensionPoint appServerExnPt = getParentExtensionPoint(exnPt);
    String relativeConfigExtDirPath = getDescriptor().getAttribute(ATTR_STAGE_DEPLOY_DIR).getValue();
    File destDir = new File(getPluginTmpDir(), getAppServerDirname() + "/" + relativeConfigExtDirPath);
    for (Extension exn : appServerExnPt.getConnectedExtensions()) {
        PluginDescriptor pd = exn.getDeclaringPluginDescriptor();
        for (Parameter param : exn.getParameters("file")) {
            File src = getFilePath(pd, param.valueAsString());
            FileUtils.copyFileToDirectory(src, destDir);
        }/*from www  .j av  a  2  s  .  c o  m*/
        for (Parameter param : exn.getParameters("dir")) {
            File srcDir = getFilePath(pd, param.valueAsString());
            FileUtils.copyDirectoryToDirectory(srcDir, destDir);
        }
    }
}

From source file:org.tolven.assembler.war.WARAssembler.java

protected void addTagSource(PluginDescriptor pd, File metaInfTagDir, XMLStreamWriter writer)
        throws IOException, XMLStreamException {
    ExtensionPoint tagSrcDirectoryExnPt = pd.getExtensionPoint("tagSourceDirectory");
    if (tagSrcDirectoryExnPt != null) {
        for (Extension tagSrcDirectoryExn : tagSrcDirectoryExnPt.getConnectedExtensions()) {
            String dirname = tagSrcDirectoryExn.getParameter("source-directory").valueAsString();
            File dir = getFilePath(tagSrcDirectoryExn.getDeclaringPluginDescriptor(), dirname);
            logger.debug("Copy " + dir.getPath() + " to " + metaInfTagDir.getPath());
            FileUtils.copyDirectoryToDirectory(dir, metaInfTagDir);
            addTagSource(dir, writer);/*from   w  w w  .  jav a2  s  . c  o  m*/
        }
    }
}

From source file:org.wise.vle.web.MySystemExporter.java

private void copyDirToZipDir(String sourcePath, String relativePath) {
    File sourceFile = new File(sourcePath);
    File destDir = new File(zipFolder.toString(), relativePath);
    try {/*from w  w  w. j  a  va2  s .c  o m*/
        FileUtils.forceMkdir(destDir);
        FileUtils.copyDirectoryToDirectory(sourceFile, destDir);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.wise.vle.web.VLEGetSpecialExport.java

/**
 * Generates and returns an excel xls of exported student data.
 *//*  www. j  av  a 2 s  . co  m*/
@RequestMapping("/specialExport")
public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //get the signed in user
    User signedInUser = ControllerUtil.getSignedInUser();

    /*
     * clear the instance variables because only one instance of a servlet
     * is ever created
     */
    clearVariables();

    //obtain the start time for debugging purposes
    debugStartTime = new Date().getTime();

    //get the run and project attributes
    runId = request.getParameter("runId");
    runName = request.getParameter("runName");
    projectId = request.getParameter("projectId");
    projectName = request.getParameter("projectName");
    parentProjectId = request.getParameter("parentProjectId");
    nodeId = request.getParameter("nodeId");

    //the export type "latestStudentWork" or "allStudentWork"
    exportType = request.getParameter("exportType");

    Long runIdLong = null;
    try {
        runIdLong = new Long(runId);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }

    Run run = null;
    try {
        if (runId != null) {
            //get the run object
            run = runService.retrieveById(runIdLong);
        }
    } catch (ObjectNotFoundException e1) {
        e1.printStackTrace();
    }

    boolean allowedAccess = false;

    /*
     * admins can make a request
     * teachers that are owners of the run can make a request
     */
    if (SecurityUtils.isAdmin(signedInUser)) {
        //the user is an admin so we will allow this request
        allowedAccess = true;
    } else if (SecurityUtils.isTeacher(signedInUser)
            && SecurityUtils.isUserOwnerOfRun(signedInUser, runIdLong)) {
        //the user is a teacher that is an owner or shared owner of the run so we will allow this request
        allowedAccess = true;
    }

    if (!allowedAccess) {
        //user is not allowed to make this request
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }

    Project projectObj = run.getProject();
    ProjectMetadata metadata = projectObj.getMetadata();
    String projectMetaDataJSONString = metadata.toJSONString();

    String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");
    String rawProjectUrl = (String) run.getProject().getCurnit().accept(new CurnitGetCurnitUrlVisitor());
    String projectPath = curriculumBaseDir + rawProjectUrl;
    String projectFolderName = "";
    String projectFolderPath = "";

    if (rawProjectUrl != null) {
        // get the folder name e.g. 12345
        projectFolderName = rawProjectUrl.substring(1, rawProjectUrl.indexOf("/", 1));
    }

    if (projectPath != null) {
        // get the project folder path e.g. /user/wise/tomcat/webapps/curriculum/12345
        projectFolderPath = projectPath.substring(0, projectPath.lastIndexOf("/"));
    }

    //get the classmate user infos
    JSONArray classmateUserInfosJSONArray = RunUtil.getClassmateUserInfos(run, workgroupService, runService);

    //get the teacher info
    teacherUserInfoJSONObject = RunUtil.getTeacherUserInfo(run, workgroupService);

    //get the shared teacher infos
    JSONArray sharedTeacherUserInfosJSONArray = RunUtil.getSharedTeacherUserInfos(run, workgroupService);

    //get the run info
    JSONObject runInfoJSONObject = RunUtil.getRunInfo(run);

    //get all the student attendance entries for this run
    List<StudentAttendance> studentAttendanceList = studentAttendanceService
            .getStudentAttendanceByRunId(run.getId());
    JSONArray studentAttendanceJSONArray = new JSONArray();

    /*
     * loop through all the student attendance entries so we can
     * create JSONObjects out of them to put in our studentAttendanceJSONArray
     */
    for (int x = 0; x < studentAttendanceList.size(); x++) {
        //get a StudenAttendance object
        StudentAttendance studentAttendance = studentAttendanceList.get(x);

        //get the JSONObject representation
        JSONObject studentAttendanceJSONObj = studentAttendance.toJSONObject();

        //add it to our array
        studentAttendanceJSONArray.put(studentAttendanceJSONObj);
    }

    //get the path of the wise base dir
    String wiseBaseDir = vleProperties.getProperty("wiseBaseDir");

    try {
        //get the project meta data JSON object
        projectMetaData = new JSONObject(projectMetaDataJSONString);
    } catch (JSONException e2) {
        e2.printStackTrace();
    }

    try {
        if (runInfoJSONObject.has("startTime")) {
            //get the start time as a string
            String startTimeString = runInfoJSONObject.getString("startTime");

            if (startTimeString != null && !startTimeString.equals("null") && !startTimeString.equals("")) {
                long startTimeLong = Long.parseLong(startTimeString);

                Timestamp startTimeTimestamp = new Timestamp(startTimeLong);

                //get the date the run was created
                startTime = timestampToFormattedString(startTimeTimestamp);
            }
        }

        if (runInfoJSONObject.has("endTime")) {
            //get the end time as a string
            String endTimeString = runInfoJSONObject.getString("endTime");

            if (endTimeString != null && !endTimeString.equals("null") && !endTimeString.equals("")) {
                long endTimeLong = Long.parseLong(endTimeString);

                Timestamp endTimeTimestamp = new Timestamp(endTimeLong);

                //get the date the run was archived
                endTime = timestampToFormattedString(endTimeTimestamp);
            }
        }
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    //parse the student attendance data so we can query it later
    parseStudentAttendance(studentAttendanceJSONArray);

    //the List that will hold all the workgroup ids
    Vector<String> workgroupIds = new Vector<String>();

    JSONArray customStepsArray = new JSONArray();

    //gather the custom steps if the teacher is requesting a custom export
    if (exportType.equals("customLatestStudentWork") || exportType.equals("customAllStudentWork")) {
        String customStepsArrayJSONString = request.getParameter("customStepsArray");

        try {
            customStepsArray = new JSONArray(customStepsArrayJSONString);

            //loop through all the node ids
            for (int x = 0; x < customStepsArray.length(); x++) {
                //add the node id to our list of custom steps
                String nodeId = customStepsArray.getString(x);
                customSteps.add(nodeId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //create a file handle to the project file
    File projectFile = new File(projectPath);

    //the hash map to store workgroup id to period id
    HashMap<Integer, Integer> workgroupIdToPeriodId = new HashMap<Integer, Integer>();

    String teacherWorkgroupId = "";

    //create an array to hold all the teacher workgroup ids
    teacherWorkgroupIds = new ArrayList<String>();

    JSONObject project = null;

    try {
        //get the project JSON object
        project = new JSONObject(FileManager.getFileText(projectFile));

        //create the map of node ids to node titles
        makeNodeIdToNodeTitleAndNodeMap(project);

        /*
         * create the list of node ids in the order they appear in the project.
         * this also creates the map of node ides to node titles with positions
         */
        makeNodeIdList(project);

        //get the nodes
        JSONArray nodes = project.getJSONArray("nodes");

        //loop through all the nodes
        for (int x = 0; x < nodes.length(); x++) {
            //get a node
            JSONObject node = nodes.getJSONObject(x);

            try {
                //get the text from the file
                String fileText = FileManager
                        .getFileText(new File(projectFile.getParentFile(), node.getString("ref")));

                //get the content for the node
                JSONObject nodeContent = new JSONObject(fileText);

                //put an entry into the hashmap with key as node id and value as JSON node content
                nodeIdToNodeContent.put(node.getString("identifier"), nodeContent);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //get the array of classmates
        //JSONArray classmateUserInfosJSONArray = new JSONArray(classmateUserInfos);

        //get the teacher user info
        //teacherUserInfoJSONObject = new JSONObject(teacherUserInfo);

        //get the owner teacher workgroup id
        teacherWorkgroupId = teacherUserInfoJSONObject.getString("workgroupId");

        //add the owner teacher
        teacherWorkgroupIds.add(teacherWorkgroupId);

        //get the shared teacher user infos
        //JSONArray sharedTeacherUserInfosJSONArray = new JSONArray(sharedTeacherUserInfos);

        //loop through all the shared teacher user infos
        for (int z = 0; z < sharedTeacherUserInfosJSONArray.length(); z++) {
            //get a shared teacher
            JSONObject sharedTeacherJSONObject = (JSONObject) sharedTeacherUserInfosJSONArray.get(z);

            if (sharedTeacherJSONObject != null) {
                if (sharedTeacherJSONObject.has("workgroupId")) {
                    //get the shared teacher workgroup id
                    String sharedTeacherWorkgroupId = sharedTeacherJSONObject.getString("workgroupId");

                    //add the shared teacher workgroup id to the array
                    teacherWorkgroupIds.add(sharedTeacherWorkgroupId);
                }
            }
        }

        //loop through all the classmates
        for (int y = 0; y < classmateUserInfosJSONArray.length(); y++) {
            //get a classmate
            JSONObject classmate = classmateUserInfosJSONArray.getJSONObject(y);

            //make sure workgroupId and periodId exist and are not null
            if (classmate.has("workgroupId") && !classmate.isNull("workgroupId")) {
                //get the workgroup id for the classmate
                int workgroupId = classmate.getInt("workgroupId");

                if (classmate.has("periodId") && !classmate.isNull("periodId")) {
                    //get the period id for the classmate
                    int periodId = classmate.getInt("periodId");

                    //put an entry into the hashmap with key as workgroup id and value as period id
                    workgroupIdToPeriodId.put(workgroupId, periodId);
                }

                if (classmate.has("periodName") && !classmate.isNull("periodName")) {
                    //get the period name such as 1, 2, 3, or 4, etc.
                    String periodName = classmate.getString("periodName");
                    workgroupIdToPeriodName.put(workgroupId, periodName);
                }

                if (classmate.has("userIds") && !classmate.isNull("userIds")) {
                    /*
                     * get the student logins, this is a single string with the logins
                     * separated by ':'
                     */
                    String userIds = classmate.getString("userIds");
                    workgroupIdToUserIds.put(workgroupId, userIds);
                }

                if (classmate.has("periodId") && !classmate.isNull("periodId") && classmate.has("periodName")
                        && !classmate.isNull("periodName") && classmate.has("userIds")
                        && !classmate.isNull("userIds")) {

                    //add the workgroup id string to the List of workgroup ids
                    workgroupIds.add(workgroupId + "");
                }

                if (classmate.has("wiseIds") && !classmate.isNull("wiseIds")) {
                    //get the wise ids for this workgroup
                    JSONArray wiseIds = classmate.getJSONArray("wiseIds");
                    workgroupIdToWiseIds.put(workgroupId, wiseIds);
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (exportType.equals("specialExport")) {

        String nodeTitleWithPosition = "Step " + nodeIdToNodeTitlesWithPosition.get(nodeId);
        String fileName = runName + "-" + runId + "-" + nodeTitleWithPosition;
        fileName = fileName.replaceAll(" ", "_");

        /*
         * we will return a zipped folder that contains all the necessary
         * files to view the student work
         */
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + ".zip" + "\"");

        //create a folder that will contain all the files and will then be zipped
        File zipFolder = new File(fileName);
        zipFolder.mkdir();

        //create the file that will contain all the data in a JSON object
        File dataFile = new File(zipFolder, "data.js");

        JSONObject data = new JSONObject();
        JSONArray students = new JSONArray();

        try {
            //add the project, run, and step information
            data.put("projectName", projectName);
            data.put("projectId", projectId);
            data.put("runName", runName);
            data.put("runId", runId);
            data.put("stepName", nodeTitleWithPosition);
            data.put("nodeId", nodeId);
            data.put("projectFolderName", projectFolderName);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

        String nodeType = "";

        //get the step content
        JSONObject nodeContent = nodeIdToNodeContent.get(nodeId);

        if (nodeContent != null) {
            try {
                //get the node type e.g. SVGDraw or mysystem2
                nodeType = nodeContent.getString("type");

                if (nodeType != null) {
                    //make the node type lower case for easy comparison later
                    nodeType = nodeType.toLowerCase();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (nodeType == null) {

        } else if (nodeType.equals("svgdraw")) {
            if (wiseBaseDir != null && wiseBaseDir != "") {
                //get the lz77.js file from the server
                File sourcelz77File = new File(wiseBaseDir + "/vle/node/draw/svg-edit/lz77.js");

                //create a lz77.js file in the folder we are creating
                File newlz77File = new File(zipFolder, "lz77.js");

                //copy the contents of the lz77.js file into our new file
                FileUtils.copyFile(sourcelz77File, newlz77File);

                //get the viewStudentWork.html file for svgdraw
                File sourceViewStudentWorkFile = new File(wiseBaseDir + "/vle/node/draw/viewStudentWork.html");

                //create a viewStudentWork.html file in the folder we are creating
                File newViewStudentWorkFile = new File(zipFolder, "viewStudentWork.html");

                //copy the contents of the viewStudentWork.html file into our new file
                FileUtils.copyFile(sourceViewStudentWorkFile, newViewStudentWorkFile);

                // get the project assets folder
                File assetsFolder = new File(projectFolderPath, "assets");

                // copy the assets folder into the folder we are creating
                FileUtils.copyDirectoryToDirectory(assetsFolder, zipFolder);
            }
        } else if (nodeType.equals("mysystem2")) {
            if (wiseBaseDir != null && wiseBaseDir != "") {
                MySystemExporter myExporter = new MySystemExporter(wiseBaseDir, zipFolder);
                myExporter.copyFiles();
            }
        } else if (nodeType.equals("sensor")) {
            if (wiseBaseDir != null && wiseBaseDir != "") {
                //get the paths of all the files we need to copy
                Vector<String> filesToCopy = new Vector<String>();
                filesToCopy.add(wiseBaseDir + "/vle/model/content.js");
                filesToCopy.add(wiseBaseDir + "/vle/util/helperfunctions.js");
                filesToCopy.add(wiseBaseDir + "/vle/lib/jquery/js/flot/jquery.flot.js");
                filesToCopy.add(wiseBaseDir + "/vle/lib/jquery/js/flot/jquery.js");
                filesToCopy.add(wiseBaseDir + "/vle/node/Node.js");
                filesToCopy.add(wiseBaseDir + "/vle/model/nodevisit.js");
                filesToCopy.add(wiseBaseDir + "/vle/node/sensor/sensor.js");
                filesToCopy.add(wiseBaseDir + "/vle/node/sensor/SensorNode.js");
                filesToCopy.add(wiseBaseDir + "/vle/node/sensor/sensorstate.js");
                filesToCopy.add(wiseBaseDir + "/vle/node/sensor/viewStudentWork.html");

                //loop through all the file paths
                for (int x = 0; x < filesToCopy.size(); x++) {
                    //get a file path
                    String filePath = filesToCopy.get(x);

                    //copy the file to our zip folder
                    copyFileToFolder(filePath, zipFolder);
                }

                //get the original step content file
                File originalStepContentFile = new File(projectFolderPath + "/" + nodeId);

                //get the content as a string
                String stepContentString = FileUtils.readFileToString(originalStepContentFile);

                //make a variable definition for the step content object so we can access it as a variable
                stepContentString = "var stepContent = " + stepContentString + ";";

                //create the new file
                File newStepContentFile = new File(zipFolder, "stepContent.js");

                //write the step content to the stepContent.js file
                FileUtils.writeStringToFile(newStepContentFile, stepContentString);
            }
        }

        //loop through the workgroup ids
        for (int x = 0; x < workgroupIds.size(); x++) {
            //get a workgroup id
            String userId = workgroupIds.get(x);
            Long userIdLong = Long.parseLong(userId);

            //get the UserInfo object for the workgroup id
            UserInfo userInfo = vleService.getUserInfoByWorkgroupId(userIdLong);

            //get the wise ids
            JSONArray wiseIds = workgroupIdToWiseIds.get(Integer.parseInt(userId));

            //get all the work for a workgroup id
            List<StepWork> stepWorksForWorkgroupId = vleService.getStepWorksByUserInfo(userInfo);

            //get all the step works for this node id
            List<StepWork> stepWorksForNodeId = getStepWorksForNodeId(stepWorksForWorkgroupId, nodeId);

            JSONArray studentDataArray = new JSONArray();

            //loop through all the step works
            for (int y = 0; y < stepWorksForNodeId.size(); y++) {
                //get a stepwork
                StepWork stepWork = stepWorksForNodeId.get(y);

                //get the student data from the step work
                JSONObject studentData = getStudentData(stepWork);

                //put the student data into the student data array
                studentDataArray.put(studentData);
            }

            JSONObject studentObject = new JSONObject();
            try {
                //put the workgroup id into the student object
                studentObject.put("workgroupId", userIdLong);

                //put the wise ids into the student object
                studentObject.put("wiseIds", wiseIds);

                //put the array of student work into the student object
                studentObject.put("studentDataArray", studentDataArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //add the student object into the array
            students.put(studentObject);
        }

        try {
            //put the student array into the data object
            data.put("students", students);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /*
         * turn the student data object into a javascript declaration
         * e.g.
         * from
         * {}
         * to
         * var data = {};
         */
        String javascriptDataString = getJavascriptText("data", data);

        //write the data to the data.js file
        FileUtils.writeStringToFile(dataFile, javascriptDataString);

        //get the response output stream
        ServletOutputStream outputStream = response.getOutputStream();

        //create ZipOutputStream object
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));

        //get path prefix so that the zip file does not contain the whole path
        // eg. if folder to be zipped is /home/lalit/test
        // the zip file when opened will have test folder and not home/lalit/test folder
        int len = zipFolder.getAbsolutePath().lastIndexOf(File.separator);
        String baseName = zipFolder.getAbsolutePath().substring(0, len + 1);

        //add the folder to the zip file
        addFolderToZip(zipFolder, out, baseName);

        //close the zip output stream
        out.close();

        //delete the folder that has been created on the server
        FileUtils.deleteDirectory(zipFolder);
    }

    //perform cleanup
    clearVariables();

    return null;
}

From source file:org.wso2.ppaas.tools.artifactmigration.ConversionTool.java

/**
 * Method to add script directories specific to each IaaS
 *
 * @param outputLocation output location of the script directories
 *///  www  . jav  a 2 s  .c o  m
private static void addIaasScriptDirectories(String outputLocation) {

    File sourceLocationEc2 = new File(
            Constants.DIRECTORY_SOURCE_SCRIPT + Constants.DIRECTORY_SOURCE_SCRIPT_EC2);
    File sourceLocationGce = new File(
            Constants.DIRECTORY_SOURCE_SCRIPT + Constants.DIRECTORY_SOURCE_SCRIPT_GCE);
    File sourceLocationKub = new File(
            Constants.DIRECTORY_SOURCE_SCRIPT + Constants.DIRECTORY_SOURCE_SCRIPT_KUBERNETES);
    File sourceLocationMock = new File(
            Constants.DIRECTORY_SOURCE_SCRIPT + Constants.DIRECTORY_SOURCE_SCRIPT_MOCK);
    File sourceLocationOS = new File(
            Constants.DIRECTORY_SOURCE_SCRIPT + Constants.DIRECTORY_SOURCE_SCRIPT_OPENSTACK);
    File targetLocation = new File(outputLocation);
    try {
        FileUtils.copyDirectoryToDirectory(sourceLocationEc2, targetLocation);
        FileUtils.copyDirectoryToDirectory(sourceLocationGce, targetLocation);
        FileUtils.copyDirectoryToDirectory(sourceLocationKub, targetLocation);
        FileUtils.copyDirectoryToDirectory(sourceLocationMock, targetLocation);
        FileUtils.copyDirectoryToDirectory(sourceLocationOS, targetLocation);
    } catch (IOException e) {
        log.error("Error in copying scripts directory ", e);
    }
}