Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shareok.data.webserv; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.shareok.data.config.DataUtil; import org.shareok.data.config.ShareokdataManager; import org.shareok.data.datahandlers.DataHandlersUtil; import org.shareok.data.kernel.api.services.server.RepoServerService; import org.shareok.data.redis.RedisUtil; import org.shareok.data.redis.job.RedisJob; import org.shareok.data.redis.server.RepoServer; import org.springframework.util.FileCopyUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * * @author Tao Zhao */ public class WebUtil { private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(WebUtil.class); public static void setupFileDownload(HttpServletResponse response, String downloadPath) { try { File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { logger.error("Cannot set up a file download.", ioex); } } public static void outputJobInfoToModel(ModelAndView model, RedisJob job) { Date startTime = job.getStartTime(); Date endTime = job.getEndTime(); model.addObject("jobId", job.getJobId()); model.addObject("status", RedisUtil.REDIS_JOB_STATUS[job.getStatus()]); model.addObject("startTime", (null == startTime) ? "" : ShareokdataManager.getSimpleDateFormat().format(startTime)); model.addObject("endTime", (null == endTime) ? "" : ShareokdataManager.getSimpleDateFormat().format(endTime)); model.addObject("jobType", DataUtil.JOB_TYPES[job.getType()]); } public static void outputJobInfoToModel(RedirectAttributes redirectAttrs, RedisJob job) { Date startTime = job.getStartTime(); Date endTime = job.getEndTime(); redirectAttrs.addFlashAttribute("jobId", String.valueOf(job.getJobId())); redirectAttrs.addFlashAttribute("status", RedisUtil.REDIS_JOB_STATUS[job.getStatus()]); redirectAttrs.addFlashAttribute("startTime", (null != startTime ? ShareokdataManager.getSimpleDateFormat().format(startTime) : "")); redirectAttrs.addFlashAttribute("endTime", (null != endTime ? ShareokdataManager.getSimpleDateFormat().format(endTime) : "")); redirectAttrs.addFlashAttribute("jobType", DataUtil.JOB_TYPES[job.getType()]); redirectAttrs.addFlashAttribute("repoType", DataUtil.REPO_TYPES[job.getRepoType()].toUpperCase()); } public static String getReportDownloadLink(String jobType, String jobId) { String[] jobInfo = jobType.split("-"); String repoType = jobInfo[jobInfo.length - 1]; return ShareokdataManager.getShareokdataPath() + File.separator + repoType + File.separator + jobType + File.separator + jobId + File.separator + jobId + "-report.txt"; } public static String getMapFileDownloadLink(String jobType, String jobId) { String[] jobInfo = jobType.split("-"); String repoType = jobInfo[jobInfo.length - 1]; return ShareokdataManager.getShareokdataPath() + File.separator + repoType + File.separator + jobType + File.separator + jobId + File.separator + "mapfile"; } public static ModelAndView getServerList(ModelAndView model, RepoServerService serverService) throws JsonProcessingException { Map<String, String> serverList = serverService.getServerNameIdList(); if (null != serverList && serverList.size() > 0) { ObjectMapper mapper = new ObjectMapper(); Collection<String> ids = serverList.values(); List<RepoServer> serverObjList = serverService.getServerObjList(ids); String serverListJson = mapper.writeValueAsString(serverList); model.addObject("serverList", serverListJson); model.addObject("serverObjList", mapper.writeValueAsString(serverObjList)); } else { // model.addObject("emptyServerList", "There are NO servers set up."); } return model; } public static ModelAndView getRepoTypeList(ModelAndView model) throws JsonProcessingException { int index = 0; Map repoTypeMap = new HashMap(); for (String repoType : DataUtil.REPO_TYPES) { repoTypeMap.put(index, repoType); index++; } String repoTypeListStr; ObjectMapper mapper = new ObjectMapper(); repoTypeListStr = mapper.writeValueAsString(repoTypeMap); model.addObject("repoTypeList", repoTypeListStr); return model; } public static String getJournalSearchResultDownloadFileName(String publisher, String startDate, String endDate) { return ShareokdataManager.getJournalSearchResultDownloadPath() + File.separator + publisher + "_" + startDate + "_" + endDate + "_" + DataHandlersUtil.getCurrentTimeString() + ".csv"; } public static String getJournalSearchResultDownloadFilePathLink(String filePath) { return File.separator + "webserv" + File.separator + "downloads" + File.separator + filePath.split("downloads" + File.separator)[1]; } public static String getJournalSearchResultDownloadFilePathFromFileName(String fileName) { return ShareokdataManager.getJournalSearchResultDownloadPath() + File.separator + fileName; } public static void writeCsvData(String csvFilePath, List<List<String>> data) { DataHandlersUtil.writeCsvData(csvFilePath, data); } public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) { try { File file = new File(downloadPath); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); } catch (IOException ioex) { logger.error("Cannot download file responding to downloading resquest!", ioex); } } }