View Javadoc
1   /*
2    * Copyright (c) 2002-2016, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.test;
35  
36  import static org.junit.Assert.fail;
37  
38  import java.io.BufferedReader;
39  import java.io.ByteArrayInputStream;
40  import java.io.IOException;
41  import java.io.InputStream;
42  import java.io.InputStreamReader;
43  import java.io.StringWriter;
44  import java.io.Writer;
45  import java.math.BigInteger;
46  import java.nio.charset.StandardCharsets;
47  import java.security.SecureRandom;
48  import java.util.HashMap;
49  import java.util.Locale;
50  import java.util.Map;
51  import java.util.Random;
52  
53  import javax.servlet.http.HttpServletRequest;
54  
55  import com.fasterxml.jackson.databind.JsonNode;
56  import com.fasterxml.jackson.databind.ObjectMapper;
57  import org.xml.sax.SAXException;
58  
59  import fr.paris.lutece.portal.business.right.Right;
60  import fr.paris.lutece.portal.business.user.AdminUser;
61  import nu.validator.client.EmbeddedValidator;
62  
63  /**
64   * Utils for tests
65   */
66  public class Utils
67  {
68      private static Utils#Utils">Utils _singleton = new Utils( );
69  
70      private static final String ATTRIBUTE_ADMIN_USER = "lutece_admin_user";
71  
72      private static final Random _rand = new SecureRandom( );
73  
74      /**
75       * Register an admin user with a given right
76       * @param request the request to register the user into
77       * @param user The user
78       * @param strRight The right
79       */
80      public static void registerAdminUserWithRigth( HttpServletRequest request, AdminUser user, String strRight )
81      {
82          Map<String, Right> mapRights = new HashMap<String, Right>( );
83          Right right = new Right( );
84          right.setId( strRight );
85          mapRights.put( strRight, right );
86          user.setRights( mapRights );
87  
88          // TODO set locale user
89          user.setLocale( new Locale( "fr", "FR", "" ) );
90          registerAdminUser( request, user );
91      }
92      
93      /**
94       * Register an admin user
95       * @param request the request to register the user into
96       * @param user The user
97       */
98      public static void registerAdminUser( HttpServletRequest request, AdminUser user )
99      {
100         request.getSession( true ).setAttribute( ATTRIBUTE_ADMIN_USER, user );
101     }
102     
103     /**
104      * Gets the content of a file as a string
105      * 
106      * @param strFilename
107      *            The filename (ie: myfile.text for file stored in src/test/resources)
108      * @return The file's content
109      * @throws IOException
110      *             If an IO error occurs
111      */
112     public static String getFileContent( String strFilename ) throws IOException
113     {
114         InputStream is = _singleton.getClass( ).getResourceAsStream( "/" + strFilename );
115         InputStreamReader isr = new InputStreamReader( is );
116         BufferedReader in = new BufferedReader( isr );
117         Writer writer = new StringWriter( );
118 
119         if ( in != null )
120         {
121             char [ ] buffer = new char [ 1024];
122 
123             try
124             {
125                 int n;
126 
127                 while ( ( n = in.read( buffer ) ) != -1 )
128                 {
129                     writer.write( buffer, 0, n );
130                 }
131             }
132             finally
133             {
134                 isr.close( );
135             }
136 
137             return writer.toString( );
138         }
139         else
140         {
141             return "";
142         }
143     }
144 
145     /**
146      * Validate an html fragment, failing on warning
147      * 
148      * @param html
149      *            the fragment to validate
150      * @throws IOException
151      *             in case of error
152      * @throws SAXException
153      *             in case of error
154      * @throws AssertionError
155      *             if the fragment is invalid or produces warnings
156      */
157     public static void validateHtmlFragment( String html ) throws IOException, SAXException
158     {
159         validateHtmlFragment( html, true );
160     }
161 
162     /**
163      * Validate an html fragment
164      * 
165      * @param html
166      *            the fragment to validate
167      * @param failOnWarning
168      *            whether to fail on warning
169      * @throws IOException
170      *             in case of error
171      * @throws SAXException
172      *             in case of error
173      * @throws AssertionError
174      *             if the fragment is invalid or produces warnings
175      */
176     public static void validateHtmlFragment( String html, boolean failOnWarning ) throws IOException, SAXException
177     {
178         validateHtml( "<!DOCTYPE html><html lang=fr><title>junit</title>" + html, failOnWarning );
179     }
180 
181     /**
182      * Validate an html document
183      * 
184      * @param html
185      *            the document to validate
186      * @throws IOException
187      *             in case of error
188      * @throws SAXException
189      *             in case of error
190      * @throws AssertionError
191      *             if the document is invalid or produces warnings
192      */
193     public static void validateHtml( String html ) throws IOException, SAXException
194     {
195         validateHtml( html, true );
196     }
197 
198     /**
199      * Validate an html document
200      * 
201      * @param html
202      *            the document to validate
203      * @param failOnWarning
204      *            whether to fail on warning
205      * @throws IOException
206      *             in case of error
207      * @throws SAXException
208      *             in case of error
209      * @throws AssertionError
210      *             if the document is invalid or produces warnings
211      */
212     public static void validateHtml( String html, boolean failOnWarning ) throws IOException, SAXException
213     {
214         EmbeddedValidator validator = new EmbeddedValidator( );
215         String res = validator.validate( new ByteArrayInputStream( html.getBytes( StandardCharsets.UTF_8 ) ) );
216         ObjectMapper mapper = new ObjectMapper( );
217         JsonNode node = mapper.readTree( res );
218         JsonNode messages = node.get( "messages" );
219         if ( messages != null )
220         {
221             messages.forEach( message -> {
222                 JsonNode type = message.get( "type" );
223                 if ( type != null )
224                 {
225                     switch ( type.asText( ) )
226                     {
227                     case "error":
228                         fail( "Invalid HTML : " + message.toString( ) );
229                         break;
230                     case "info":
231                         JsonNode subtype = message.get( "subType" );
232                         if ( subtype != null && subtype.asText( ).equals( "warning" ) )
233                         {
234                             if ( failOnWarning )
235                             {
236                                 fail( "HTML with warning : " + message.toString( ) );
237                             }
238                         }
239                     default:
240                         break;
241                     }
242 
243                 }
244             } );
245         }
246     }
247 
248     /**
249      * Get a random name for use in tests
250      * 
251      * @return a random name with prefix <q>junit</q> and 128 bits of randomness
252      */
253     public static String getRandomName( )
254     {
255         return getRandomName( "junit", 128 );
256     }
257 
258     /**
259      * Get a random name for use in tests
260      * 
261      * @param strPrefix
262      *            the prefix to use
263      * @return a random name with the specified prefix and 128 bits of
264      *         randomness
265      */
266     public static String getRandomName( String strPrefix )
267     {
268         return getRandomName( strPrefix, 128 );
269     }
270 
271     /**
272      * Get a random name for use in tests
273      * 
274      * @param strPrefix
275      *            the prefix to use
276      * @param nRandomBits
277      *            the numnber of bits of randomness to use
278      * @return a random name with the specified prefix and the specified number
279      *         of bits of randomness
280      */
281     public static String getRandomName( String strPrefix, int nRandomBits )
282     {
283         BigInteger bigInt = new BigInteger( nRandomBits, _rand );
284         return strPrefix + bigInt.toString( 36 );
285     }
286 }