View Javadoc
1   /*
2    * Copyright (c) 2002-2014, 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.plugins.dila.web;
35  
36  import fr.paris.lutece.plugins.dila.business.stylesheet.DilaStyleSheetAction;
37  import fr.paris.lutece.plugins.dila.business.stylesheet.dto.ContentType;
38  import fr.paris.lutece.plugins.dila.business.stylesheet.dto.DilaStyleSheet;
39  import fr.paris.lutece.plugins.dila.service.DilaStyleSheetResourceIdService;
40  import fr.paris.lutece.plugins.dila.service.IContentTypeService;
41  import fr.paris.lutece.plugins.dila.service.IDilaStyleSheetActionService;
42  import fr.paris.lutece.plugins.dila.service.IDilaStyleSheetService;
43  import fr.paris.lutece.plugins.dila.utils.ListUtils;
44  import fr.paris.lutece.plugins.dila.utils.constants.DilaConstants;
45  import fr.paris.lutece.portal.business.rbac.RBAC;
46  import fr.paris.lutece.portal.service.admin.AccessDeniedException;
47  import fr.paris.lutece.portal.service.fileupload.FileUploadService;
48  import fr.paris.lutece.portal.service.i18n.I18nService;
49  import fr.paris.lutece.portal.service.message.AdminMessage;
50  import fr.paris.lutece.portal.service.message.AdminMessageService;
51  import fr.paris.lutece.portal.service.rbac.RBACService;
52  import fr.paris.lutece.portal.service.spring.SpringContextService;
53  import fr.paris.lutece.portal.service.template.AppTemplateService;
54  import fr.paris.lutece.portal.service.util.AppLogService;
55  import fr.paris.lutece.portal.service.util.AppPathService;
56  import fr.paris.lutece.portal.service.util.AppPropertiesService;
57  import fr.paris.lutece.portal.web.admin.PluginAdminPageJspBean;
58  import fr.paris.lutece.portal.web.constants.Parameters;
59  import fr.paris.lutece.portal.web.upload.MultipartHttpServletRequest;
60  import fr.paris.lutece.portal.web.util.LocalizedPaginator;
61  import fr.paris.lutece.util.ReferenceItem;
62  import fr.paris.lutece.util.ReferenceList;
63  import fr.paris.lutece.util.filesystem.FileSystemUtil;
64  import fr.paris.lutece.util.html.HtmlTemplate;
65  import fr.paris.lutece.util.html.Paginator;
66  import fr.paris.lutece.util.sort.AttributeComparator;
67  
68  import java.io.ByteArrayInputStream;
69  import java.io.File;
70  import java.io.FileOutputStream;
71  import java.io.IOException;
72  import java.io.OutputStream;
73  import java.util.Collections;
74  import java.util.HashMap;
75  import java.util.List;
76  import java.util.Map;
77  
78  import javax.servlet.http.HttpServletRequest;
79  import javax.servlet.http.HttpServletResponse;
80  import javax.xml.parsers.ParserConfigurationException;
81  import javax.xml.parsers.SAXParser;
82  import javax.xml.parsers.SAXParserFactory;
83  
84  import org.apache.commons.fileupload.FileItem;
85  import org.apache.commons.io.IOUtils;
86  import org.apache.commons.lang.StringUtils;
87  import org.xml.sax.InputSource;
88  import org.xml.sax.SAXException;
89  
90  
91  /**
92   * This class provides the user interface to manage StyleSheet of DILA features
93   */
94  public class StyleSheetJspBean extends PluginAdminPageJspBean
95  {
96      // Right
97      public static final String RIGHT_MANAGE_STYLESHEET = "DILA_STYLESHEET_MANAGEMENT";
98  
99      /** The serial ID */
100     private static final long serialVersionUID = 2933032349706505918L;
101 
102     // Constants
103     private int _nItemsPerPage;
104     private int _nDefaultItemsPerPage;
105     private String _strCurrentPageIndex;
106 
107     // Services
108     private IContentTypeService _typeContenuService = SpringContextService.getBean( "contentTypeService" );
109     private IDilaStyleSheetService _dilaStyleSheetService = SpringContextService.getBean( "dilaStyleSheetService" );
110     private IDilaStyleSheetActionService _dilaStyleSheetActionService = SpringContextService
111             .getBean( "dilaStyleSheetActionService" );
112 
113     /**
114      * Displays the stylesheets list
115      * @return the html code for displaying the stylesheets list
116      * @param request The request
117      */
118     public String getManageStyleSheet( HttpServletRequest request )
119     {
120         // Parameters processing
121         String strContentTypeId = request.getParameter( DilaConstants.MARK_CONTENT_TYPE_ID );
122         strContentTypeId = ( strContentTypeId != null ) ? strContentTypeId : "0";
123 
124         String strStyleSheetName = request.getParameter( DilaConstants.MARK_NAME );
125 
126         int nContentTypeId = Integer.parseInt( strContentTypeId );
127 
128         // Get the list of ContentType
129         ReferenceList contentTypeList = ListUtils.toReferenceList( _typeContenuService.getContentTypes( ), "id",
130                 "label", I18nService.getLocalizedString( DilaConstants.LABEL_WITHOUT_TYPE, getLocale( ) ) );
131         ReferenceItem itemAll = new ReferenceItem( );
132         itemAll.setCode( "0" );
133         itemAll.setName( I18nService.getLocalizedString( DilaConstants.LABEL_ALL, getLocale( ) ) );
134         contentTypeList.add( itemAll );
135 
136         // Get the list of style sheet with filters
137         List<DilaStyleSheet> listStyleSheets = _dilaStyleSheetService.getDilaStyleSheetList( nContentTypeId,
138                 strStyleSheetName );
139 
140         // Orders the list of result and add pagination
141         String strSortedAttributeName = request.getParameter( Parameters.SORTED_ATTRIBUTE_NAME );
142         String strAscSort = null;
143 
144         if ( strSortedAttributeName != null )
145         {
146             strAscSort = request.getParameter( Parameters.SORTED_ASC );
147 
148             boolean bIsAscSort = Boolean.parseBoolean( strAscSort );
149 
150             Collections.sort( listStyleSheets, new AttributeComparator( strSortedAttributeName, bIsAscSort ) );
151         }
152 
153         _nDefaultItemsPerPage = AppPropertiesService.getPropertyInt( DilaConstants.PROPERTY_STYLESHEETS_PER_PAGE, 50 );
154         _strCurrentPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex );
155         _nItemsPerPage = Paginator.getItemsPerPage( request, Paginator.PARAMETER_ITEMS_PER_PAGE, _nItemsPerPage,
156                 _nDefaultItemsPerPage );
157 
158         String strURL = getHomeUrl( request );
159 
160         if ( strSortedAttributeName != null )
161         {
162             strURL += ( "?" + Parameters.SORTED_ATTRIBUTE_NAME + "=" + strSortedAttributeName );
163         }
164 
165         if ( strAscSort != null )
166         {
167             strURL += ( "&" + Parameters.SORTED_ASC + "=" + strAscSort );
168         }
169 
170         LocalizedPaginator<DilaStyleSheet> paginator = new LocalizedPaginator<DilaStyleSheet>( listStyleSheets,
171                 _nItemsPerPage, strURL, Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex, getLocale( ) );
172 
173         // Permissions
174         Map<String, Object> model = new HashMap<String, Object>( );
175 
176         if ( RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID,
177                 DilaStyleSheetResourceIdService.PERMISSION_CREATE_STYLESHEET, getUser( ) ) )
178         {
179             model.put( DilaConstants.MARK_PERMISSION_CREATE_STYLESHEET, true );
180         }
181         else
182         {
183             model.put( DilaConstants.MARK_PERMISSION_CREATE_STYLESHEET, false );
184         }
185 
186         List<DilaStyleSheetAction> listActions;
187         listActions = _dilaStyleSheetActionService.selectActions( getLocale( ) );
188 
189         List<DilaStyleSheetAction> listActionsForStyleSheet;
190 
191         for ( DilaStyleSheet styleSheet : paginator.getPageItems( ) )
192         {
193             listActionsForStyleSheet = (List<DilaStyleSheetAction>) RBACService.getAuthorizedActionsCollection(
194                     listActions, styleSheet, getUser( ) );
195             styleSheet.setListActions( listActionsForStyleSheet );
196         }
197 
198         // Get the html with freemarker
199         model.put( DilaConstants.MARK_CONTENT_TYPE_ID, strContentTypeId );
200         model.put( DilaConstants.MARK_NAME, strStyleSheetName );
201         model.put( DilaConstants.MARK_NB_ITEMS_PER_PAGE, "" + _nItemsPerPage );
202         model.put( DilaConstants.MARK_PAGINATOR, paginator );
203         model.put( DilaConstants.MARK_STYLESHEET_LIST, paginator.getPageItems( ) );
204         model.put( DilaConstants.MARK_CONTENT_TYPE_LIST, contentTypeList );
205         model.put( DilaConstants.MARK_PERMISSION_MODIFY_STYLESHEET,
206                 DilaStyleSheetResourceIdService.PERMISSION_MODIFY_STYLESHEET );
207         model.put( DilaConstants.MARK_PERMISSION_DELETE_STYLESHEET,
208                 DilaStyleSheetResourceIdService.PERMISSION_DELETE_STYLESHEET );
209         model.put( DilaConstants.MARK_PERMISSION_VIEW_STYLESHEET,
210                 DilaStyleSheetResourceIdService.PERMISSION_VIEW_STYLESHEET );
211 
212         HtmlTemplate template = AppTemplateService.getTemplate( DilaConstants.TEMPLATE_MANAGE_STYLESHEETS,
213                 getLocale( ), model );
214 
215         return getAdminPage( template.getHtml( ) );
216     }
217 
218     /**
219      * Returns the create form of a new dila stylesheet with the upload field
220      * @param request the http request
221      * @return the html code for the create form of a new stylesheet
222      * @throws AccessDeniedException AccessDeniedException
223      */
224     public String getSaveStyleSheet( HttpServletRequest request ) throws AccessDeniedException
225     {
226         Map<String, Object> model = new HashMap<String, Object>( );
227 
228         String strStyleSheetId = request.getParameter( DilaConstants.MARK_STYLESHEET_ID );
229 
230         // Modification
231         int nIdStylesheet = 0;
232 
233         if ( StringUtils.isNotEmpty( strStyleSheetId ) )
234         {
235             if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, strStyleSheetId,
236                     DilaStyleSheetResourceIdService.PERMISSION_MODIFY_STYLESHEET, getUser( ) ) )
237             {
238                 return getManageStyleSheet( request );
239             }
240 
241             try
242             {
243                 nIdStylesheet = Integer.parseInt( strStyleSheetId );
244             }
245             catch ( NumberFormatException e )
246             {
247                 nIdStylesheet = -1;
248             }
249 
250             if ( nIdStylesheet > 0 )
251             {
252                 DilaStyleSheet styleSheet = _dilaStyleSheetService.findByPrimaryKey( nIdStylesheet );
253                 styleSheet.setListActions( (List<DilaStyleSheetAction>) RBACService.getAuthorizedActionsCollection(
254                         _dilaStyleSheetActionService.selectActions( getLocale( ) ), styleSheet, getUser( ) ) );
255                 model.put( DilaConstants.MARK_STYLESHEET, styleSheet );
256                 model.put( DilaConstants.MARK_PERMISSION_VIEW_STYLESHEET,
257                         DilaStyleSheetResourceIdService.PERMISSION_VIEW_STYLESHEET );
258             }
259         }
260         else if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID,
261                 DilaStyleSheetResourceIdService.PERMISSION_CREATE_STYLESHEET, getUser( ) ) )
262         {
263             return getManageStyleSheet( request );
264         }
265 
266         //Getting content types
267         ReferenceList contentTypeList = ListUtils.toReferenceList(
268                 _typeContenuService.getContentTypesWithoutAssociatedStyleSheet( nIdStylesheet ), "id", "label",
269                 I18nService.getLocalizedString( DilaConstants.LABEL_WITHOUT_TYPE, getLocale( ) ) );
270         model.put( DilaConstants.MARK_CONTENT_TYPE_LIST, contentTypeList );
271 
272         HtmlTemplate template = AppTemplateService.getTemplate( DilaConstants.TEMPLATE_CREATE_STYLESHEET, getLocale( ),
273                 model );
274 
275         return getAdminPage( template.getHtml( ) );
276     }
277 
278     /**
279      * Processes the creation form of a new dila stylesheet by recovering the
280      * parameters
281      * in the http request
282      * @param request the http request
283      * @return The Jsp URL of the process result
284      * @throws AccessDeniedException AccessDeniedException
285      */
286     public String doSaveStyleSheet( HttpServletRequest request ) throws AccessDeniedException
287     {
288         DilaStyleSheet stylesheet = new DilaStyleSheet( );
289 
290         if ( !( request instanceof MultipartHttpServletRequest ) )
291         {
292             throw new AssertionError( "Unexpected type: " + request );
293         }
294 
295         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
296 
297         // Modification
298         String strIdStylesheet = multipartRequest.getParameter( DilaConstants.MARK_STYLESHEET_ID );
299 
300         if ( StringUtils.isNotEmpty( strIdStylesheet ) )
301         {
302             if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, strIdStylesheet,
303                     DilaStyleSheetResourceIdService.PERMISSION_MODIFY_STYLESHEET, getUser( ) ) )
304             {
305                 throw new AccessDeniedException( "User is not authrorized to access this page." );
306             }
307 
308             Integer nId;
309 
310             try
311             {
312                 nId = Integer.parseInt( strIdStylesheet );
313             }
314             catch ( NumberFormatException e )
315             {
316                 nId = -1;
317             }
318 
319             if ( nId > 0 )
320             {
321                 stylesheet.setId( nId );
322             }
323         }
324         else if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID,
325                 DilaStyleSheetResourceIdService.PERMISSION_CREATE_STYLESHEET, getUser( ) ) )
326         {
327             throw new AccessDeniedException( "User is not authrorized to access this page." );
328         }
329 
330         // creation or modification
331         boolean bIsModification = ( stylesheet.getId( ) > 0 ) ? true : false;
332 
333         String strErrorUrl = getData( multipartRequest, stylesheet, bIsModification );
334 
335         if ( strErrorUrl != null )
336         {
337             return strErrorUrl;
338         }
339         else if ( bIsModification )
340         {
341             // Remove the old local file if change
342             if ( stylesheet.getSource( ) != null )
343             {
344                 removeOldLocalStyleSheet( stylesheet.getId( ) );
345             }
346 
347             // Update the stylesheet in database
348             _dilaStyleSheetService.update( stylesheet );
349         }
350         else
351         {
352             //insert in the table stylesheet of the database
353             _dilaStyleSheetService.create( stylesheet );
354         }
355 
356         //create a local file
357         if ( stylesheet.getSource( ) != null )
358         {
359             localStyleSheetFile( stylesheet );
360         }
361 
362         //Displays the list of the stylesheet files
363         return getHomeUrl( request );
364     }
365 
366     /**
367      * Returns the confirmation message to delete a dila stylesheet.
368      * 
369      * @param request The Http request
370      * @return the html code message
371      * @throws AccessDeniedException AccessDeniedException
372      */
373     public String getDeleteStyleSheet( HttpServletRequest request ) throws AccessDeniedException
374     {
375         String strStylesheetId = request.getParameter( DilaConstants.MARK_STYLESHEET_ID );
376 
377         if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, strStylesheetId,
378                 DilaStyleSheetResourceIdService.PERMISSION_DELETE_STYLESHEET, getUser( ) ) )
379         {
380             throw new AccessDeniedException( "User is not authrorized to access this page." );
381         }
382 
383         int nIdStylesheet = 0;
384 
385         try
386         {
387             nIdStylesheet = Integer.parseInt( strStylesheetId );
388         }
389         catch ( NumberFormatException e )
390         {
391             return AdminMessageService.getMessageUrl( request, DilaConstants.MESSAGE_ERROR_OCCUR,
392                     AdminMessage.TYPE_STOP );
393         }
394 
395         Map<String, Object> urlParam = new HashMap<String, Object>( );
396         urlParam.put( DilaConstants.MARK_STYLESHEET_ID, nIdStylesheet );
397 
398         return AdminMessageService.getMessageUrl( request, DilaConstants.MESSAGE_CONFIRMATION_DELETE_STYLESHEET, null,
399                 DilaConstants.MESSAGE_TITLE_DELETE_STYLESHEET, DilaConstants.JSP_DELETE_STYLESHEET, "_self",
400                 AdminMessage.TYPE_CONFIRMATION, urlParam, DilaConstants.JSP_MANAGE_STYLESHEET );
401     }
402 
403     /**
404      * Delete a dila styleSheet.
405      * 
406      * @param request The Http request
407      * @return url return
408      * @throws AccessDeniedException AccessDeniedException
409      */
410     public String doDeleteStyleSheet( HttpServletRequest request ) throws AccessDeniedException
411     {
412         String strStyleSheetId = request.getParameter( DilaConstants.MARK_STYLESHEET_ID );
413 
414         if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, strStyleSheetId,
415                 DilaStyleSheetResourceIdService.PERMISSION_DELETE_STYLESHEET, getUser( ) ) )
416         {
417             throw new AccessDeniedException( "User is not authrorized to access this page." );
418         }
419 
420         if ( !StringUtils.isNumeric( strStyleSheetId ) )
421         {
422             return AdminMessageService.getMessageUrl( request, DilaConstants.MESSAGE_ERROR_OCCUR,
423                     AdminMessage.TYPE_STOP );
424         }
425 
426         Integer nIdStyleSheet = Integer.parseInt( strStyleSheetId );
427         removeOldLocalStyleSheet( nIdStyleSheet );
428         _dilaStyleSheetService.doDeleteStyleSheet( nIdStyleSheet );
429 
430         return AppPathService.getBaseUrl( request ) + DilaConstants.JSP_MANAGE_STYLESHEET;
431     }
432 
433     /**
434      * Reads dila stylesheet's data
435      * @param multipartRequest The request
436      * @param stylesheet The style sheet
437      * @param bIsModification If is modification
438      * @return An error message URL or null if no error
439      */
440     private String getData( MultipartHttpServletRequest multipartRequest, DilaStyleSheet stylesheet,
441             boolean bIsModification )
442     {
443         String strErrorUrl = null;
444         String strName = multipartRequest.getParameter( DilaConstants.MARK_NAME );
445         String strContentTypeId = multipartRequest.getParameter( DilaConstants.MARK_CONTENT_TYPE_ID );
446 
447         FileItem fileSource = multipartRequest.getFile( DilaConstants.MARK_SOURCE );
448         byte[] baXslSource = fileSource.get( );
449         String strFilename = FileUploadService.getFileNameOnly( fileSource );
450 
451         boolean modification = StringUtils
452                 .isNotEmpty( multipartRequest.getParameter( DilaConstants.MARK_STYLESHEET_ID ) );
453 
454         // Mandatory fields
455         boolean isMandatoryOk = true;
456 
457         if ( strName.equals( "" ) || ( strFilename == null ) || strFilename.equals( "" ) )
458         {
459             if ( !modification )
460             {
461                 isMandatoryOk = false;
462             }
463         }
464 
465         if ( baXslSource == null )
466         {
467             isMandatoryOk = false;
468         }
469 
470         if ( !isMandatoryOk )
471         {
472             return AdminMessageService.getMessageUrl( multipartRequest, DilaConstants.MESSAGE_MANDATORY_FIELD,
473                     AdminMessage.TYPE_STOP );
474         }
475 
476         //test the existence of content type already associated with this stylesheet except if there's no type
477         int nContentTypeId = Integer.parseInt( strContentTypeId );
478 
479         if ( nContentTypeId > 0 )
480         {
481             int nCount = _dilaStyleSheetService.getStyleSheetNbPerTypeContenu( nContentTypeId );
482 
483             // Do not create a stylesheet of there is already one
484             DilaStyleSheet oldStylesheet = _dilaStyleSheetService.findByPrimaryKey( stylesheet.getId( ) );
485 
486             if ( ( ( nCount >= 1 ) && ( stylesheet.getId( ) == 0 ) )
487                     || ( ( oldStylesheet != null ) && ( ( oldStylesheet.getContentType( ).getId( ) != nContentTypeId ) && ( nCount >= 1 ) ) ) )
488             {
489                 return AdminMessageService.getMessageUrl( multipartRequest,
490                         DilaConstants.MESSAGE_STYLESHEET_ALREADY_EXISTS, AdminMessage.TYPE_STOP );
491             }
492         }
493 
494         // Check the XML validity of the XSL stylesheet
495         String isValid = isValid( baXslSource );
496 
497         if ( isValid != null )
498         {
499             Object[] args = { isValid };
500 
501             return AdminMessageService.getMessageUrl( multipartRequest, DilaConstants.MESSAGE_STYLESHEET_NOT_VALID,
502                     args, AdminMessage.TYPE_STOP );
503         }
504 
505         stylesheet.setDescription( strName );
506 
507         ContentType contentType = new ContentType( );
508         contentType.setId( nContentTypeId );
509         stylesheet.setContentType( contentType );
510         stylesheet.setSource( baXslSource );
511 
512         // get existing stylesheet
513         DilaStyleSheet dilaStyleSheet = null;
514 
515         if ( bIsModification )
516         {
517             dilaStyleSheet = _dilaStyleSheetService.findByPrimaryKey( stylesheet.getId( ) );
518         }
519 
520         boolean isNewFileModification = ( dilaStyleSheet != null )
521                 && !strFilename.equalsIgnoreCase( dilaStyleSheet.getFile( ) );
522 
523         // creation : test if file already exists
524         // modification : if new file, test if file already exists
525         if ( !bIsModification || isNewFileModification )
526         {
527             File file = new File( AppPathService.getPath( DilaConstants.PROPERTY_PATH_XSL ) + strFilename );
528 
529             if ( file.exists( ) && file.isFile( ) )
530             {
531                 return AdminMessageService.getMessageUrl( multipartRequest,
532                         DilaConstants.MESSAGE_STYLESHEET_NAME_EXISTS, AdminMessage.TYPE_STOP );
533             }
534         }
535 
536         stylesheet.setFile( strFilename );
537 
538         return strErrorUrl;
539     }
540 
541     /**
542      * Use parsing for validate the modify xsl file
543      * 
544      * @param baXslSource The XSL source
545      * @return the message exception when the validation is false
546      */
547     private String isValid( byte[] baXslSource )
548     {
549         String strError = null;
550 
551         try
552         {
553             SAXParserFactory factory = SAXParserFactory.newInstance( );
554             SAXParser analyzer = factory.newSAXParser( );
555             InputSource is = new InputSource( new ByteArrayInputStream( baXslSource ) );
556             analyzer.getXMLReader( ).parse( is );
557         }
558         catch ( SAXException e )
559         {
560             strError = e.getMessage( );
561         }
562         catch ( ParserConfigurationException e )
563         {
564             strError = e.getMessage( );
565         }
566         catch ( IOException e )
567         {
568             strError = e.getMessage( );
569         }
570 
571         return strError;
572     }
573 
574     /**
575      * Create and Update the local download file
576      * 
577      * @param stylesheet The dila style sheet
578      */
579     private void localStyleSheetFile( DilaStyleSheet stylesheet )
580     {
581         String strPathStyleSheet = AppPathService.getPath( DilaConstants.PROPERTY_PATH_XSL ) + stylesheet.getFile( );
582         FileOutputStream fos = null;
583 
584         try
585         {
586             File file = new File( strPathStyleSheet );
587 
588             if ( file.exists( ) )
589             {
590                 if ( !file.delete( ) )
591                 {
592                     AppLogService.error( "Erreur lors de la suppression du fichier" );
593                 }
594             }
595 
596             fos = new FileOutputStream( file );
597             fos.write( stylesheet.getSource( ) );
598             fos.flush( );
599         }
600         catch ( IOException e )
601         {
602             AppLogService.error( e.getMessage( ), e );
603         }
604         finally
605         {
606             IOUtils.closeQuietly( fos );
607         }
608     }
609 
610     /**
611      * remove the xsl file from the tmp directory
612      * @param nId the identifier of the file
613      */
614     private void removeOldLocalStyleSheet( int nId )
615     {
616         //Remove the file which been modify
617         DilaStyleSheet stylesheet = _dilaStyleSheetService.findByPrimaryKey( nId );
618         String strPathStyleSheet = AppPathService.getPath( DilaConstants.PROPERTY_PATH_XSL );
619         String strOldFileName = stylesheet.getFile( );
620         String strOldFilePath = strPathStyleSheet + strOldFileName;
621         File oldFile = new File( strOldFilePath );
622 
623         if ( oldFile.exists( ) )
624         {
625             if ( !oldFile.delete( ) )
626             {
627                 AppLogService.error( "Erreur lors de la suppression du fichier" );
628             }
629         }
630     }
631 
632     /**
633      * write in the http response the value of the response whose identifier is
634      * specified in the request if there is no response return a error
635      * @param request the http request
636      * @param response The http response
637      * @return The URL to go after performing the action
638      * @throws AccessDeniedException AccessDeniedException
639      */
640     public String doDownloadStyleSheet( HttpServletRequest request, HttpServletResponse response )
641             throws AccessDeniedException
642     {
643         String strIdStyleSheet = request.getParameter( DilaConstants.MARK_STYLESHEET_ID );
644 
645         if ( !RBACService.isAuthorized( DilaStyleSheet.RESOURCE_TYPE, strIdStyleSheet,
646                 DilaStyleSheetResourceIdService.PERMISSION_VIEW_STYLESHEET, getUser( ) ) )
647         {
648             throw new AccessDeniedException( "User is not authrorized to access this page." );
649         }
650 
651         int nIdStyleSheet = -1;
652 
653         if ( strIdStyleSheet != null )
654         {
655             try
656             {
657                 nIdStyleSheet = Integer.parseInt( strIdStyleSheet );
658             }
659             catch ( NumberFormatException ne )
660             {
661                 AppLogService.error( ne );
662             }
663         }
664 
665         DilaStyleSheet stylesheet = _dilaStyleSheetService.findByPrimaryKey( nIdStyleSheet );
666 
667         response.setHeader( "Content-Disposition", "attachment ;filename=\"" + stylesheet.getFile( ) + "\"" );
668 
669         response.setCharacterEncoding( "UTF-8" );
670 
671         String strMimeType = FileSystemUtil.getMIMEType( stylesheet.getFile( ) );
672 
673         if ( strMimeType != null )
674         {
675             response.setContentType( strMimeType );
676         }
677         else
678         {
679             response.setContentType( "application/octet-stream" );
680         }
681 
682         response.setHeader( "Pragma", "public" );
683         response.setHeader( "Expires", "0" );
684         response.setHeader( "Cache-Control", "must-revalidate,post-check=0,pre-check=0" );
685 
686         try
687         {
688             byte[] byteFileOutPut = _dilaStyleSheetService.getSourceByStyleSheetId( nIdStyleSheet );
689 
690             if ( byteFileOutPut != null )
691             {
692                 response.setContentLength( byteFileOutPut.length );
693 
694                 OutputStream os = response.getOutputStream( );
695                 os.write( byteFileOutPut );
696                 os.close( );
697             }
698         }
699         catch ( IOException e )
700         {
701             AppLogService.error( e );
702         }
703 
704         return AppPathService.getBaseUrl( request ) + DilaConstants.JSP_MANAGE_STYLESHEET;
705     }
706 }