DingXiaoYu há 3 anos atrás
pai
commit
1149c7034f
1 ficheiros alterados com 409 adições e 1 exclusões
  1. 409 1
      后端接口/Java-Service.md

+ 409 - 1
后端接口/Java-Service.md

@@ -484,4 +484,412 @@ public boolean trainTheModel(int modelId) throws Exception{
     }
 ```
 
-高级方法,对某个模型使用某个文件来获得结果,最后删除这个文件。(为什么?)
+高级方法,对某个模型使用某个文件来获得结果,最后删除这个文件。(为什么?)
+
+# 5. FileService
+
+```java
+    public int uploadFile(int userId, MultipartFile inFile, String filename) throws Exception {
+        log.info("file uploading: filename = " + filename + ", userId = " + userId);
+        String fileType = FileHelper.getFileType(filename);
+        File file = FileHelper.multipartToFile(inFile);
+        log.info("server file location: " + file.getAbsolutePath());
+        int rsl = "csv".equals(fileType) ? csvLoader.loadCsv(file.getAbsolutePath(), userId) :
+                sasLoader.loadSas(file.getAbsolutePath(), userId);
+        file.delete();
+        return rsl;
+    }
+```
+
+首先获取文件名的后缀fileType,再讲MultipartFile转化为File对象。
+
+接着判断后缀是否为csv,如果是则用csvLoader保存,否则用sasLoader保存,最后删除该临时文件。返回值为文件id。
+
+> SAS可以读取各种文件作为其数据源,如CSV,Excel,Access,SPSS和原始数据。 它还有许多内置的数据源可供使用。 如果SAS程序使用数据集,则数据集称为**临时数据集**,然后在会话运行后丢弃。 但是如果它永久存储以备将来使用,那么它被称为**永久数据集**。 所有永久数据集都存储在特定库下。 SAS数据集以行和列的形式存储,也称为SAS数据表。
+>
+> 一般Excel导出的文件后缀即为csv文件。
+
+```java
+    public void deleteFile(int fileId) throws Exception {
+        String fileLoc = fileInfoDao.findById(fileId).getLocation();
+        fileInfoDao.delete(fileInfoDao.findById(fileId));
+        hdfsDao.deleteFileInHdfs(fileLoc, true);
+    }
+```
+
+在数据库和hdfs中同时删除该文件。
+
+```java
+    public TestFileValuePojo uploadTestFile(int userId, MultipartFile inFile, String filename) throws Exception {
+        int fileId = uploadFile(userId, inFile, filename);
+        String fileLoc = fileInfoDao.findById(fileId).getLocation();
+        List<Map<String, String>> values = csvAdapter.parquetFileReader(fileLoc);
+        log.error("Test File values: ", values);
+        //deleteFile(fileId);
+        return new TestFileValuePojo(String.valueOf(fileId), values);
+    }
+```
+
+上传测试文件后,要去获得某个属性(不清楚),封装进testFileValuePojo返回。
+
+```java
+    public List<FileNamePojo> getAllFiles(int userId) throws Exception {
+        List<FileInfo> files = fileInfoDao.findByUserId(userId);
+        List<FileNamePojo> rsl = files.stream().map((file) -> new FileNamePojo(String.valueOf(file.getId()), file.getFilename()))
+                .collect(Collectors.toList());
+        return rsl;
+    }
+```
+
+获取用户所有的文件信息,封装进FileNamePojo的列表后返回。
+
+```java
+    public FileAndFuncInfoPojo getAllFilesAndFunc(int userId) throws Exception {
+        return new FileAndFuncInfoPojo(getAllFiles(userId), funcInfoDao.findAll());
+    }
+```
+
+和上面的方法相比,多返回了些内容。
+
+```java
+    public FileDetailPojo getFileDetailInfo(int fileId) throws Exception {
+        FileInfo fileInfo = fileInfoDao.findById(fileId);
+        List<HeaderInfo> headerInfos = headerInfoDao.findByFileInfoId(fileId);
+        return new FileDetailPojo(fileInfo.getFilename(), fileInfo.getUploadTime(), new Json2Object().Json2HashMap(fileInfo.getFileStrucInfo()), headerInfos);
+    }
+```
+
+找到fileInfo和其对应的header信息,再封装返回。
+
+```java
+    public void analysis(int fileId) throws Exception {
+        try {
+            fileAnalysis.fileAnalysis(fileId, (float) 0.01);
+        } catch (Exception e) {
+            log.error("file analysis error");
+            throw e;
+        }
+    }
+```
+
+高级方法,暂时没看懂。
+
+```java
+    public boolean deleteFileById(int fileId) {
+        FileInfo fileInfo = fileInfoDao.findById(fileId);
+        if (fileInfo == null) {
+            return false;
+        }
+        List<Config> configList = configDao.findByFileInfoId(fileId);
+        if (configList != null) {
+            for (Config config : configList) {
+                List<Model> modelList = modelDao.findByConfigId(config.getId());
+                if (modelList != null) {
+                    for (Model model : modelList) {
+                        modelDao.delete(model);
+                    }
+                }
+                configDao.delete(configDao.findById(config.getId()));
+            }
+        }
+        //这里之前有bug需要在hdfs中删除文件
+        String fileLoc = fileInfoDao.findById(fileId).getLocation();
+        hdfsDao.deleteFileInHdfs(fileLoc, true);
+        fileInfoDao.delete(fileInfo);
+        return true;
+    }
+```
+
+找到该文件对应的config,找到使用该文件的所有config,以及所有config对应的model,并删除。最后在hdfs中删除。
+
+```java
+    public boolean updateHeaderInfo(int headerId, String aliasName, String fieldDes) {
+        HeaderInfo headerInfo = headerInfoDao.findById(headerId);
+        if (headerInfo == null) {
+            return false;
+        }
+        headerInfo.setFieldDes(fieldDes);
+        headerInfo.setAliasName(aliasName);
+        headerInfoDao.save(headerInfo);
+        return true;
+    }
+```
+
+修改headerInfo的信息。
+
+```java
+public boolean updateAllHeaders(List<InnerHeaderInfo> innerHeaderInfos, List<Integer> headerToUpdate) {
+    if (innerHeaderInfos == null || headerToUpdate == null) {
+        return false;
+    }
+    int currLen = headerToUpdate.size();
+    System.out.println("headerInfos = [" + innerHeaderInfos + "], headerToUpdate = [" + headerToUpdate + "]");
+    System.out.println(currLen);
+    for (int index : headerToUpdate) {
+        InnerHeaderInfo innerheaderInfo = innerHeaderInfos.get(index);
+        if (!updateHeaderInfo(Integer.parseInt(innerheaderInfo.getId()), innerheaderInfo.getAliasName(),
+                innerheaderInfo.getFieldDes())) {
+            return false;
+        }
+    }
+    return true;
+}
+```
+
+批量修改headerInfo。
+
+```java
+    public HashMap<String, HashMap<String, Object>> getFieldDistribution(String[] fieldIds) throws Exception {
+        try {
+            HashMap<String,HashMap<String,Object>> res = fileAnalysis.getFieldDistribution(fieldIds);
+            return res;
+        } catch (Exception e) {
+            log.error("file analysis error");
+            throw e;
+        }
+    }
+```
+
+高级方法,暂时看不懂。
+
+```java
+    public Object getFieldAnalysis(String[] fieldIds, int funcId) throws Exception {
+        try {
+
+            if (fieldIds == null || fieldIds.length == 0 || funcId == 0) {
+                return null;
+            }
+            String funcName = funcInfoDao.findById(funcId).getFuncName();
+            if (funcName == null) {
+                return null;
+            }
+            switch (funcName) {
+                case "数据分布":
+                    HashMap<String, HashMap<String, Object>> res_1 = fileAnalysis.getFieldDistribution(fieldIds);
+                    return res_1;
+                case "散点图":
+                    HashMap<String,ArrayList<Object>> res_2 = fileAnalysis.getFieldScatterDiagram(fieldIds);
+                    return res_2;
+                case "数据统计":
+                    HashMap<String, HashMap<String, Object>> res_3 = fileAnalysis.getFieldDescription(fieldIds);
+                    return res_3;
+                case "偏度-峰度":
+                    HashMap<String, HashMap<String, Object>> res_4 = fileAnalysis.getFieldSkewnessAndKurtosis(fieldIds);
+                    return res_4;
+                case "皮尔森相关系数":
+                    HashMap<String, Object> res_5 = fileAnalysis.getFieldCorr(fieldIds);
+                    return res_5;
+                default:
+                    break;
+            }
+            return null;
+        } catch (Exception e) {
+            log.error("file analysis error");
+            throw e;
+        }
+    }
+```
+
+高级方法,暂时看不懂。
+
+```java
+    public Object getFieldClassificationAnalysis(int fieldId, String[] fieldIds, int funcId) throws Exception {
+        try {
+            if (fieldId == 0 || fieldIds == null || fieldIds.length == 0 || funcId == 0) {
+                return null;
+            }
+            String funcName = funcInfoDao.findById(funcId).getFuncName();
+            if (funcName == null) {
+                return null;
+            }
+            switch (funcName) {
+                case "平均值":
+                    HashMap<String, HashMap<String, Object>> res_1 = fileAnalysis.getFieldClassificationAverage(fieldId,fieldIds);
+                    return res_1;
+                default:
+                    break;
+            }
+            return null;
+        }catch (Exception e) {
+            log.error("file analysis error");
+            throw e;
+        }
+    }
+```
+
+高级方法,暂时看不懂。
+
+# 6. PictureService
+
+```java
+    public boolean uploadPic(int userId, MultipartFile inFile, String filename) throws Exception {
+        String picAbsolutePath = appConfig.getAbsolutePath();
+        log.info("file uploading: filename = " + filename + ", userId = " + userId);
+        File file = FileHelper.multipartToFile(inFile);
+        log.info("server file location: " + file.getAbsolutePath());
+        if(!inFile.isEmpty()){
+            try {
+                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(inFile.getOriginalFilename())));
+                out.write(inFile.getBytes());
+                out.flush();
+                out.close();
+            } catch (IOException e) {
+               e.printStackTrace();
+                return false;
+            }
+            new Thread(new MyThread(file.getAbsolutePath(), userId, picAbsolutePath)).start();
+            return true;
+        }else{
+            return false;
+        }
+    }
+```
+
+这个方法很乱...它将MultipartFile转化为File之后,又进行了一次写操作,而且我怀疑是多余的。
+
+然后启动了一个线程去完成另外的任务。
+
+```java
+    public boolean parseZipFile(String filename, int userId, String descDir) throws IOException{
+        long startTime=System.currentTimeMillis();
+
+        if(!filename.endsWith(".zip")){
+            return false;
+        }
+        File pathFile = new File(descDir);
+        if(!pathFile.exists()){
+            if (!pathFile.mkdirs()){
+                return false;
+            }
+        }
+        File zipFile = new File(descDir+filename);
+        ZipFile zip = new ZipFile(zipFile);
+
+        String picFile = null;
+        Set<String> hs = new HashSet<>();
+        PicCategory picCategory = null;
+        PicFile picFileId = null;
+        List<PicInfo> picInfos = new ArrayList<>();
+        
+
+        for(Enumeration<? extends ZipEntry> enumeration = zip.entries(); enumeration.hasMoreElements();){
+            ZipEntry entry = enumeration.nextElement();
+            String zipEntryName = entry.getName();
+            InputStream in = zip.getInputStream(entry);
+            String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
+            //判断路径是否存在,不存在则创建文件路径
+            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
+            if(!file.exists()){
+                if (!file.mkdirs()){
+                    return false;
+                }
+            }
+            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
+            if(new File(outPath).isDirectory()){
+                continue;
+            }
+            //输出文件路径信息
+            String[] paths = outPath.split("/");
+            int pathLen = paths.length;
+
+            if(picFile==null){
+                picFile = paths[pathLen - 3];
+                picFileId = pictureFileDao.save(new PicFile(userId, paths[pathLen - 3], outPath.substring(0, outPath.lastIndexOf('/')).substring(0,outPath.lastIndexOf('/'))));
+            }
+
+            if(!hs.contains(paths[pathLen-2])){
+                hs.add(paths[pathLen - 2]);
+                picCategory = pictureCategoryDao.save(new PicCategory(paths[pathLen - 2], picFileId.getId()));
+                System.out.println(picCategory.getCategoryName());
+            }
+            //String location, String picname, String tag, String categoryId
+            picInfos.add(new PicInfo(outPath,paths[pathLen-1], paths[pathLen-2], picCategory.getId()));
+
+            OutputStream out = new FileOutputStream(outPath);
+            byte[] buf1 = new byte[1024];
+            int len;
+            while((len=in.read(buf1))>0){
+                out.write(buf1,0,len);
+            }
+            in.close();
+            out.close();
+        }
+        picInfos.forEach(picInfo -> pictureInfoDao.save(picInfo));
+        //("******************解压完毕********************");
+        long endTime=System.currentTimeMillis();
+        System.out.println(endTime - startTime);
+        return true;
+    }
+```
+
+首先将file转化为zip对象,然后对于zip对象中每一个entry项,都进行解压,并存入数据库中。
+
+```java
+    public List<PicFilePojo> getAllProj(int userId){
+        List<PicFile> picFiles = pictureFileDao.findByUserId(userId);
+        List<PicFilePojo> res = picFiles.stream().map((picInfo) -> new PicFilePojo(String.valueOf(picInfo.getId()), picInfo.getFileName()))
+                .collect(Collectors.toList());
+        return res;
+    }
+```
+
+找出用户所有的图片,封装为picFilePojo后返回。
+
+```java
+    public List<PicCategoryPojo> getOneProj(int picFileId){
+        List<PicCategory> picCategories = pictureCategoryDao.findByPicFileId(picFileId);
+        List<PicCategoryPojo> res = picCategories.stream().map((picInfo) -> new PicCategoryPojo(String.valueOf(picInfo.getId()), picInfo.getCategoryName()))
+                .collect(Collectors.toList());
+        return res;
+    }
+```
+
+获取单个图片的类别信息。
+
+```java
+    public List<PicInfoPojo> getAllPicAddr(int picTag){
+        List<PicInfo> picInfos = pictureInfoDao.findByCategoryId(picTag);
+        List<PicInfoPojo> res = picInfos.stream().map((picInfo) -> new PicInfoPojo(String.valueOf(picInfo.getId()), picInfo.getPicname(),picInfo.getLocation()))
+                .collect(Collectors.toList());
+        return res;
+    }
+```
+
+获取所有类别为picTag的图片信息。
+
+```java
+    public boolean updatePicInfo(int picId, int picCategoryId, String picTag ){
+        PicInfo picInfo =  pictureInfoDao.findById(picId);
+        //T.B.D.
+        //modelOfGet.setModel(model);
+        picInfo.setCategoryId(picCategoryId);
+        picInfo.setTag(picTag);
+        pictureInfoDao.save(picInfo);
+        return true;
+    }
+```
+
+更新某个图片的类别信息,不过话说,上面picTag还是int,怎么到这里就变成String了?
+
+```java
+    public class MyThread implements Runnable{
+        private final String fileAbsolutePath;
+        private final int userId;
+        private final String picAbsolutePath;
+        public MyThread(String fileAbsolutePath, int userId, String picAbsolutePath){
+            this.fileAbsolutePath = fileAbsolutePath;
+            this.userId = userId;
+            this.picAbsolutePath = picAbsolutePath;
+        }
+        @Override
+        public void run(){
+            try {
+                parseZipFile(fileAbsolutePath, userId, picAbsolutePath);
+            }catch (IOException e){
+               e.printStackTrace();
+            }
+        }
+    }
+```
+
+自创线程,调用parseZipFile方法。