Changeset 35719


Ignore:
Timestamp:
2021-11-03T15:24:04+13:00 (5 weeks ago)
Author:
cstephen
Message:

Add support for JSON response to direct input queries. Cleanup other components.

Location:
other-projects/the-macronizer/trunk
Files:
5 added
19 edited

Legend:

Unmodified
Added
Removed
  • other-projects/the-macronizer/trunk/src/java/monogram/model/ListModel.java

    r30062 r35719  
    1212import java.util.HashSet;
    1313import java.util.Set;
    14 import util.Pool;
    1514
    1615
     
    2120public class ListModel {
    2221     
    23         private Set<String> specialConditionsList;
    24         private final String CHARSET_ENCODING = "utf-8";
    25         private final String DELIMITER = "\t";
     22    // private static final String DELIMITER = "\t";
     23
     24    private final String CHARSET_ENCODING = "utf-8";
     25    private final String path;
     26    private final Set<String> specialConditionsList;
     27
    2628   
    27         private Pool<String> pool;
    28         private final String path;
    29    
    30     public ListModel(String path, Pool<String> pool){
     29    public ListModel(String path)
     30    {
    3131        this.path = path;
    32         this.pool = pool;
    33         specialConditionsList = new HashSet();
     32        this.specialConditionsList = new HashSet<String>();
     33
    3434        init();
    35        
    3635    }
    3736   
    38     private void init() {
     37    private void init()
     38    {
    3939         BufferedReader reader = null;
    4040        try {
     
    5454    }
    5555   
    56      private void close(Reader reader) {
     56    private void close(Reader reader)
     57    {
    5758        if (reader != null) {
    5859            try {
     
    6465    }
    6566     
    66      public Set<String> getMonogramProbabilities() {
     67    public Set<String> getMonogramProbabilities()
     68    {
    6769        return specialConditionsList;
    6870    }
    6971   
    70      public boolean contains(String s){
    71          
    72          if(specialConditionsList.contains(s)){
    73              
    74              return true;
    75          }
    76          
    77          return false;
    78      }
     72    public boolean contains(String s)
     73    {
     74        if(specialConditionsList.contains(s))
     75        {
     76            return true;
     77        }
     78       
     79        return false;
     80    }
    7981   
    8082   
  • other-projects/the-macronizer/trunk/src/java/monogram/model/MonogramFactory.java

    r29855 r35719  
    1 
    21package monogram.model;
    32
     
    98 * When the pool thread is done this it clears the pool.
    109 *
    11  * @see MonogramMode
    12  *
     10 * @see MonogramModel
    1311 *
    1412 * @author University of Waikato - Te Whare Wānanga o Waikato
     
    1614 * @since   2014-11-20
    1715 */
    18 
    19 public class MonogramFactory {
    20 
     16public class MonogramFactory
     17{
    2118    private final static MonogramModel macronModel;
    2219    private final static MonogramModel doubleVowelModel;
    23    private final static ListModel blackList;
     20    private final static ListModel blackList;
    2421
    2522    static {
     
    2724        macronModel = new MonogramModel("../data/macron", pool);
    2825        doubleVowelModel = new MonogramModel("../data/doublevowel", pool);
    29         blackList = new ListModel("../data/list/blacklist.data", pool);
     26        blackList = new ListModel("../data/list/blacklist.data");
    3027        pool.clear();
    3128    }
    3229
    3330    private MonogramFactory() {
    34         //hide constructor.
     31        // Hide constructor.
    3532    }
    36 /** monogram model for macron data (/data/macron) */
     33
     34    /** monogram model for macron data (/data/macron) */
    3735    public static MonogramModel getMacronModel() {
    38      
    3936        return macronModel;
    4037    }
    41 /** monogram model for double vowel data (/data/doubleVowel) */
     38
     39    /** Monogram model for double vowel data (/data/doubleVowel) */
    4240    public static MonogramModel getDoubleVowelModel() {
    4341        return doubleVowelModel;
    4442    }
    4543   
    46     /** monogram model for black list data (/data/blacklist) */
     44    /** Monogram model for black list data (/data/blacklist) */
    4745    public static ListModel getBlackList() {
    4846        return blackList;
    49   }
     47    }
    5048}
  • other-projects/the-macronizer/trunk/src/java/monogram/plugin/PluginConfiguration.java

    r29855 r35719  
    1717    private String charsetEncoding;
    1818    private boolean preserveExistingMacrons;
     19    private boolean markupChangedWorlds;
    1920   
    2021    public File getFile() {
     
    3233    public boolean getPreserveExistingMacrons() {
    3334        return preserveExistingMacrons;
     35    }
     36
     37    public boolean getMarkupChangedWords()
     38    {
     39        return markupChangedWorlds;
    3440    }
    3541
     
    5056    }
    5157
     58    public void setMarkupChangedWords(boolean value)
     59    {
     60        markupChangedWorlds = value;
     61    }
     62
    5263    @Override
    5364    public String toString() {
  • other-projects/the-macronizer/trunk/src/java/monogram/plugin/PluginDOCX.java

    r30062 r35719  
    3535        File documentOut = new File(unzipDir, "word" + File.separator + "mi-tmp-document.xml");
    3636        XMLRestorer restorer = new XMLRestorer();
    37         restorer.restore(documentIn, "utf-8", documentOut, configuration.getPreserveExistingMacrons());
     37
     38        restorer.restore
     39        (
     40            documentIn,
     41            "utf-8",
     42            documentOut,
     43            configuration.getPreserveExistingMacrons(),
     44            configuration.getMarkupChangedWords()
     45        );
     46
    3847        //Delete the old document.xml and rename the restored document.
    3948        documentIn.delete();
  • other-projects/the-macronizer/trunk/src/java/monogram/plugin/PluginODT.java

    r30062 r35719  
    3535        File documentOut = new File(unzipDir, "mi-tmp-content.xml");
    3636        XMLRestorer restorer = new XMLRestorer();
    37         restorer.restore(documentIn, "utf-8", documentOut, configuration.getPreserveExistingMacrons());
     37
     38        restorer.restore
     39        (
     40            documentIn,
     41            "utf-8",
     42            documentOut,
     43            configuration.getPreserveExistingMacrons(),
     44            configuration.getMarkupChangedWords()
     45        );
     46       
    3847        //Delete the old document.xml and rename the restored document.
    3948        documentIn.delete();
  • other-projects/the-macronizer/trunk/src/java/monogram/plugin/PluginTXT.java

    r30062 r35719  
    1818    private File tmpdir;
    1919
    20     public PluginTXT(File tmpdir) {
     20    public PluginTXT(File tmpdir)
     21    {
    2122        this.tmpdir = tmpdir;
    2223    }
    2324
    24     public File run(PluginConfiguration configuration) throws IllegalArgumentException, IOException {
    25         if (configuration.getCharsetEncoding() == null) {
    26            
     25    public File run(PluginConfiguration configuration)
     26        throws IllegalArgumentException, IOException
     27    {
     28        if (configuration.getCharsetEncoding() == null)
     29        {
    2730            throw new IllegalArgumentException();
    2831        }
     32
    2933        final File outputFile = File.createTempFile("mi-tmp-", configuration.getFileType(), tmpdir);
    3034        final TxtRestorer restorer = new TxtRestorer();
    31         restorer.restore(configuration.getFile(), configuration.getCharsetEncoding(), outputFile, configuration.getPreserveExistingMacrons());
     35
     36        restorer.restore
     37        (
     38            configuration.getFile(),
     39            configuration.getCharsetEncoding(),
     40            outputFile,
     41            configuration.getPreserveExistingMacrons(),
     42            configuration.getMarkupChangedWords()
     43        );
     44
    3245        return outputFile;
    3346    }
  • other-projects/the-macronizer/trunk/src/java/monogram/restorer/MonogramRestorer.java

    r30062 r35719  
    88import monogram.model.ListModel;
    99import util.StringUtil;
    10 import web.servlets.DirectInput;
    1110
    1211/**
    13 * @author University of Waikato - Te Whare Wānanga o Waikato
     12 * @author University of Waikato - Te Whare Wānanga o Waikato
    1413 * @version 1.0
    15  * @since   2014-11-20
     14 * @since 2014-11-20
    1615 */
    1716public class MonogramRestorer {
     
    2120    private MonogramModel doubleVowelModel;
    2221    private ListModel blackListModel;
    23    
     22
    2423    private String previousToken;
    2524    private String currentToken;
     
    3029        macronModel = MonogramFactory.getMacronModel();
    3130        doubleVowelModel = MonogramFactory.getDoubleVowelModel();
    32     blackListModel = MonogramFactory.getBlackList();
     31        blackListModel = MonogramFactory.getBlackList();
    3332        previousToken = "";
    3433        selector = new Selector(3);
    3534    }
    3635
    37     public String restore(String token) {
    38        
    39         // Test to see if it should preserve the macrons already in the input texts. If not remove all macrons.
     36    public String restore(String token, Boolean markupChangedWords) {
     37        // Test to see if it should preserve the macrons already in the input texts. If
     38        // not remove all macrons.
    4039        if (!preserveMacrons && StringUtil.containsAccents(token)) {
    4140            token = StringUtil.removeAccents(token);
    4241        }
    43        
    44        
     42
    4543        // Make lower case copy of token.
    4644        final String tokenLowerCase = token.toLowerCase();
    47        
     45
    4846        String restoredToken = token;
    49         //If the word is in the black list return the token with no macron.
    50 if(blackListModel.contains(token)){return restoredToken;}
     47        // If the word is in the black list return the token with no macron.
     48        if (blackListModel.contains(token)) {
     49            return restoredToken;
     50        }
    5151        // Is selector > 0 it is on a sequence
    5252        if (selector.isMacronTokenSequence()) {
    5353            if (restoreByMacronModel(tokenLowerCase)) {
    54                
    55                 //Restore capitalization
     54                // Restore capitalization
    5655                restoredToken = StringUtil.copyCapitalization(token, currentToken);
    57                 // If restoredToken is not the same as token then macron/s have been add so add <mark> html. This is the yellow background around the words on the front end. 
    58                 if(!restoredToken.equals(token)){
    59                      // only add <mark> html tag if it directinput and not being output to a file.
    60                     if(DirectInput.DI){restoredToken = "<mark>"+restoredToken+"</mark> ";}
    61                 }
    62                
    63                 //if the tonken can not be restored by the MacronModel try and restor it with the DoubleVowelModel.
     56                // If restoredToken is not the same as token then macron/s have been add so add
     57                // <mark> html. This is the yellow background around the words on the front end.
     58                if (!restoredToken.equals(token)) {
     59                    // only add <mark> html tag if it directinput and not being output to a file.
     60                    if (markupChangedWords) {
     61                        restoredToken = "<mark>" + restoredToken + "</mark> ";
     62                    }
     63                }
     64
     65                // if the tonken can not be restored by the MacronModel try and restor it with
     66                // the DoubleVowelModel.
    6467            } else if (restoreByDoubleVowelModel(tokenLowerCase)) {
    6568                restoredToken = StringUtil.copyDVowelCapitalization(token, currentToken);
     
    6770                currentToken = tokenLowerCase;
    6871            }
    69         } 
     72        }
    7073        // else if it is not in a sequence
    7174        else {
     
    7376            if (restoreByDoubleVowelModel(tokenLowerCase)) {
    7477                restoredToken = StringUtil.copyDVowelCapitalization(token, currentToken);
    75             } 
     78            }
    7679            // try and restor it with the MacronModel
    7780            else if (restoreByMacronModel(tokenLowerCase)) {
    7881                restoredToken = StringUtil.copyCapitalization(token, currentToken);
    79             } 
     82            }
    8083            // Dose not need to be restored
    8184            else {
     
    8790    }
    8891
    89     // trys to restore by using the MacronModel and return boolean if it has. 
     92    // trys to restore by using the MacronModel and return boolean if it has.
    9093    private boolean restoreByMacronModel(String token) {
    91        
    92         // Test to see if token is in the Distinct Transformation hashset. 
     94
     95        // Test to see if token is in the Distinct Transformation hashset.
    9396        if (macronModel.isDistinctTransformation(token)) {
    94             //if token is in Distinct Transformation hashset make the distinct ransformation then move along the sequence.
     97            // if token is in Distinct Transformation hashset make the distinct
     98            // ransformation then move along the sequence.
    9599            currentToken = macronModel.getDistinctTransformation(token);
    96100            selector.incrementMacronTokenSequence();
    97101            return true;
    98         } 
    99         // If token is in Indistinct Transformation hashset 
     102        }
     103        // If token is in Indistinct Transformation hashset
    100104        else if (macronModel.isIndistinctTransformation(token)) {
    101105            final String[] transformations = macronModel.getIndistinctTransformation(token);
    102106            double maxProbability = Double.MIN_VALUE;
    103107            String maxToken = token;
    104             // loops all transformation and finds the one with the highest probability given the previous token.
     108            // loops all transformation and finds the one with the highest probability given
     109            // the previous token.
    105110            for (String transformation : transformations) {
    106                 //double probability = macronModel.getIndistinctProbability(transformation);
     111                // double probability = macronModel.getIndistinctProbability(transformation);
    107112                double probability = 1.0;
    108                 //if macron model has a probability for this transformation then get its probability.
     113                // if macron model has a probability for this transformation then get its
     114                // probability.
    109115                if (macronModel.containsMonogramProbability(transformation, previousToken)) {
    110116                    probability *= macronModel.getMonogramProbability(transformation, previousToken);
    111117                }
    112                
    113                 // if transformation not in macron model then try and find probability in Indistinct probability
     118
     119                // if transformation not in macron model then try and find probability in
     120                // Indistinct probability
    114121                if (probability == 1.0) {
    115122                    probability = macronModel.getIndistinctProbability(transformation);
    116123                }
    117                
    118                 //If probability is better then any before it update maxProbability and maxToken.
     124
     125                // If probability is better then any before it update maxProbability and
     126                // maxToken.
    119127                if (probability >= maxProbability) {
    120128                    maxProbability = probability;
     
    144152            String maxToken = token;
    145153            for (String transformation : transformations) {
    146                 //double probability = doubleVowelModel.getIndistinctProbability(transformation);
     154                // double probability =
     155                // doubleVowelModel.getIndistinctProbability(transformation);
    147156
    148157                double probability = 1.0;
     
    191200        }
    192201
    193         public boolean isDoubleVowelTokenSequence() {
    194             return current == 0;
    195         }
     202        // public boolean isDoubleVowelTokenSequence() {
     203        //     return current == 0;
     204        // }
    196205    }
    197206}
  • other-projects/the-macronizer/trunk/src/java/monogram/restorer/TxtRestorer.java

    r30062 r35719  
    2828    }
    2929
    30     public void restore(File inputFile, String inputCharsetEncoding, File outputFile, boolean preserveMacrons) {
     30    public void restore(File inputFile, String inputCharsetEncoding, File outputFile, boolean preserveMacrons, boolean markupChangedWords) {
    3131        MonogramRestorer restorer = new MonogramRestorer(preserveMacrons);
    3232        BufferedReader reader = null;
     
    4343                    final String nonToken = matcher.group(2);
    4444                    if (token != null) {
    45                         String restoredToken = restorer.restore(token);
     45                        String restoredToken = restorer.restore(token, markupChangedWords);
    4646                        writer.write(restoredToken);
    4747                    } else {
  • other-projects/the-macronizer/trunk/src/java/monogram/restorer/XMLRestorer.java

    r29855 r35719  
    2626    }
    2727
    28     public void restore(File inputFile, String inputCharsetEncoding, File outputFile, boolean preserveMacrons) {
     28    public void restore(File inputFile, String inputCharsetEncoding, File outputFile, boolean preserveMacrons, boolean markupChangedWords) {
    2929        MonogramRestorer restorer = new MonogramRestorer(preserveMacrons);
    3030        final StringBuilder buffer = new StringBuilder();
     
    5050                        buffer.append(reader.nextChar());
    5151                    }
    52                     final String restoredToken = restorer.restore(buffer.toString());
     52                    final String restoredToken = restorer.restore(buffer.toString(), markupChangedWords);
    5353                    writer.write(restoredToken);
    5454                } else if (CharacterUtil.isPunctuation(peek)) {
    55                     final String restoredToken = restorer.restore(String.valueOf(reader.nextChar()));
     55                    final String restoredToken = restorer.restore(String.valueOf(reader.nextChar()), markupChangedWords);
    5656                    writer.write(restoredToken);
    5757                } else {
  • other-projects/the-macronizer/trunk/src/java/util/FileUtil.java

    r29855 r35719  
    1313public class FileUtil {
    1414
    15     private final String TMP_FILE_SUFFIX = "mi-tmp-";
     15    public static final String TMP_FILE_PREFIX = "mi-tmp-";
    1616
    1717    /**
  • other-projects/the-macronizer/trunk/src/java/util/FixedLinkedList.java

    r29855 r35719  
    44import java.util.Collection;
    55import java.util.LinkedList;
    6 import java.util.List;
    76
    87/**
  • other-projects/the-macronizer/trunk/src/java/util/MySQLAccess.java

    r32755 r35719  
    1717
    1818import java.util.Properties;
    19 
    20 import java.util.List;
    2119
    2220
     
    9997            statement = connect.createStatement();
    10098
    101             int result = statement.executeUpdate("set names utf8mb4"); // should return 0 for SQL stmts that return nothing
     99            statement.executeUpdate("set names utf8mb4"); // should return 0 for SQL stmts that return nothing
    102100            System.out.println("Connected to MySQL DB " + DB_NAME);
    103101            success = true;
     
    210208
    211209    //Occurrence into
    212     private int insertOccurrence(int wordID, int timeID, int dateID) throws SQLException {
     210    private int insertOccurrence(int wordID, int timeID, int dateID)
     211        throws SQLException
     212    {
    213213        String query = "INSERT INTO Occurrences (word_id, time_id, date_id) VALUES (?,?,?)";
    214214        preparedStatement = connect.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
     
    218218
    219219        int occurrence_id = -1;
    220         try {
    221             int result = preparedStatement.executeUpdate();
     220
     221        try
     222        {
     223            preparedStatement.executeUpdate();
    222224            resultSet = preparedStatement.getGeneratedKeys();
    223225
    224             if (resultSet.next()) {
     226            if (resultSet.next())
     227            {
    225228                occurrence_id = resultSet.getInt(1);
    226229            }
    227230
    228         } catch (SQLException e) {
     231        }
     232        catch (SQLException e)
     233        {
    229234            throw e; // any other SQLException is a bad case, so we'll handle it in the caller
    230         } finally {
    231             return occurrence_id;
    232         }
     235        }
     236
     237        return occurrence_id;
    233238    }
    234239
     
    269274
    270275        int word_id = -1;
    271         try {
    272             int result = preparedStatement.executeUpdate();
     276
     277        try {
     278            preparedStatement.executeUpdate();
    273279
    274280            resultSet = preparedStatement.getGeneratedKeys();
     
    287293        } catch (SQLException e) {
    288294            throw e; // any other SQLException is a bad case, so we'll handle it in the caller
    289         } finally {
    290             return word_id;
    291         }
     295        }
     296       
     297        return word_id;
    292298    }
    293299
     
    318324
    319325        int date_id = -1;
    320         try {
    321             int result = preparedStatement.executeUpdate();
     326
     327        try {
     328            preparedStatement.executeUpdate();
    322329            resultSet = preparedStatement.getGeneratedKeys();
    323330
     
    333340        } catch (SQLException e) {
    334341            throw e; // any other SQLException is a bad case, so we'll handle it in the caller
    335         } finally {
    336             return date_id;
    337         }
     342        }
     343       
     344        return date_id;
    338345    }
    339346
     
    364371        int time_id = -1;
    365372        try {
    366             int result = preparedStatement.executeUpdate();
     373            preparedStatement.executeUpdate();
    367374            resultSet = preparedStatement.getGeneratedKeys();
    368375
     
    378385        } catch (SQLException e) {
    379386            throw e; // any other SQLException is a bad case, so we'll handle it in the caller
    380         } finally {
    381             return time_id;
    382         }
     387        }
     388       
     389        return time_id;
    383390    }
    384391
  • other-projects/the-macronizer/trunk/src/java/util/Utils4JJ.java

    r29855 r35719  
    9595     * @return Package path for the class.
    9696     */
    97     public static String getPackagePath(final Class clasz) {
     97    public static String getPackagePath(final Class<?> clasz) {
    9898        checkNotNull("clasz", clasz);
    9999        return clasz.getPackage().getName().replace('.', '/');
     
    111111     * @return Resource URL.
    112112     */
    113     public static URL getResource(final Class clasz, final String name) {
     113    public static URL getResource(final Class<?> clasz, final String name) {
    114114        checkNotNull("clasz", clasz);
    115115        checkNotNull("name", name);
     
    130130     * @return Properties.
    131131     */
    132     public static Properties loadProperties(final Class clasz,
     132    public static Properties loadProperties(final Class<?> clasz,
    133133            final String filename) {
    134134        checkNotNull("clasz", clasz);
     
    264264        checkNotNull("className", className);
    265265        try {
    266             final Class clasz = Class.forName(className);
     266            final Class<?> clasz = Class.forName(className);
    267267            return clasz.newInstance();
    268268        } catch (final ClassNotFoundException e) {
     
    281281     *            URL to add - Cannot be <code>null</code>.
    282282     */
    283     public static void addToClasspath(final String url) {
     283    public static void addToClasspath(final String url)
     284        throws IOException
     285    {
    284286        checkNotNull("url", url);
    285287        try {
     
    657659     *            URL to add - Cannot be <code>null</code>.
    658660     */
    659     public static void addToClasspath(final URL url) {
     661    public static void addToClasspath(final URL url)
     662        throws IOException
     663    {
    660664        checkNotNull("url", url);
    661665        final ClassLoader classLoader = Utils4JJ.class.getClassLoader();
     
    681685                throw new RuntimeException(e);
    682686            }
     687            finally {
     688                urlClassLoader.close();
     689            }
    683690        }
    684691    }
     
    730737     */
    731738    private static String getMethodSignature(final String returnType,
    732             final String methodName, final Class[] argTypes) {
     739            final String methodName, final Class<?>[] argTypes) {
    733740        final StringBuffer sb = new StringBuffer();
    734741        if (returnType != null) {
     
    771778     */
    772779    public static Object invoke(final Object obj, final String methodName,
    773             final Class[] argTypes, final Object[] args)
     780            final Class<?>[] argTypes, final Object[] args)
    774781            throws InvokeMethodFailedException {
    775782
     
    777784        checkNotNull("methodName", methodName);
    778785
    779         final Class[] argTypesIntern;
     786        final Class<?>[] argTypesIntern;
    780787        final Object[] argsIntern;
    781788        if (argTypes == null) {
     
    842849    }
    843850
    844     private static void checkSameLength(final Class[] argTypes,
     851    private static void checkSameLength(final Class<?>[] argTypes,
    845852            final Object[] args) {
    846853        if (argTypes.length != args.length) {
     
    904911        final ZipFile zip = new ZipFile(zipFile);
    905912        try {
    906             final Enumeration enu = zip.entries();
     913            final Enumeration<?> enu = zip.entries();
    907914            while (enu.hasMoreElements()
    908915                    && ((cancelable == null) || !cancelable.isCanceled())) {
     
    10251032     *         unchanged.
    10261033     */
    1027     public static String replaceVars(final String str, final Map vars) {
     1034    public static String replaceVars(final String str, final Map<?, ?> vars) {
    10281035
    10291036        if (str == null) {
  • other-projects/the-macronizer/trunk/src/java/web/listeners/MyHttpSessionListener.java

    r29855 r35719  
    22
    33import java.io.File;
    4 import javax.servlet.http.HttpSession;
    54import javax.servlet.http.HttpSessionEvent;
    65import javax.servlet.http.HttpSessionListener;
  • other-projects/the-macronizer/trunk/src/java/web/listeners/MyServletContextListener.java

    r30060 r35719  
    33
    44import java.io.File;
    5 import java.io.IOException;
    65import java.util.Properties;
    76import java.util.Timer;
  • other-projects/the-macronizer/trunk/src/java/web/servlets/DirectInput.java

    r31962 r35719  
    1 /*
    2  * To change this template, choose Tools | Templates
    3  * and open the template in the editor.
    4  */
    51package web.servlets;
    62
     
    139import java.io.InputStreamReader;
    1410import java.io.OutputStreamWriter;
    15 import java.io.Reader;
    16 import java.io.Writer;
     11import java.io.UnsupportedEncodingException;
     12
    1713import javax.servlet.RequestDispatcher;
    1814import javax.servlet.ServletConfig;
     
    2117import javax.servlet.http.HttpServletRequest;
    2218import javax.servlet.http.HttpServletResponse;
     19
     20import com.google.gson.Gson;
     21import com.google.gson.stream.JsonWriter;
     22
    2323import monogram.plugin.PluginConfiguration;
    2424import monogram.plugin.PluginManager;
     25
    2526import org.apache.log4j.*;
    2627
     28import util.FileUtil;
     29import util.IOUtil;
     30
    2731/**
    28  *
     32 * Represents a servlet for macronising direct text input.
    2933 * @author OEM
     34 * @version 2.0
    3035 */
    31 public class DirectInput extends HttpServlet {
    32 
    33     private final String UNEXPECTED_ERROR = "An unexpected error has occurred. Please try again or contact the web administrator if the problem persists.";
    34     private final String UTF8_ENCODING = "utf-8";
    35     public static boolean DI; // This will be used in a test in the mongramRestorer to add html to highlight the changes on the webpage output.
     36public class DirectInput extends HttpServlet
     37{
     38    private static final String UTF8_ENCODING = "utf-8";
     39
     40    //Create an instance of the logger object defined for this class in log4j.properties
     41    private static final Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName());
     42   
     43    private final Gson gsonInstance = new Gson();
     44   
    3645    private File tmpdir;
    37     //Create an instance of the Logger object created for this class in log4j.properties
    38     static Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName());
     46    private PluginManager pluginManager;
    3947
    4048    @Override
    41     public void init(ServletConfig config) throws ServletException {
     49    public void init(ServletConfig config) throws ServletException
     50    {
    4251        super.init(config);
     52
    4353        tmpdir = new File((String) config.getServletContext().getAttribute("tmpdir"));
    44     }
    45 
    46     /**
    47      * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    48      * @param request servlet request
    49      * @param response servlet response
    50      * @throws ServletException if a servlet-specific error occurs
    51      * @throws IOException if an I/O error occurs
    52      */
    53     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    54             throws ServletException, IOException {
    55     }
    56 
    57     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
     54        pluginManager = new PluginManager(tmpdir);
     55    }
     56
    5857    /**
    5958     * Handles the HTTP <code>GET</code> method.
    60      * @param request servlet request
    61      * @param response servlet response
    62      * @throws ServletException if a servlet-specific error occurs
    63      * @throws IOException if an I/O error occurs
     59     * @param request The servlet request.
     60     * @param response The servlet response.
     61     * @throws IllegalStateException if a reponse has already been committed.
     62     * @throws IOException if an I/O error occurs.
    6463     */
    6564    @Override
    6665    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    67             throws ServletException, IOException {
    68         processRequest(request, response);
     66            throws IllegalStateException, IOException
     67    {
     68        response.sendError(405); // 405 Method Not Allowed
    6969    }
    7070
    7171    /**
    7272     * Handles the HTTP <code>POST</code> method.
    73      * @param request servlet request
    74      * @param response servlet response
    75      * @throws ServletException if a servlet-specific error occurs
    76      * @throws IOException if an I/O error occurs
     73     * @param request The servlet request.
     74     * @param response The servlet response.
     75     * @throws IllegalStateException if a response has already been committed.
     76     * @throws IOException if an I/O error occurs.
     77     * @throws ServletException if a servlet-specific error occurs.
     78     * @throws UnsupportedEncodingException if the selected encoding is not supported.
    7779     */
    7880    @Override
    7981    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    80             throws ServletException, IOException {
    81         request.setCharacterEncoding("utf-8");
    82         DI = true;
     82        throws IllegalStateException, IOException, ServletException, UnsupportedEncodingException
     83    {
     84        request.setCharacterEncoding(UTF8_ENCODING);
     85
    8386        final String fragment = request.getParameter("fragment");
     87        final Boolean showAdvancedOptions = request.getParameter("options") != null && request.getParameter("options").equals("true");
     88        final Boolean shouldPreserveMacrons = request.getParameter("preserveExistingMacrons") != null && request.getParameter("preserveExistingMacrons").equals("true");
     89        final OutputType outputType = OutputType.parse(request.getParameter("o"));
     90
     91        // Note that the lang parameter might be null if the request hasn't been made from an internal JSP page
    8492        final String lang = request.getParameter("lang");
    85         final String preserveMacrons = request.getParameter("preserveExistingMacrons") != null ? request.getParameter("preserveExistingMacrons") : "false";
    86         final String options = request.getParameter("options");
    87         final String path = "/jsp" + (lang.equals("en") ? "/en" : "/mi");
    88          //Write the input to a temporary file.
    89         File file = File.createTempFile("mi-tmp-", ".txt", tmpdir);
    90         write(file, "utf-8", fragment);
     93        final String forwardPath = lang != null ? "/jsp/" + lang : "/jsp/mi";
     94
     95        try
     96        {
     97            final String restoredFragment = restoreMacrons
     98            (
     99                fragment,
     100                shouldPreserveMacrons,
     101                true //outputType == OutputType.JspRedirect
     102            );
     103
     104            if (outputType == OutputType.Json)
     105            {
     106                response.setContentType("application/json; charset=UTF-8");
     107                JsonWriter writer = gsonInstance.newJsonWriter(response.getWriter());
     108                writer.beginArray();
     109
     110                for (String element : restoredFragment.split("\\ "))
     111                {
     112                    writer.beginObject();
     113
     114                    if (element.contains("<mark>"))
     115                    {
     116                        element = element.replace("<mark>", "").replace("</mark>", "");
     117                        writer.name("macronised");
     118                        writer.value(true);
     119                    }
     120
     121                    writer.name("w");
     122                    writer.value(element);
     123
     124                    writer.endObject();
     125                }
     126               
     127                writer.endArray();
     128                writer.flush();
     129            }
     130            else
     131            {
     132                request.setAttribute("fragment2", restoredFragment);
     133                request.setAttribute("old", fragment);
     134                request.setAttribute("options", showAdvancedOptions.toString());
     135                request.setAttribute("preserveMacrons", shouldPreserveMacrons.toString());
     136   
     137                forward(forwardPath + "/main.jsp", request, response);
     138            }
     139   
     140            logger.info("Macron restoration succeeded. Input: " + fragment + " | Output: " + restoredFragment);
     141        }
     142        catch (Exception ex)
     143        {
     144            ex.printStackTrace();
     145            logger.error("Failed to restore macrons", ex);
     146
     147            switch (outputType) {
     148                case Json:
     149                    // 500 Internal Server Error
     150                    response.sendError(500, "An unexpected error has occurred. Please try again or contact the web administrator if the problem persists.");
     151                    break;
     152                default:
     153                    request.setAttribute("errorMessage", "UNEXPECTED_ERROR");
     154                    forward(forwardPath + "/error.jsp", request, response);
     155                    break;
     156            }
     157        }
     158    }
     159
     160    /**
     161     * Restores macrons on an input fragment.
     162     * @param input The input fragment to restore.
     163     * @param preserveMacrons Indicates whether existing macrons on the input should be preserved.
     164     * @return The macronised fragment.
     165     * @throws IOException
     166     * @throws UnsupportedOperationException
     167     * @throws Exception
     168     */
     169    private String restoreMacrons(String input, boolean preserveMacrons, boolean markupChangedWords)
     170        throws IOException, UnsupportedOperationException, Exception
     171    {
     172        //Write the input to a temporary file.
     173        File inputFile = File.createTempFile(FileUtil.TMP_FILE_PREFIX, ".txt", tmpdir);
     174        write(inputFile, UTF8_ENCODING, input);
    91175       
    92176        //Create a fileview
    93177        PluginConfiguration configuration = new PluginConfiguration();
    94         configuration.setFile(file);
    95         configuration.setCharsetEncoding("utf-8");
     178        configuration.setFile(inputFile);
     179        configuration.setCharsetEncoding(UTF8_ENCODING);
    96180        configuration.setFileType(".txt");
    97         configuration.setPreserveExistingMacrons(preserveMacrons.equals("true"));
     181        configuration.setPreserveExistingMacrons(preserveMacrons);
     182        configuration.setMarkupChangedWords(markupChangedWords);
     183
    98184        //Restore the file.
    99         PluginManager pluginManager = new PluginManager(tmpdir);
    100185        File restoredFile = null;
    101         try {
     186
     187        try
     188        {
    102189            restoredFile = pluginManager.run(configuration);
    103             //Read the file into a String then delete
    104             String restoredFragment = read(restoredFile, "utf-8");
    105              
    106             request.setAttribute("fragment2", restoredFragment);
    107             request.setAttribute("old", fragment);
    108             request.setAttribute("options", options);
    109             request.setAttribute("preserveMacrons", preserveMacrons);
    110             RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(path + "/main.jsp");
    111             dispatcher.forward(request, response);
    112         //Generate an "info" level logger message including the input('fragment') and output('restoredFragment')
    113         logger.info("Input:"+fragment+"Output: "+restoredFragment);
    114         } catch (Exception e) {
    115            request.setAttribute("errorMessage", UNEXPECTED_ERROR);
    116            forward(path + "/error.jsp", request, response);
    117         } finally {
    118      file.delete();
    119       if (restoredFile != null) {
    120         restoredFile.delete();
    121       }
     190            return read(restoredFile, UTF8_ENCODING).trim();
     191        }
     192        finally
     193        {
     194            inputFile.delete();
     195
     196            if (restoredFile != null)
     197            {
     198                restoredFile.delete();
     199            }
    122200        }
    123201    }
     
    125203    /**
    126204     * Forwards a request from a servlet to another resource on the server.
    127      * @param path Path to forward to.
    128      * @param request
    129      * @param response
     205     * @param path The path to forward to.
     206     * @param request The servlet request.
     207     * @param response The servlet response.
    130208     * @throws ServletException
    131209     * @throws IOException
    132210     */
    133211    private void forward(String path, HttpServletRequest request, HttpServletResponse response)
    134             throws ServletException, IOException {
     212            throws ServletException, IOException
     213    {
    135214        final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
    136215        dispatcher.forward(request, response);
     
    141220     * @param file The file to write to.
    142221     * @param fragment The String to write to the file.
    143      */
    144     private void write(File file, String charsetEncoding, String fragment) {
     222     * @throws IOException
     223     */
     224    private void write(File file, String charsetEncoding, String fragment)
     225        throws IOException
     226    {
    145227        BufferedWriter out = null;
    146         try {
     228        try
     229        {
    147230            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charsetEncoding));
    148231            out.write(fragment);
    149         } catch (IOException e) {
    150             e.printStackTrace();
    151         } finally {
    152             close(out);
     232        }
     233        finally
     234        {
     235            IOUtil.closeWriter(out);
    153236        }
    154237    }
     
    159242     * @param charsetEncoding The character set encoding of the file.
    160243     * @return The contents of the file.
    161      */
    162     private String read(File file, String charsetEncoding) {
     244     * @throws IOException
     245     */
     246    private String read(File file, String charsetEncoding)
     247        throws IOException
     248    {
    163249        final StringBuilder buffer = new StringBuilder();
    164250        BufferedReader reader = null;
    165         try {
     251
     252        try
     253        {
    166254            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charsetEncoding));
    167255            final char[] chars = new char[1024];
    168256            int numRead = 0;
    169             while ((numRead = reader.read(chars)) > -1) {
     257
     258            while ((numRead = reader.read(chars)) > -1)
     259            {
    170260                buffer.append(String.valueOf(chars, 0, numRead));
    171261            }
    172         } catch (IOException e) {
    173             e.printStackTrace();
    174         } finally {
    175             close(reader);
    176         }
     262        }
     263        finally
     264        {
     265            IOUtil.closeReader(reader);
     266        }
     267
    177268        return buffer.toString();
    178269    }
    179 
    180     /**
    181      * Close the writer.
    182      * @param writer The Writer to close.
    183      */
    184     private void close(Writer writer) {
    185         if (writer != null) {
    186             try {
    187                 writer.close();
    188             } catch (IOException e) {
    189                 e.printStackTrace();
    190             }
    191         }
    192     }
    193 
    194     /**
    195      * Close the reader.
    196      * @param reader The Reader to close.
    197      */
    198     private void close(Reader reader) {
    199         if (reader != null) {
    200             try {
    201                 reader.close();
    202             } catch (IOException e) {
    203                 e.printStackTrace();
    204             }
    205         }
    206     }
    207 
    208     /**
    209      * Returns a short description of the servlet.
    210      * @return a String containing servlet description
    211      */
    212     @Override
    213     public String getServletInfo() {
    214         return "Short description";
    215     }// </editor-fold>
    216270}
  • other-projects/the-macronizer/trunk/src/java/web/servlets/Download.java

    r29855 r35719  
    77import java.io.InputStream;
    88import java.io.PrintWriter;
    9 import javax.servlet.RequestDispatcher;
     9
    1010import javax.servlet.ServletException;
    1111import javax.servlet.ServletOutputStream;
  • other-projects/the-macronizer/trunk/src/java/web/servlets/FileUpload.java

    r31964 r35719  
    11package web.servlets;
    22
    3 import java.io.BufferedReader;
    43import java.io.File;
    5 import java.io.FileReader;
    64import java.io.IOException;
    7 import java.lang.StringBuilder;
     5import java.util.ArrayList;
    86import java.util.List;
     7
    98import javax.servlet.RequestDispatcher;
    109import javax.servlet.ServletConfig;
     
    1312import javax.servlet.http.HttpServletRequest;
    1413import javax.servlet.http.HttpServletResponse;
     14
     15import monogram.plugin.PluginConfiguration;
     16import monogram.plugin.PluginManager;
     17
    1518import org.apache.commons.fileupload.FileItem;
     19import org.apache.commons.fileupload.FileUploadException;
    1620import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    1721import org.apache.commons.fileupload.servlet.ServletFileUpload;
    18 import monogram.plugin.PluginConfiguration;
     22import org.apache.log4j.*;
     23
    1924import util.FileUtil;
    20 import monogram.plugin.PluginManager;
    21 import org.apache.log4j.*;
    2225
    2326/**
     
    2831public class FileUpload extends HttpServlet {
    2932
     33    // Create an instance of the logger object defined for the DirectInput servlet in log4j.properties.
     34    private static final Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName());
     35
    3036    private File tmpdir;
    31     private String inputFile;
    32     private String outputFile;
    33 
    34     //Create an instance of the Logger object created for this class in log4j.properties           
    35     static Logger logger = Logger.getLogger(web.servlets.DirectInput.class.getName());
     37    private PluginManager pluginManager;
    3638
    3739    @Override
    38     public void init(ServletConfig config) throws ServletException {
     40    public void init(ServletConfig config)
     41        throws ServletException
     42    {
    3943        super.init(config);
     44
    4045        tmpdir = new File((String) config.getServletContext().getAttribute("tmpdir"));
    41     }
    42 
    43     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    44             throws ServletException, IOException {
    45         //do nothing
    46     }
    47 
     46        pluginManager = new PluginManager(tmpdir);
     47    }
     48
     49    /**
     50     * Handles the HTTP <code>GET</code> method.
     51     * @param request The servlet request.
     52     * @param response The servlet response.
     53     * @throws IllegalStateException if a reponse has already been committed.
     54     * @throws IOException if an I/O error occurs.
     55     */
    4856    @Override
    4957    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    50             throws ServletException, IOException {
    51         processRequest(request, response);
     58            throws IllegalStateException, IOException
     59    {
     60        response.sendError(405); // 405 Method Not Allowed
    5261    }
    5362
     
    6170    @Override
    6271    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    63             throws ServletException, IOException {
    64         // set DI to false as this is not Directinput.
    65        DirectInput.DI = false;
    66         final Properties properties = handleRequest(request);
    67         final String address = "/jsp" + (properties.getLanguage().equals("en") ? "/en" : "/mi");
    68         final PluginConfiguration configuration = configure(properties);
    69         final PluginManager pluginManager = new PluginManager(tmpdir);
    70 
    71         if (configuration.getFile().length() == 0) {
    72             configuration.getFile().delete();
    73             request.setAttribute("errorCode", "FILE_NOT_FOUND_ERROR");
    74             forward(address + "/error.jsp", request, response);
    75             return;
    76         }
    77 
     72        throws IllegalStateException, IOException, ServletException
     73    {
     74        final OutputType outputType = OutputType.parse(request.getParameter("o")); // TODO: This probably won't work with the multipart request
     75       
    7876        File restoredFile = null;
    79         try {
     77        PluginConfiguration configuration = null;
     78        Properties properties = null;
     79        String forwardPath = "/jsp/mi";
     80
     81        try
     82        {
     83            properties = handleRequest(request);
     84            forwardPath = properties.getLanguage() != null ? "/jsp/" + properties.getLanguage() : forwardPath;
     85        }
     86        catch (Exception ex)
     87        {
     88            setError(outputType, forwardPath, "INVALID_REQUEST", request, response);
     89        }
     90
     91        try
     92        {
     93            configuration = configure(properties);
     94
     95            if (configuration.getFile().length() == 0)
     96            {
     97                configuration.getFile().delete();
     98                setError(outputType, forwardPath, "FILE_NOT_FOUND_ERROR", request, response);
     99                return;
     100            }
     101
    80102            restoredFile = pluginManager.run(configuration);
    81103            request.setAttribute("file", restoredFile);
     
    85107            request.setAttribute("preserveMacrons", properties.getPreserveExistingMacrons());
    86108            request.setAttribute("options", properties.getOptions());
    87             forward(address + "/main.jsp", request, response);
    88         outputFile = stringFromFile(restoredFile);
    89         logger.error("Output:"+outputFile);
    90         } catch (UnsupportedOperationException e) {
     109            forward(forwardPath + "/main.jsp", request, response);
     110        }
     111        catch (UnsupportedOperationException uoex)
     112        {
    91113            FileUtil.deleteFile(restoredFile);
    92             request.setAttribute("errorCode", "FILE_TYPE_NOT_SUPPORTED_ERROR");
    93             forward(address + "/error.jsp", request, response);
    94         } catch (Exception e) {
     114            logger.error("Failed to restore macrons on a file", uoex);
     115            setError(outputType, forwardPath, "FILE_TYPE_NOT_SUPPORTED_ERROR", request, response);
     116        }
     117        catch (Exception ex)
     118        {
    95119            FileUtil.deleteFile(restoredFile);
    96             request.setAttribute("errorCode", "UNEXPECTED_ERROR");
    97             forward(address + "/error.jsp", request, response);
    98         } finally {
    99             FileUtil.deleteFile(configuration.getFile());
    100         }
    101     }
    102 
     120            ex.printStackTrace();
     121            logger.error("Failed to restore macrons on a file", ex);
     122            setError(outputType, forwardPath, "UNEXPECTED_ERROR", request, response);
     123        }
     124        finally
     125        {
     126            if (configuration != null)
     127            {
     128                FileUtil.deleteFile(configuration.getFile());
     129            }
     130        }
     131    }
     132
     133    private void setError(OutputType outputType, String forwardPath, String errorCode, HttpServletRequest request, HttpServletResponse response)
     134        throws IOException, ServletException
     135    {
     136        switch (outputType) {
     137            case Json:
     138                // 500 Internal Server Error
     139                response.sendError(500, errorCode);
     140                break;
     141            default:
     142                request.setAttribute("errorMessage", errorCode);
     143                forward(forwardPath + "/error.jsp", request, response);
     144                break;
     145        }
     146    }
     147
     148    /**
     149     * Forwards a request from a servlet to another resource on the server.
     150     * @param path The path to forward to.
     151     * @param request The servlet request.
     152     * @param response The servlet response.
     153     * @throws ServletException
     154     * @throws IOException
     155     */
    103156    private void forward(String path, HttpServletRequest request, HttpServletResponse response)
    104             throws ServletException, IOException {
     157            throws ServletException, IOException
     158    {
    105159        final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
    106160        dispatcher.forward(request, response);
    107161    }
    108162
    109     private Properties handleRequest(HttpServletRequest request) {
     163    private Properties handleRequest(HttpServletRequest request)
     164        throws Exception, FileUploadException, IOException
     165    {
    110166        Properties requestData = new Properties();
    111167        DiskFileItemFactory factory = new DiskFileItemFactory();
    112168        factory.setSizeThreshold(10 * 1024 * 1024);
    113169        ServletFileUpload upload = new ServletFileUpload(factory);
    114         try {
    115             //System.out.println("looking at request parameters...");
    116             List<FileItem> items = upload.parseRequest(request);
    117 
    118             for (FileItem item : items) {
    119                 if (item.isFormField()) {
    120                     String fieldName = item.getFieldName();
    121                     String fieldValue = item.getString();
    122                     if (fieldName.equals("charsetEncoding")) {
    123                         requestData.setCharsetEncoding(fieldValue);
    124                     } else if (fieldName.equals("fileType")) {
    125                         requestData.setFileType(fieldValue);
    126                     } else if (fieldName.equals("preserveExistingMacrons")) {
    127                         requestData.setPreserveExistingMacrons(fieldValue);
    128                     } else if (fieldName.equals("lang")) {
    129                         requestData.setLanguage(fieldValue);
    130                     } else if (fieldName.equals("options")) {
    131                         requestData.setOptions(fieldValue);
    132                     }
    133                 } else {
    134                     String fileType = FileUtil.guessFileType(new File(item.getName()));
    135                     File file = File.createTempFile("mi-tmp-", fileType, tmpdir);
    136                     item.write(file);
    137                     requestData.setFile(file);
    138                     requestData.setFilename(item.getName());
    139             inputFile=stringFromFile(file);
    140             // logger.error("Input:"+logText);
     170
     171        List<FileItem> items = new ArrayList<>();
     172        for (Object element : upload.parseRequest(request)) {
     173            items.add(FileItem.class.cast(element));
     174        }
     175
     176        for (FileItem item : items)
     177        {
     178            if (item.isFormField())
     179            {
     180                String fieldName = item.getFieldName();
     181                String fieldValue = item.getString();
     182                if (fieldName.equals("charsetEncoding")) {
     183                    requestData.setCharsetEncoding(fieldValue);
     184                } else if (fieldName.equals("fileType")) {
     185                    requestData.setFileType(fieldValue);
     186                } else if (fieldName.equals("preserveExistingMacrons")) {
     187                    requestData.setPreserveExistingMacrons(fieldValue);
     188                } else if (fieldName.equals("lang")) {
     189                    requestData.setLanguage(fieldValue);
     190                } else if (fieldName.equals("options")) {
     191                    requestData.setOptions(fieldValue);
    141192                }
    142193            }
    143         } catch (Exception e) {
    144             e.printStackTrace();
    145         }
     194            else
     195            {
     196                String fileType = FileUtil.guessFileType(new File(item.getName()));
     197                File file = File.createTempFile(FileUtil.TMP_FILE_PREFIX, fileType, tmpdir);
     198                item.write(file);
     199                requestData.setFile(file);
     200                requestData.setFilename(item.getName());
     201            }
     202        }
     203
    146204        return requestData;
    147205    }
    148206   
    149     private String stringFromFile(File file)throws IOException{
    150     BufferedReader reader = new BufferedReader(new FileReader(file));
    151     String line = null;
    152     StringBuilder sb = new StringBuilder();
    153     try{
    154         while((line=reader.readLine())!=null){
    155         sb.append(line);
    156         }
    157     }
    158     catch (Exception e){
    159         e.printStackTrace();
    160     }
    161     finally{
    162         reader.close();
    163     }
    164         return sb.toString();
    165     }
     207    /* Useful for debugging file operations */
     208    // private String readStringFromFile(File file)
     209    //     throws FileNotFoundException, IOException
     210    // {
     211    //     BufferedReader reader = new BufferedReader(new FileReader(file));
     212    //     String line = null;
     213    //     StringBuilder sb = new StringBuilder();
     214
     215    //     try
     216    //     {
     217    //         while ((line=reader.readLine()) != null)
     218    //         {
     219    //             sb.append(line);
     220    //         }
     221    //     }
     222    //     finally
     223    //     {
     224    //         reader.close();
     225    //     }
     226
     227    //     return sb.toString();
     228    // }
    166229   
    167     private PluginConfiguration configure(Properties properties) {
     230    private PluginConfiguration configure(Properties properties)
     231    {
    168232        final File file = properties.getFile();
    169233        final String fileType = properties.getFileType().equals("(detect automatically)") ? FileUtil.guessFileType(file) : properties.getFileType();
     
    176240        configuration.setCharsetEncoding(charsetEncoding);
    177241        configuration.setPreserveExistingMacrons(Boolean.getBoolean(preserveExistingMacrons));
     242
    178243        return configuration;
    179244    }
    180245
    181     private class Properties {
    182 
     246    private class Properties
     247    {
    183248        private File file;
    184249        private String filename;
     
    209274        }
    210275
     276        @SuppressWarnings("unused")
    211277        public String getLanguage() {
    212278            return language;
  • other-projects/the-macronizer/trunk/web/WEB-INF/web.xml

    r29855 r35719  
    11<?xml version="1.0" encoding="UTF-8"?>
    22<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
     3    <!-- Listener Definitions -->
    34    <listener>
    45        <listener-class>web.listeners.MyHttpSessionListener</listener-class>
    56    </listener>
     7
    68    <listener>
    79        <listener-class>web.listeners.MyHttpSessionAttributeListener</listener-class>
    810    </listener>
     11
    912    <listener>
    1013        <listener-class>web.listeners.MyServletContextListener</listener-class>
    1114    </listener>
     15
     16    <!-- Filter Definitions -->
     17    <filter>
     18        <filter-name>CorsFilter</filter-name>
     19        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
     20        <init-param>
     21          <param-name>cors.allowed.origins</param-name>
     22          <!-- Allowing access from localhost:8080 for the gs3 Atea interface dev server. -->
     23          <param-value>http://localhost:8080</param-value> <!-- Separate values by a comma -->
     24        </init-param>
     25    </filter>
     26
     27    <!-- Servlet Definitions -->
     28
    1229    <servlet>
    1330        <servlet-name>FileUpload</servlet-name>
    1431        <servlet-class>web.servlets.FileUpload</servlet-class>
    1532    </servlet>
     33
    1634    <servlet>
    1735        <servlet-name>Download</servlet-name>
    1836        <servlet-class>web.servlets.Download</servlet-class>
    1937    </servlet>
     38
    2039    <servlet>
    2140        <servlet-name>DirectInput</servlet-name>
    2241        <servlet-class>web.servlets.DirectInput</servlet-class>
    2342    </servlet>
     43
    2444    <servlet>
    2545        <servlet-name>EmailServlet</servlet-name>
    2646        <servlet-class>web.servlets.Email</servlet-class>
    2747    </servlet>
     48
     49    <!-- Filter Mappings -->
     50
     51    <filter-mapping>
     52      <filter-name>CorsFilter</filter-name>
     53      <url-pattern>/*</url-pattern>
     54    </filter-mapping>
     55
     56    <!-- Servlet Mappings -->
     57
    2858    <servlet-mapping>
    2959        <servlet-name>Download</servlet-name>
    3060        <url-pattern>/jsp/servlet/Download</url-pattern>
    3161    </servlet-mapping>
     62
    3263    <servlet-mapping>
    3364        <servlet-name>FileUpload</servlet-name>
    3465        <url-pattern>/jsp/servlet/FileUpload</url-pattern>
    3566    </servlet-mapping>
     67
    3668    <servlet-mapping>
    3769        <servlet-name>DirectInput</servlet-name>
    3870        <url-pattern>/jsp/servlet/DirectInput</url-pattern>
    3971    </servlet-mapping>
     72
    4073    <servlet-mapping>
    4174        <servlet-name>EmailServlet</servlet-name>
    4275        <url-pattern>/jsp/servlet/EmailServlet</url-pattern>
    4376    </servlet-mapping>
     77
    4478    <session-config>
    4579        <session-timeout>1</session-timeout>
    4680    </session-config>
     81
    4782    <welcome-file-list>
    4883        <welcome-file>index.jsp</welcome-file>
Note: See TracChangeset for help on using the changeset viewer.