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.plugins.htmldocs.web;
35  
36  import fr.paris.lutece.plugins.htmldocs.business.DocContent;
37  import fr.paris.lutece.plugins.htmldocs.business.DocContentHome;
38  import fr.paris.lutece.plugins.htmldocs.business.HtmlDoc;
39  import fr.paris.lutece.plugins.htmldocs.business.HtmlDocHome;
40  import fr.paris.lutece.plugins.htmldocs.business.HtmldocSearchFilter;
41  import fr.paris.lutece.plugins.htmldocs.business.Tag;
42  import fr.paris.lutece.plugins.htmldocs.business.TagHome;
43  import fr.paris.lutece.plugins.htmldocs.business.portlet.HtmlDocPublication;
44  import fr.paris.lutece.plugins.htmldocs.business.portlet.HtmlDocPublicationHome;
45  import fr.paris.lutece.plugins.htmldocs.service.HtmlDocService;
46  import fr.paris.lutece.plugins.htmldocs.service.docsearch.HtmlDocSearchService;
47  import fr.paris.lutece.portal.service.message.AdminMessage;
48  import fr.paris.lutece.portal.service.message.AdminMessageService;
49  import fr.paris.lutece.portal.util.mvc.admin.annotations.Controller;
50  import fr.paris.lutece.portal.util.mvc.commons.annotations.Action;
51  import fr.paris.lutece.portal.util.mvc.commons.annotations.View;
52  import fr.paris.lutece.portal.web.resource.ExtendableResourcePluginActionManager;
53  import fr.paris.lutece.portal.web.upload.MultipartHttpServletRequest;
54  import fr.paris.lutece.portal.web.util.LocalizedPaginator;
55  import fr.paris.lutece.util.html.Paginator;
56  import fr.paris.lutece.util.json.JsonResponse;
57  import fr.paris.lutece.util.json.JsonUtil;
58  import fr.paris.lutece.util.sort.AttributeComparator;
59  import fr.paris.lutece.util.url.UrlItem;
60  import fr.paris.lutece.util.ReferenceItem;
61  import fr.paris.lutece.util.ReferenceList;
62  import fr.paris.lutece.portal.service.resource.ExtendableResourceRemovalListenerService;
63  import fr.paris.lutece.portal.service.util.AppLogService;
64  import fr.paris.lutece.portal.service.util.AppPathService;
65  import fr.paris.lutece.portal.service.util.AppPropertiesService;
66  import fr.paris.lutece.portal.service.admin.AdminUserService;
67  import fr.paris.lutece.portal.business.user.AdminUser;
68  
69  import java.util.ArrayList;
70  import java.util.Collections;
71  import java.util.HashMap;
72  import java.util.List;
73  import java.util.Locale;
74  import java.util.Map;
75  import java.io.ByteArrayInputStream;
76  import java.io.StringWriter;
77  
78  import javax.servlet.http.HttpServletRequest;
79  import javax.xml.transform.OutputKeys;
80  import javax.xml.transform.TransformerFactory;
81  import javax.xml.transform.sax.SAXTransformerFactory;
82  import javax.xml.transform.sax.TransformerHandler;
83  import javax.xml.transform.stream.StreamResult;
84  
85  import org.outerj.daisy.diff.HtmlCleaner;
86  import org.outerj.daisy.diff.html.HTMLDiffer;
87  import org.outerj.daisy.diff.html.HtmlSaxDiffOutput;
88  import org.outerj.daisy.diff.html.TextNodeComparator;
89  import org.outerj.daisy.diff.html.dom.DomTreeBuilder;
90  import org.xml.sax.InputSource;
91  import org.apache.commons.fileupload.FileItem;
92  import org.apache.commons.lang.ArrayUtils;
93  import org.apache.commons.lang.StringUtils;
94  
95  /**
96   * This class provides the user interface to manage HtmlDoc features ( manage, create, modify, remove )
97   */
98  @Controller( controllerJsp = "ManageHtmlDocs.jsp", controllerPath = "jsp/admin/plugins/htmldocs/", right = "HTMLDOCS_MANAGEMENT" )
99  public class HtmlDocJspBean extends ManageHtmldocsJspBean
100 {
101     // Templates
102     private static final String TEMPLATE_MANAGE_HTMLDOCS = "/admin/plugins/htmldocs/manage_htmldocs.html";
103     private static final String TEMPLATE_CREATE_HTMLDOC = "/admin/plugins/htmldocs/create_htmldoc.html";
104     private static final String TEMPLATE_MODIFY_HTMLDOC = "/admin/plugins/htmldocs/modify_htmldoc.html";
105     private static final String TEMPLATE_HISTORY_HTMLDOC = "admin/plugins/htmldocs/history_htmldoc.html";
106     private static final String TEMPLATE_PREVIEW_HTMLDOC = "admin/plugins/htmldocs/preview_htmldoc.html";
107     private static final String TEMPLATE_DIFF_HTMLDOC = "admin/plugins/htmldocs/diff_htmldoc.html";
108 
109     // Parameters
110     protected static final String PARAMETER_ID_HTMLDOC = "id";
111     protected static final String PARAMETER_VERSION_HTMLDOC = "htmldoc_version";
112     protected static final String PARAMETER_VERSION_HTMLDOC2 = "htmldoc_version2";
113     protected static final String PARAMETER_CONTENT_LABEL = "content_label";
114     protected static final String PARAMETER_HTML_CONTENT = "html_content";
115     protected static final String PARAMETER_EDIT_COMMENT = "edit_comment";
116     protected static final String PARAMETER_DESCRIPTION = "description";
117     protected static final String PARAMETER_VIEW = "view";
118     protected static final String PARAMETER_BUTTON_SEARCH = "button_search";
119     protected static final String PARAMETER_SEARCH_TEXT = "search_text";
120     protected static final String PARAMETER_UPDATE_ATTACHMENT = "update_attachment";
121     protected static final String PARAMETER_TAG = "tag_doc";
122     protected static final String PARAMETER_TAG_NAME = "tag_name";
123 
124     protected static final String PARAMETER_TAG_TO_REMOVE = "tag_remove";
125     protected static final String PARAMETER_SHAREABLE = "shareable";
126     protected static final String PARAMETER_PRIORITY= "tag_priority";
127     protected static final String PARAMETER_TAG_ACTION= "tagAction";
128 
129 
130 
131     // Properties for page titles
132     private static final String PROPERTY_PAGE_TITLE_MANAGE_HTMLDOCS = "htmldocs.manage_htmldocs.pageTitle";
133     private static final String PROPERTY_PAGE_TITLE_MODIFY_HTMLDOC = "htmldocs.modify_htmldoc.pageTitle";
134     private static final String PROPERTY_PAGE_TITLE_CREATE_HTMLDOC = "htmldocs.create_htmldoc.pageTitle";
135     private static final String PROPERTY_PAGE_TITLE_HISTORY_HTMLDOC = "htmldocs.history_htmldoc.pageTitle";
136     private static final String PROPERTY_PAGE_TITLE_PREVIEW_HTMLDOC = "htmldocs.preview_htmldoc.pageTitle";
137     private static final String PROPERTY_PAGE_TITLE_DIFF_HTMLDOC = "htmldocs.diff_htmldoc.pageTitle";
138     // Properties
139     private static final String PROPERTY_DEFAULT_LIST_ITEM_PER_PAGE = "htmldocs.listItems.itemsPerPage";
140 
141     private static final String PROPERTY_RESOURCE_TYPE = "htmldoc";
142     private static final String PROPERTY_REFERENE_ITEME_ALL = "all";
143 
144 
145     // Markers
146     protected static final String MARK_HTMLDOC_LIST = "htmldoc_list";
147     protected static final String MARK_HTMLDOC_VERSION_LIST = "htmldoc_version_list";
148     protected static final String MARK_HTMLDOC = "htmldoc";
149     protected static final String MARK_WEBAPP_URL = "webapp_url";
150     protected static final String MARK_IS_CHECKED = "is_checked";
151     protected static final String MARK_CURRENT_USER = "current_user";
152     protected static final String MARK_ID_HTMLDOC = "id";
153     protected static final String MARK_SEARCH_TEXT = "search_text";
154     protected static final String MARK_DIFF = "htmldoc_diff";
155     protected static final String MARK_HTMLDOC2 = "htmldoc2";
156     protected static final String MARK_LIST_TAG = "list_tag";
157     protected static final String MARK_SORTED_ATTRIBUTE = "sorted_attribute_name";
158     protected static final String MARK_TAG = "tags";
159 
160 
161     private static final String JSP_MANAGE_HTMLDOCS = "jsp/admin/plugins/htmldocs/ManageHtmlDocs.jsp";
162 
163     // Properties
164     private static final String MESSAGE_CONFIRM_REMOVE_HTMLDOC = "htmldocs.message.confirmRemoveHtmlDoc";
165     private static final String MESSAGE_ERROR_DOCUMENT_IS_PUBLISHED = "htmldocs.message.errorDocumentIsPublished";
166 
167 
168     // Validations
169     private static final String VALIDATION_ATTRIBUTES_PREFIX = "htmldocs.model.entity.htmldoc.attribute.";
170 
171     // Views
172     protected static final String VIEW_MANAGE_HTMLDOCS = "manageHtmlDocs";
173     private static final String VIEW_CREATE_HTMLDOC = "createHtmlDoc";
174     private static final String VIEW_MODIFY_HTMLDOC = "modifyHtmlDoc";
175     private static final String VIEW_PREVIOUS_VERSION_HTMLDOC = "previousVersionHtmlDoc";
176     private static final String VIEW_HISTORY_HTMLDOC = "historyHtmlDoc";
177     private static final String VIEW_PREVIEW_HTMLDOC = "previewHtmlDoc";
178     private static final String VIEW_DIFF_HTMLDOC = "diffHtmlDoc";
179 
180     // Actions
181     private static final String ACTION_CREATE_HTMLDOC = "createHtmlDoc";
182     private static final String ACTION_MODIFY_HTMLDOC = "modifyHtmlDoc";
183     private static final String ACTION_REMOVE_HTMLDOC = "removeHtmlDoc";
184     private static final String ACTION_CONFIRM_REMOVE_HTMLDOC = "confirmRemoveHtmlDoc";
185     private static final String ACTION_ADD_TAG = "addTag";
186     private static final String ACTION_REMOVE_TAG = "removeTag";
187     private static final String ACTION_UPDATE_PRIORITY_TAG = "updatePriorityTag";
188     // Infos
189     private static final String INFO_HTMLDOC_CREATED = "htmldocs.info.htmldoc.created";
190     private static final String INFO_HTMLDOC_UPDATED = "htmldocs.info.htmldoc.updated";
191     private static final String INFO_HTMLDOC_REMOVED = "htmldocs.info.htmldoc.removed";
192 
193 
194     // Filter Marks
195     protected static final String MARK_HTMLDOC_FILTER_LIST = "htmldoc_filter_list";
196     protected static final String MARK_HTMLDOC_FILTER_NAME = "Nom";
197     protected static final String MARK_HTMLDOC_FILTER_DATE = "Date";
198     protected static final String MARK_HTMLDOC_FILTER_USER = "Utilisateur";
199     protected static final String MARK_PAGINATOR = "paginator";
200     protected static final String MARK_NB_ITEMS_PER_PAGE = "nb_items_per_page";
201     protected static final String MARK_ASC_SORT = "asc_sort";
202 
203 
204 
205     // Session variable to store working values
206     protected HtmlDoc _htmldoc;
207     protected boolean _bIsChecked = false;
208     protected String _strSearchText;
209     protected String _strCurrentPageIndex;
210     protected int _nItemsPerPage;
211     protected int _nDefaultItemsPerPage;
212     protected boolean _bIsSorted = false;
213     protected String _strSortedAttributeName;
214     protected Boolean _bIsAscSort;
215     protected String _strTag=PROPERTY_REFERENE_ITEME_ALL;
216 
217 
218     /**
219      * Build the Manage View
220      * 
221      * @param request
222      *            The HTTP request
223      * @return The page
224      */
225     @View( value = VIEW_MANAGE_HTMLDOCS, defaultView = true )
226     public String getManageHtmlDocs( HttpServletRequest request )
227     {
228         _htmldoc = null;
229         _strCurrentPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex ); 
230         _nDefaultItemsPerPage = AppPropertiesService.getPropertyInt( PROPERTY_DEFAULT_LIST_ITEM_PER_PAGE, 50 );
231         _nItemsPerPage = Paginator.getItemsPerPage( request, Paginator.PARAMETER_ITEMS_PER_PAGE, _nItemsPerPage, _nDefaultItemsPerPage );
232         
233         // SORT
234         String strSortedAttributeName = request.getParameter( MARK_SORTED_ATTRIBUTE );
235         String strAscSort = null;
236         
237         AdminUser user = AdminUserService.getAdminUser( request );
238         List<Integer> listHtmlDocsId= new ArrayList<Integer>();
239         String strButtonSearch = request.getParameter ( PARAMETER_BUTTON_SEARCH );
240         if ( strButtonSearch != null ) {
241             // CURRENT USER
242             _bIsChecked = request.getParameter( MARK_CURRENT_USER ) != null;
243             _strSearchText = request.getParameter( PARAMETER_SEARCH_TEXT );
244             _strTag = request.getParameter( PARAMETER_TAG );
245         }
246 
247       
248 
249         if ( StringUtils.isNotBlank( _strSearchText ) || !_strTag.equals(PROPERTY_REFERENE_ITEME_ALL) || _bIsChecked )
250         {
251         	HtmldocSearchFilter filter= new HtmldocSearchFilter();
252         	if(StringUtils.isNotBlank( _strSearchText )) filter.setKeywords(_strSearchText);
253         	if (!_strTag.equals(PROPERTY_REFERENE_ITEME_ALL)) filter.setTag(_strTag);
254         	if(_bIsChecked) filter.setUser(user.getFirstName( ));
255         	HtmlDocSearchService.getInstance().getSearchResults(filter, listHtmlDocsId);
256        	
257         }
258         
259         else{
260         	
261         	listHtmlDocsId= HtmlDocHome.getIdHtmlDocsList();
262         }
263         
264         LocalizedPaginator<Integer> paginator = new LocalizedPaginator<Integer>( (List<Integer>) listHtmlDocsId,
265                 _nItemsPerPage, getHomeUrl( request ), Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex,
266                 getLocale(  ) );
267 
268         List<HtmlDoc> listDocuments = new ArrayList<HtmlDoc>(  );
269 
270         for ( Integer documentId : paginator.getPageItems(  ) )
271         {
272         	HtmlDoc document = HtmlDocService.getInstance().findByPrimaryKeyWithoutBinaries( documentId );
273 
274             if ( document != null )
275             {
276                 listDocuments.add( document );
277             }
278         }
279         
280         if ( strSortedAttributeName != null || _bIsSorted == true )
281         {
282             if ( strSortedAttributeName == null )
283             {
284                 strSortedAttributeName = _strSortedAttributeName;
285             }
286             strAscSort = request.getParameter( MARK_ASC_SORT );
287 
288             boolean bIsAscSort = Boolean.parseBoolean( strAscSort );
289             if ( strAscSort == null )
290             {
291                 bIsAscSort = _bIsAscSort;
292             }
293 
294             Collections.sort( listDocuments, new AttributeComparator( strSortedAttributeName, bIsAscSort ) );
295 
296             _bIsSorted = true;
297 
298             _strSortedAttributeName = strSortedAttributeName;
299             _bIsAscSort = bIsAscSort;
300         }
301 
302 
303         Map<String, Object> model = new HashMap<String, Object>(  );
304         model.put(MARK_HTMLDOC_LIST, listDocuments);
305         model.put(MARK_PAGINATOR, paginator);
306         model.put( MARK_HTMLDOC_FILTER_LIST, getHtmldocFilterList( ) );
307         model.put(MARK_LIST_TAG, TagHome.getTagsReferenceList( ));
308         model.put( MARK_WEBAPP_URL, AppPathService.getBaseUrl( request ) );
309         model.put( MARK_IS_CHECKED, _bIsChecked );
310         model.put( MARK_SEARCH_TEXT, _strSearchText );
311         model.put( MARK_NB_ITEMS_PER_PAGE, "" + _nItemsPerPage );
312         model.put( MARK_TAG, _strTag );
313 
314         return getPage( PROPERTY_PAGE_TITLE_MANAGE_HTMLDOCS, TEMPLATE_MANAGE_HTMLDOCS, model );
315     }
316 
317     @View( value = VIEW_HISTORY_HTMLDOC )
318     public String getHistoryHtmlDoc( HttpServletRequest request )
319     {
320         _htmldoc = null;
321         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
322         List<HtmlDoc> listHtmlDocsVersions = HtmlDocHome.getHtmlDocsVersionsList( nId );
323 
324         UrlItem urlHistory = new UrlItem( JSP_MANAGE_HTMLDOCS );
325         urlHistory.addParameter( PARAMETER_VIEW , VIEW_HISTORY_HTMLDOC );
326         urlHistory.addParameter( PARAMETER_ID_HTMLDOC , nId );
327 
328         Map<String, Object> model = getPaginatedListModel( request, MARK_HTMLDOC_LIST, listHtmlDocsVersions, urlHistory.getUrl( ) );
329 
330         model.put( MARK_ID_HTMLDOC, nId );
331         
332 
333         return getPage( PROPERTY_PAGE_TITLE_HISTORY_HTMLDOC, TEMPLATE_HISTORY_HTMLDOC, model );
334     }
335 
336     /**
337      * Returns the form to create a htmldoc
338      *
339      * @param request
340      *            The Http request
341      * @return the html code of the htmldoc form
342      */
343     @View( VIEW_CREATE_HTMLDOC )
344     public String getCreateHtmlDoc( HttpServletRequest request )
345     {
346         _htmldoc = ( _htmldoc != null ) ? _htmldoc : new HtmlDoc( );
347 
348         Map<String, Object> model = getModel( );
349         model.put( MARK_HTMLDOC, _htmldoc );
350         model.put(MARK_LIST_TAG, getTageList());
351         model.put( MARK_WEBAPP_URL, AppPathService.getBaseUrl( request ) );
352 
353         return getPage( PROPERTY_PAGE_TITLE_CREATE_HTMLDOC, TEMPLATE_CREATE_HTMLDOC, model );
354     }
355 
356     /**
357      * Gets the current
358      *
359      * @return the current date in sql format
360      */
361     public java.sql.Timestamp getSqlDate( )
362     {
363         java.util.Date utilDate = new java.util.Date( );
364         java.sql.Timestamp sqlDate = new java.sql.Timestamp( utilDate.getTime( ) );
365 
366         return ( sqlDate );
367     }
368 
369     /**
370      * Process the data capture form of a new htmldoc
371      *
372      * @param request
373      *            The Http Request
374      * @return The Jsp URL of the process result
375      */
376     @Action( ACTION_CREATE_HTMLDOC )
377     public String doCreateHtmlDoc( HttpServletRequest request )
378     {
379     	
380         _htmldoc.setCreationDate( getSqlDate( ) );
381         _htmldoc.setUpdateDate( getSqlDate( ) );
382         _htmldoc.setUser( AdminUserService.getAdminUser( request ).getFirstName( ) );
383         _htmldoc.setUserCreator( AdminUserService.getAdminUser( request ).getFirstName( ) );
384         _htmldoc.setVersion( 1 );
385         _htmldoc.setAttachedPortletId( 0 );
386         populate( _htmldoc, request );
387 
388         // Check constraints
389         if ( !validateBean( _htmldoc, VALIDATION_ATTRIBUTES_PREFIX ) )
390         {
391             return redirectView( request, VIEW_CREATE_HTMLDOC );
392         }
393         
394         //HtmlDocHome.addInitialVersion( _htmldoc );
395         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
396         DocContent docContent= setContent( multipartRequest, request.getLocale( ) );
397         HtmlDocService.getInstance().createDocument(_htmldoc, docContent);
398 
399         addInfo( INFO_HTMLDOC_CREATED, getLocale( ) );
400 
401         return redirectView( request, VIEW_MANAGE_HTMLDOCS );
402     }
403 
404     @Action( ACTION_ADD_TAG )
405     public String doAddTag( HttpServletRequest request )
406     {
407     		String strIdTag= request.getParameter(PARAMETER_TAG);
408     		String strTagName= request.getParameter(PARAMETER_TAG_NAME);
409     		
410     		Tag tag= new Tag(Integer.parseInt(strIdTag), _htmldoc.getTag( ).size( )+1 );
411     		tag.setName(strTagName);
412     		
413         	_htmldoc.addTag(tag);
414         	
415     		return JsonUtil.buildJsonResponse(new JsonResponse("SUCESS"));
416     		
417     	
418      }
419     @Action( ACTION_REMOVE_TAG )
420     public String doRemoveTag( HttpServletRequest request )
421     {
422 		     String strIdTag= request.getParameter(PARAMETER_TAG);
423 		     Tag tag= new  Tag();
424 		     tag.setIdTag(Integer.parseInt(strIdTag));
425         	_htmldoc.deleteTag(tag);
426         	
427     		return JsonUtil.buildJsonResponse(new JsonResponse("SUCESS"));
428     		
429     	
430      }
431     @Action( ACTION_UPDATE_PRIORITY_TAG )
432     public String doUpdatePriorityTag( HttpServletRequest request )
433     {
434     		Tag tg= null;
435     		Tag tagMove= null;
436     		int nPriorityToSet=0;
437     		int nPriority= 0;
438 
439     		String strIdTag= request.getParameter(PARAMETER_TAG);
440     		String strAction= request.getParameter(PARAMETER_TAG_ACTION);
441     		    		
442     		for(Tag tag:_htmldoc.getTag()){
443     			if(tag.getIdTag()== Integer.parseInt(strIdTag)){
444     				tg= tag;	
445     				nPriorityToSet= tag.getPriority();
446     				nPriority= tag.getPriority();
447     			}
448     		}
449     		for(Tag tag:_htmldoc.getTag()){
450     			if(strAction.equals("moveUp") && tag.getPriority()== nPriority -1 ){
451     				tagMove= tag;
452     				tagMove.setPriority(tagMove.getPriority( ) +1 );
453     				nPriorityToSet= nPriority - 1;
454     				
455     			}else if(strAction.equals("moveDown") && tag.getPriority()== nPriority +1){
456     				tagMove= tag;
457     				tagMove.setPriority(tagMove.getPriority( ) - 1);
458     				nPriorityToSet= nPriority + 1;
459 
460     			}
461     		}
462     		tg.setPriority(nPriorityToSet);
463     		  
464     		if( tagMove!=null ){
465     			
466     		return JsonUtil.buildJsonResponse(new JsonResponse(String.valueOf(tagMove.getIdTag())));
467     		
468     		}
469     		return JsonUtil.buildJsonResponse(new JsonResponse(String.valueOf(tg.getIdTag())));
470 
471     	
472      }
473     /**
474      * Manages the removal form of a htmldoc whose identifier is in the http request
475      *
476      * @param request
477      *            The Http request
478      * @return the html code to confirm
479      */
480     @Action( ACTION_CONFIRM_REMOVE_HTMLDOC )
481     public String getConfirmRemoveHtmlDoc( HttpServletRequest request )
482     {
483         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
484         UrlItem url = new UrlItem( getActionUrl( ACTION_REMOVE_HTMLDOC ) );
485         url.addParameter( PARAMETER_ID_HTMLDOC, nId );
486 
487         String strMessageUrl = AdminMessageService.getMessageUrl( request, MESSAGE_CONFIRM_REMOVE_HTMLDOC, url.getUrl( ), AdminMessage.TYPE_CONFIRMATION );
488 
489         return redirect( request, strMessageUrl );
490     }
491 
492     /**
493      * Handles the removal form of a htmldoc
494      *
495      * @param request
496      *            The Http request
497      * @return the jsp URL to display the form to manage htmldocs
498      */
499     @Action( ACTION_REMOVE_HTMLDOC )
500     public String doRemoveHtmlDoc( HttpServletRequest request )
501     {
502         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
503     	List<HtmlDocPublication>   docPublication= HtmlDocPublicationHome.getDocPublicationByIdDoc( nId );
504 
505        
506         if ( docPublication.size() > 0 )
507         {
508         	String strMessageUrl = AdminMessageService.getMessageUrl( request, MESSAGE_ERROR_DOCUMENT_IS_PUBLISHED,  AdminMessage.TYPE_STOP);
509 
510             return redirect( request, strMessageUrl );
511         }
512         HtmlDocService.getInstance().deleteDocument(nId);
513         ExtendableResourceRemovalListenerService.doRemoveResourceExtentions(HtmlDoc.PROPERTY_RESOURCE_TYPE, String.valueOf(nId));
514         
515         addInfo( INFO_HTMLDOC_REMOVED, getLocale( ) );
516 
517         return redirectView( request, VIEW_MANAGE_HTMLDOCS );
518     }
519 
520     /**
521      * Returns the form to update info about a htmldoc
522      *
523      * @param request
524      *            The Http request
525      * @return The HTML form to update info
526      */
527     @View( VIEW_MODIFY_HTMLDOC )
528     public String getModifyHtmlDoc( HttpServletRequest request )
529     {
530         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
531         String strResetVersion = request.getParameter( PARAMETER_VERSION_HTMLDOC );
532         int nVersion = -1;
533         if (strResetVersion != null )
534         {
535             nVersion = Integer.parseInt( strResetVersion );
536         }
537 
538         if ( _htmldoc == null || ( _htmldoc.getId( ) != nId ) || ( strResetVersion != null && _htmldoc.getVersion( ) != nVersion ) )
539         {
540             if ( strResetVersion != null )
541             {
542                 _htmldoc = HtmlDocHome.findVersion( nId, nVersion );
543             } else
544             {
545                 _htmldoc = HtmlDocService.getInstance().loadDocument(nId);
546             }
547           //  _htmldoc.setEditComment("");
548         }
549 
550         Map<String, Object> model = getModel( );
551         model.put( MARK_HTMLDOC, _htmldoc );
552         model.put(MARK_LIST_TAG, getTageList());
553 
554         model.put( MARK_WEBAPP_URL, AppPathService.getBaseUrl( request ) );
555         
556         ExtendableResourcePluginActionManager.fillModel( request, getUser(  ), model, String.valueOf(nId),
557                 HtmlDoc.PROPERTY_RESOURCE_TYPE );
558 
559         return getPage( PROPERTY_PAGE_TITLE_MODIFY_HTMLDOC, TEMPLATE_MODIFY_HTMLDOC, model );
560     }
561 
562     /**
563      * Process the change form of a htmldoc
564      *
565      * @param request
566      *            The Http request
567      * @return The Jsp URL of the process result
568      */
569     @Action( ACTION_MODIFY_HTMLDOC )
570     public String doModifyHtmlDoc( HttpServletRequest request )
571     {
572         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
573         String strHtmlContent = request.getParameter( PARAMETER_HTML_CONTENT );
574         String strEditComment = request.getParameter( PARAMETER_EDIT_COMMENT );
575         String strContentLabel = request.getParameter( PARAMETER_CONTENT_LABEL );
576         String strDescription = request.getParameter( PARAMETER_DESCRIPTION );
577         String strShareable = request.getParameter( PARAMETER_SHAREABLE );
578 
579         String strUpdate_attachment= request.getParameter( PARAMETER_UPDATE_ATTACHMENT );
580         boolean bIsUpdatable = ( ( strUpdate_attachment == null ) || strUpdate_attachment.equals( "" ) ) ? false : true;
581 
582         
583         HtmlDoc latestVersionHtmlDoc = HtmlDocHome.findByPrimaryKey( nId );
584         if ( _htmldoc == null || ( _htmldoc.getId( ) != nId ) )
585         {
586             _htmldoc = latestVersionHtmlDoc;
587         }
588 
589         _htmldoc.setContentLabel( strContentLabel );
590         _htmldoc.setDescription(strDescription);
591         _htmldoc.setShareable(Boolean.parseBoolean(strShareable));
592         _htmldoc.setHtmlContent( strHtmlContent );
593         _htmldoc.setEditComment( strEditComment );
594         _htmldoc.setUpdateDate( getSqlDate( ) );
595         _htmldoc.setUser( AdminUserService.getAdminUser( request ).getFirstName( ) );
596     
597         // Check constraints
598         if ( !validateBean( _htmldoc, VALIDATION_ATTRIBUTES_PREFIX ) )
599         {
600             return redirect( request, VIEW_MODIFY_HTMLDOC, PARAMETER_ID_HTMLDOC, _htmldoc.getId( ) );
601         }
602 
603         _htmldoc.setVersion( latestVersionHtmlDoc.getVersion( ) + 1 );
604        
605         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
606         DocContent docContent= setContent( multipartRequest, request.getLocale( ) );
607         if(bIsUpdatable && docContent == null){
608         	
609         	DocContentHome.remove(nId);
610         	docContent = null;
611         }
612         else if(docContent == null ){
613         	
614         	docContent = _htmldoc.getDocContent();
615         
616         }
617         
618         HtmlDocService.getInstance().updateDocument(_htmldoc, docContent);
619         
620 
621         addInfo( INFO_HTMLDOC_UPDATED, getLocale( ) );
622 
623         return redirectView( request, VIEW_MANAGE_HTMLDOCS );
624     }
625 
626     /**
627      * Returns the preview of an htmldoc
628      *
629      * @param request
630      *            The Http request
631      * @return The HTML form to update info
632      */
633     @View( VIEW_PREVIEW_HTMLDOC )
634     public String getPreviewHtmlDoc( HttpServletRequest request )
635     {
636         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
637         String strVersion = request.getParameter( PARAMETER_VERSION_HTMLDOC );
638         int nVersion = -1;
639         if (strVersion != null )
640         {
641             nVersion = Integer.parseInt( strVersion );
642         }
643 
644         HtmlDoc htmldoc;
645         if ( strVersion != null )
646         {
647             htmldoc = HtmlDocHome.findVersion( nId, nVersion );
648         } else
649         {
650             htmldoc = HtmlDocService.getInstance().loadDocument(nId);
651         }
652         htmldoc.setHtmldocPubilcation(HtmlDocPublicationHome.getDocPublicationByIdDoc( nId ));
653 
654 
655         Map<String, Object> model = getModel( );
656         model.put(MARK_LIST_TAG, TagHome.getTagsReferenceList( ));
657 
658         model.put( MARK_HTMLDOC, htmldoc );
659         
660         ExtendableResourcePluginActionManager.fillModel( request, getUser(  ), model, String.valueOf(nId),
661                 HtmlDoc.PROPERTY_RESOURCE_TYPE );
662 
663         return getPage( PROPERTY_PAGE_TITLE_PREVIEW_HTMLDOC, TEMPLATE_PREVIEW_HTMLDOC, model );
664     }
665 
666     /**
667      * Returns the diff of two htmldocs versions
668      *
669      * @param request
670      *            The Http request
671      * @return The HTML form to update info
672      */
673     @View( VIEW_DIFF_HTMLDOC )
674     public String getDiffHtmlDoc( HttpServletRequest request )
675     {
676         int nId = Integer.parseInt( request.getParameter( PARAMETER_ID_HTMLDOC ) );
677         String strVersion = request.getParameter( PARAMETER_VERSION_HTMLDOC );
678         int nVersion = -1;
679         if (strVersion != null )
680         {
681             nVersion = Integer.parseInt( strVersion );
682         }
683         String strVersion2 = request.getParameter( PARAMETER_VERSION_HTMLDOC2 );
684 
685         HtmlDoc htmldoc;
686         if ( strVersion != null )
687         {
688             htmldoc = HtmlDocHome.findVersion( nId, nVersion );
689         } else
690         {
691             htmldoc = HtmlDocHome.findByPrimaryKey( nId );
692         }
693 
694         int nVersion2 = htmldoc.getVersion( ) - 1;
695         if ( strVersion2 != null )
696         {
697             nVersion2 = Integer.parseInt( strVersion2 );
698         }
699 
700         HtmlDoc htmldoc2 = HtmlDocHome.findVersion( nId, nVersion2 );
701         if ( htmldoc2 == null ) {
702             htmldoc2 = HtmlDocHome.findByPrimaryKey( nId );
703         }
704 
705         if ( htmldoc2.getVersion() > htmldoc.getVersion() ) {
706             HtmlDoc tmp = htmldoc2;
707             htmldoc2 = htmldoc;
708             htmldoc = tmp;
709         }
710 
711         String strDiff = null;
712         HtmlCleaner cleaner = new HtmlCleaner();
713         try {
714           SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
715           TransformerHandler result = tf.newTransformerHandler();
716           result.getTransformer().setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" );
717           StringWriter resultWriter = new StringWriter();
718           result.setResult(new StreamResult(resultWriter));
719           Locale locale = getLocale();
720 
721           DomTreeBuilder oldHandler = new DomTreeBuilder();
722           cleaner.cleanAndParse(new InputSource(new ByteArrayInputStream(htmldoc2.getHtmlContent().getBytes("UTF-8"))), oldHandler);
723           TextNodeComparator leftComparator = new TextNodeComparator( oldHandler, locale );
724 
725           DomTreeBuilder newHandler = new DomTreeBuilder();
726           cleaner.cleanAndParse(new InputSource(new ByteArrayInputStream(htmldoc.getHtmlContent().getBytes("UTF-8"))), newHandler);
727           TextNodeComparator rightComparator = new TextNodeComparator( newHandler, locale );
728 
729           HtmlSaxDiffOutput output = new HtmlSaxDiffOutput(result, "");
730           HTMLDiffer differ = new HTMLDiffer(output);
731           differ.diff(leftComparator, rightComparator);
732 
733           strDiff = resultWriter.toString();
734         } catch (Exception e) {
735           AppLogService.error( "Error generating daisy diff for htmldoc " + nId + ":" + htmldoc.getContentLabel() + "; versions ("+ htmldoc.getVersion() + "," + htmldoc2.getVersion() + ")", e);
736         }
737 
738         List<HtmlDoc> listHtmlDocsVersions = HtmlDocHome.getHtmlDocsVersionsList( nId );
739 
740         Map<String, Object> model = getModel( );
741         model.put( MARK_HTMLDOC, htmldoc );
742         model.put( MARK_HTMLDOC2, htmldoc2 );
743         model.put( MARK_DIFF, strDiff );
744         model.put( MARK_HTMLDOC_VERSION_LIST, listHtmlDocsVersions );
745 
746         return getPage( PROPERTY_PAGE_TITLE_DIFF_HTMLDOC, TEMPLATE_DIFF_HTMLDOC, model );
747     }
748 
749     
750     private ReferenceList getHtmldocFilterList( )
751     {
752         ReferenceList list = new ReferenceList( );
753         list.addItem( MARK_HTMLDOC_FILTER_NAME, "Nom" );
754         list.addItem( MARK_HTMLDOC_FILTER_DATE, "Date" );
755         list.addItem( MARK_HTMLDOC_FILTER_USER, "Utilisateur" );
756 
757         return list;
758     }
759     
760     public DocContent setContent( MultipartHttpServletRequest mRequest, Locale locale )
761     {
762     	
763         FileItem fileParameterBinaryValue = mRequest.getFile( "attachment" );
764         //boolean bToResize = ( ( strToResize == null ) || strToResize.equals( "" ) ) ? false : true;
765 
766       
767        if ( fileParameterBinaryValue != null ) // If the field is a file
768         {
769            
770             String strContentType = fileParameterBinaryValue.getContentType(  );
771             byte[] bytes = fileParameterBinaryValue.get(  );
772             String strFileName = fileParameterBinaryValue.getName(  );
773            
774             if(!ArrayUtils.isEmpty( bytes )){
775             	
776             	  DocContent docContent= new DocContent();
777                   docContent.setBinaryValue( bytes );
778                   docContent.setValueContentType( strContentType );
779                   docContent.setTextValue( strFileName );
780                 
781                   return docContent;
782             }
783           
784         }
785 
786         return null;
787     }
788     /**
789      * 
790      * @return htmlDocList
791      */
792     private ReferenceList getTageList(){
793     	
794         ReferenceList htmlDocList = TagHome.getTagsReferenceList( );
795 		int index=0;
796 
797     	for (ReferenceItem item:TagHome.getTagsReferenceList( )){
798     		for(Tag tg:_htmldoc.getTag()){
799 	    		if( item.getCode().equals(String.valueOf(tg.getIdTag( )))){
800 	    			
801 	    			htmlDocList.remove(index);
802 	    			index--;
803 	    		}
804     		}
805     		index++;
806     	}
807     	
808     	return htmlDocList;
809     }
810 }