ShowSer.java 11.3 KB
package com.example.demo;

import com.aliyuncs.imagesearch.model.v20180120.SearchItemResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;


/**
 * Created by jack on 2018/4/18.
 */
@Service
public class ShowSer {

    @Autowired
    PhotoSer aliPhotoSer;

    public ConcurrentHashMap<String, Integer> currentIndexMap = new ConcurrentHashMap<>();

    public ConcurrentHashMap<String, List<Integer>> sknDirsListMap = new ConcurrentHashMap<String, List<Integer>>();

    public ConcurrentHashMap<String, Integer> samplesMap = new ConcurrentHashMap<>();

    /*public Set<String> updateSet =Collections.synchronizedSet(new HashSet<>());*/




    public PhotoViewObj fetchCurentPhotos(String currentDir, int skip) {
        Integer index = currentIndexMap.get(currentDir);
        if (null == index) {
            index = 0;
        }
        index = index + skip;
        if (index >= sknDirsListMap.get(currentDir).size()) {
            index = 0;
        }
        currentIndexMap.put(currentDir, index);
        int skn = sknDirsListMap.get(currentDir).get(index);
        return fetchPhotos(currentDir, skn);
    }


    public PhotoViewObj fetchPrevPhotos(String currentDir) {
        int index = currentIndexMap.get(currentDir);
        index--;
        if (index < 0) {
            int last = sknDirsListMap.get(currentDir).size() - 1;

            index = last;
        }
        currentIndexMap.put(currentDir, index);
        int skn = sknDirsListMap.get(currentDir).get(index);
        return fetchPhotos(currentDir, skn);

    }

    public PhotoViewObj fetchSknPhotos(String currentDir, String skn) {
        return fetchPhotos(currentDir, Integer.valueOf(skn));
    }


    public void loadDir(String curDir) {
        curDir = StringUtils.trim(curDir);
        if (curDir.endsWith("/")) {
            curDir = StringUtils.stripEnd(curDir, "/");
        }
        //文件夹过滤器
        IOFileFilter dirFilter = new IOFileFilter() {
            public boolean accept(File dir, String name) {
                return true;
            }

            public boolean accept(File file) {
                return true;
            }
        };
        //文件过滤器
        IOFileFilter fileFilter = new IOFileFilter() {
            public boolean accept(File dir, String name) {
                return false;
            }

            public boolean accept(File file) {
                return false;
            }
        };
        Iterator<File> fileIterator = FileUtils.iterateFilesAndDirs(new File(curDir), fileFilter, dirFilter);
        List<Integer> sknDirList = new ArrayList<>();
        while (fileIterator.hasNext()) {
            File oneSknDir = fileIterator.next();
            if (!oneSknDir.isDirectory()) continue;

            if (StringUtils.equals(oneSknDir.getAbsolutePath(), curDir)) continue;
            sknDirList.add(Integer.valueOf(oneSknDir.getName()));
        }
        sknDirList.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        sknDirsListMap.put(curDir, sknDirList);
    }

