Project

General

Profile

Download (2.46 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2018 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.service;
10

    
11
import java.util.StringTokenizer;
12
import java.util.regex.Matcher;
13
import java.util.regex.Pattern;
14

    
15
import eu.etaxonomy.cdm.model.common.CdmBase;
16

    
17
/**
18
 * @author a.kohlbecker
19
 * @since Dec 14, 2018
20
 *
21
 */
22
public abstract class AbstractEllypsisFormatter<T extends CdmBase> implements EllypsisFormatter<T> {
23

    
24
    private static final String DELIM = " ";
25
    private String MORE = " \u2026";
26

    
27
    @Override
28
    public String ellypsis(T entity, String preserveString) {
29

    
30

    
31
        EllipsisData ed = entityEllypsis(entity, preserveString);
32
        String label = ed.truncated;
33

    
34
        return label;
35
    }
36

    
37
    protected abstract EllipsisData entityEllypsis(T entity, String filterString);
38

    
39
    public String stringEllypsis(String text, int maxCharsVisible, int minNumOfWords) {
40
        String ellipsedText = "";
41
        StringTokenizer tokenizer = new StringTokenizer(text, DELIM);
42
        int wordCount = 0;
43
        while(tokenizer.hasMoreElements()){
44
            String token = tokenizer.nextToken();
45
            if(ellipsedText.length() + token.length() + DELIM.length() <= maxCharsVisible || wordCount < minNumOfWords){
46
                ellipsedText = ellipsedText + (ellipsedText.isEmpty() ? "" : DELIM) + token;
47
            } else {
48
                break;
49
            }
50
            wordCount++;
51
        }
52
        return ellipsedText + MORE;
53
    }
54

    
55
    public String preserveString(String preserveString, String text, Pattern pattern, String textEllipsed) {
56
        String matchingSubstring = null;
57
        if(!preserveString.isEmpty()){
58
            Matcher m = pattern.matcher(text);
59
            if(m.find()){
60
                matchingSubstring = m.group(1);
61
            }
62
        }
63
        if(matchingSubstring != null && !textEllipsed.toLowerCase().contains(preserveString)){
64
            textEllipsed += matchingSubstring + MORE;
65
        }
66
        return textEllipsed;
67
    }
68

    
69
    static class EllipsisData {
70
        String original;
71
        String truncated;
72
        /**
73
         * @param original
74
         * @param truncated
75
         */
76
        public EllipsisData(String original, String truncated) {
77
            super();
78
            this.original = original;
79
            this.truncated = truncated;
80
        }
81
    }
82

    
83
}
(1-1/12)