ShowSer.java 16.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
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.*;
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) {
        List<Integer> sknDirList = new ArrayList<>();
        curDir = StringUtils.trim(curDir);
        if (curDir.endsWith("/")) {
            curDir = StringUtils.stripEnd(curDir, "/");
        }
        File file = new File(curDir);
        File[] childFiles = file.listFiles();
        List<String> childDirs = new ArrayList<>();
        for (File oneSknDir : childFiles) {
            if(!oneSknDir.isDirectory()|| oneSknDir.getName().startsWith(".")){
                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);
                photoViewObj.getSimPicFlag().add(false);
            }

            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);
                        }
                    }
                }

            }

            //读取skn.txt文件内容,展示是否被移除的标记
            String fileName =  curDir + "/" + skn + ".txt";
            File file = new File(fileName);
            if(file.exists()){//逐行读取文件
                LineIterator lineIterator =  FileUtils.lineIterator(new File(fileName), "UTF-8");
                while(lineIterator.hasNext()){
                    String content = lineIterator.next();
                    if(StringUtils.isNotEmpty(content)){
                        String imageName = StringUtils.split(content, ",")[1];
                        String indexStr = StringUtils.split(imageName, "-")[0];
                        int imageIndex = Integer.valueOf(indexStr) - 1;
                        photoViewObj.getSimPicFlag().set(imageIndex, true);//加入被移除的标记
                    }

                }
                lineIterator.close();//关闭

            }

        } 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 flag --true ,当前行号写入文件 false --当前行 移出文件
     */


    /*public synchronized  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;
            }
        };

       return true;
    }*/

    public synchronized  boolean  insertLine(File file, String content) {
            try {//追加写入文件
                FileUtils.writeLines(file,"utf-8", Arrays.asList(content), true);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        return true;
    }
    /**
     * 更新update文件
     * @param file
     * @param contentListStr
     * @param flag  ---true :表示写入文件; false: 表示从文件中删除
     * @return
     */
    public synchronized  boolean  modifyFile(File file, String contentListStr, boolean flag) {
        String[] strings = StringUtils.split(contentListStr, ",");
        if(flag){
            try {//追加写入文件
                FileUtils.writeLines(file,"utf-8",Arrays.asList(strings), true);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }else {//从文件中移出
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                //临时文件
                File tempFile = new File(file.getAbsolutePath() + ".tmp");
                PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    //写入临时文件
                    if (!line.trim().equals(strings[0])) {
                        pw.println(line);
                        pw.flush();
                    }
                }

                //关闭流
                pw.close();
                br.close();

                //


                if (!file.delete()) {
                    return false;
                }

                if (!tempFile.renameTo(file)){
//                    System.out.println("Could not rename file");
                    return false;
                  }

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

        return true;
    }


    public boolean checkFile(File file){
        if(!file.exists()){
            try {
                FileUtils.forceMkdirParent(file);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }


    /***
     * 根据图片src获取图片的名称
     */

    public String getImageNameBySrc(String removeImageSrc, String curDir, String skn) {
        String paramStr = removeImageSrc.substring( removeImageSrc.indexOf("?") + 1);
        String s[] = paramStr.split( "&");
       /* String curDir = "";
        String skn = "";*/
        String order = "";
        for( int i = 0 ; i < s.length ; i ++){
            if(StringUtils.startsWith(s[i], "order")){
                order = s[i].split("=")[1];
                break;
            }
        }


        String sknDir = curDir + "/" + skn + "/";
        Iterator<File> photoIterator = FileUtils.iterateFiles(new File(sknDir), null, false);
        String photoName = "";
        while (photoIterator.hasNext()) {
            File onePhoto = photoIterator.next();
            String onePhotoName = onePhoto.getName();
            if (onePhotoName.startsWith(order +"-")) {
                photoName = onePhotoName;
                break;

            }
        }

//        return photoName.substring(2);//头部不显示
        return photoName;
    }

    //统计文件的行
    public int  countFileLines(File file)  {
        int count = 0;
        LineIterator lineIterator = null;
        try {
            lineIterator = FileUtils.lineIterator(file, "UTF-8");
            while (lineIterator.hasNext()) {
                lineIterator.next();
                count ++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return count;

    }

    /**
     *
     * @param file
     * @param iDisplayStart --起始行
     * @param iDisplayLength --总行数(默认值是1)
     * @return
     */
    public List<ImageAndSimilarResp> getImagesPyPage(File file, Integer iDisplayStart, Integer iDisplayLength) {
        List<ImageAndSimilarResp> result = new ArrayList<>();
        try {
            int currentLine = 0;//当前行
            int readTotal = 0;//已经读取的行数
            boolean readFlag = false;
            LineIterator lineIterator =  FileUtils.lineIterator(file, "UTF-8");
            while(lineIterator.hasNext()){
                String content = lineIterator.next();
                if(iDisplayStart == currentLine){//需要解析的起始行
                    readFlag = true;
                }

                if(readFlag){
                    ImageAndSimilarResp obj =  analyzeLineContent(content);
                    result.add(obj);
                    readTotal++;//已经读取的行数
                }

                if(readTotal == iDisplayLength){
                    break;
                }
                currentLine++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  result;
    }


    private ImageAndSimilarResp analyzeLineContent(String content) {
        ImageAndSimilarResp obj = new ImageAndSimilarResp();
//        测试的
//        String[] s = StringUtils.split(content, "-");
        String[] s = StringUtils.split(content, ":");
        if(s.length == 2){//正确解析的情况
            obj.setSourceImage(s[0]);
            String[] similars = StringUtils.split(s[1],",");
            if(similars.length > 50){//前50
                String[] subStr = Arrays.copyOfRange(similars, 0 , 50);
                obj.setSimilarImages(Arrays.asList(subStr));
            }else{
                obj.setSimilarImages( Arrays.asList(similars));
            }

        }
        return obj;

    }
}