    private PhotoViewObj fetchPhotos(String curDir, int skn) {
        PhotoViewObj photoViewObj = new PhotoViewObj();
        try {
            photoViewObj.setMainPic("/show/read?curDir=" + URLEncoder.encode(curDir) + "&skn=" + skn + "&order=0");
            for (int i = 1; i < 20; i++) {
                photoViewObj.getSimPics().add("/show/read?curDir=" + URLEncoder.encode(curDir) + "&skn=" + skn + "&order=" + i);
            }

            String sknDir = curDir + "/" + skn + "/";
            Iterator<File> photoIterator = FileUtils.iterateFiles(new File(sknDir), null, false);
            String resourcePath = "";
            while (photoIterator.hasNext()) {
                File onePhoto = photoIterator.next();
                String onePhotoName = onePhoto.getName();
                if (onePhotoName.startsWith("0-")) {
                    resourcePath = onePhoto.getAbsolutePath();
                    break;
                }
            }
            if (StringUtils.isNotBlank(resourcePath)) {
                SearchItemResponse response = aliPhotoSer.searchPhoto(resourcePath, 20);
                if (null != response && null != response.getAuctions()) {
                    List<SearchItemResponse.Auction> auctions = response.getAuctions();
                    if (0 < auctions.size()) {
                        for (SearchItemResponse.Auction oneAuction : auctions) {
                            String oneUrl = "/show/readAli?file=" + URLEncoder.encode("/home/downloaded_imgs-maxsort/" + oneAuction.getPicName());
                            photoViewObj.getAliPics().add(oneUrl);
                        }
                    }
                }

            }

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

        return photoViewObj;
    }


    public Object readPhotoBytes(String curDir, String skn, String order) throws IOException {
        String photoFilePath = "";
        String sknDir = curDir + "/" + skn + "/";
        Iterator<File> photoIterator = FileUtils.iterateFiles(new File(sknDir), null, false);
        Map<String, String> indexMap = new HashMap<>();
        while (photoIterator.hasNext()) {
            File onePhoto = photoIterator.next();
            String onePhotoName = onePhoto.getName();
            String[] names = StringUtils.split(onePhotoName, "-");
            if (null == names || 0 == names.length) continue;
            if (StringUtils.equals(order, names[0])) {
                photoFilePath = sknDir + onePhotoName;
                break;
            }
        }
        if (StringUtils.isNotBlank(photoFilePath))
            return FileUtils.readFileToByteArray(new File(photoFilePath));
        else
            return null;
    }

    public Object readPhotoBytes(String filePath) throws IOException {
        return FileUtils.readFileToByteArray(new File(filePath));
    }

    //获取样本信息---分页
    public List<SampleViewObj> fetchSamplesByPage(String sampleDir, int startIndex, int pageSize)  {
        List<SampleViewObj> pageList = new ArrayList<>();
        LineIterator qInfo = null;
        LineIterator pInfo = null;
        LineIterator nInfo = null;
        try {
            qInfo = FileUtils.lineIterator(new File(sampleDir+"/q.info"), "UTF-8");
            pInfo = FileUtils.lineIterator(new File(sampleDir+"/p.info"), "UTF-8");
            nInfo = FileUtils.lineIterator(new File(sampleDir+"/n.info"), "UTF-8");
            int endIndex = startIndex + pageSize - 1;
            List<String> qList = readFileByIndex(qInfo,startIndex,endIndex);
            List<String> pList = readFileByIndex(pInfo,startIndex,endIndex);
            List<String> nList = readFileByIndex(nInfo,startIndex,endIndex);
            String readUrl = "/show/readAli?file=";
            String updateFilePath = sampleDir+"/update.info";
            Set<Integer> updateSet = getUpdateFileInfo(updateFilePath);
            for(int i = 0 ; i< qList.size(); i++){
                int itemIndex = startIndex + i;//所在的行 以0为起始
                boolean flag = false;
                if(updateSet.contains(itemIndex)){
                    flag = true;
                }
                SampleViewObj sampleViewObj = new SampleViewObj(
                        readUrl+ URLEncoder.encode(qList.get(i)),
                        readUrl+ URLEncoder.encode(pList.get(i)),
                        readUrl+ URLEncoder.encode(nList.get(i)),
                        itemIndex,
                        flag);
                pageList.add(sampleViewObj);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            LineIterator.closeQuietly(qInfo);
            LineIterator.closeQuietly(pInfo);
            LineIterator.closeQuietly(nInfo);
        }
        return pageList;

    }

    //读取updateFile文件
    private Set<Integer> getUpdateFileInfo(String updateFilePath) {
        Set<Integer> set = new HashSet<>();
        LineIterator lineIterator = null;
        try {
            lineIterator = FileUtils.lineIterator(new File(updateFilePath));
            while (lineIterator.hasNext()){
                String s = lineIterator.next();
                if(StringUtils.isEmpty(s))continue;
                int value = Integer.valueOf(s);
                set.add(value);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            LineIterator.closeQuietly(lineIterator);
        }

        return set;
    }

    //读取文件
    private List<String> readFileByIndex(LineIterator lineIterator, int startIndex, int endIndex) {
        List<String> info = new ArrayList<>();
        int currentNum = -1;
        while (lineIterator.hasNext()) {
            currentNum++;
            String s = lineIterator.next();
            if(currentNum < startIndex)continue;
            if(currentNum > endIndex)break;
            if(StringUtils.isNotEmpty(s)){
                info.add(s);
            }
        }
        return info;
    }



    public void loadSampleInfo(String sampleDir) {
        LineIterator qInfo = null;
        try {
            qInfo = FileUtils.lineIterator(new File(sampleDir+"/q.info"), "UTF-8");
            samplesMap.put(sampleDir, getFileLines(qInfo));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            LineIterator.closeQuietly(qInfo);
        }
    }

    private int getFileLines(LineIterator lineIterator) {
        int count= 0;
        while (lineIterator.hasNext()) {
            count ++;
            lineIterator.next();
        }
        return count;
    }

    /**
     * 更新 update.info 文件
     *
     * @param file
     * @param content
     * @param flag --true ,当前行号写入文件 false --当前行 移出文件
     */

    public boolean modifyFile(File file, int content, boolean flag) {
       if(flag){
           try {//追加写入文件
               FileUtils.writeLines(file,"utf-8",Arrays.asList(content), true);
           } catch (IOException e) {
               e.printStackTrace();
               return false;
           }
      }/*else {//从文件中移出
           LineIterator lineIterator = null;
           try {
               lineIterator = FileUtils.lineIterator(file);
               while (lineIterator.hasNext()) {
                   int s = Integer.valueOf(lineIterator.next());
                   if (s == content) {
                       lineIterator.remove();
                       break;
                   }
               }

           } catch (IOException e) {
               e.printStackTrace();
               return false;
           }
       }*/
       return true;
    }
}