View Javadoc
1   /*
2    * Copyright (c) 2002-2018, 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.appointmentfactory.web;
35  
36  import java.util.ArrayList;
37  import java.util.HashMap;
38  import java.util.Map;
39  
40  import javax.servlet.http.HttpServletRequest;
41  import javax.servlet.http.HttpSession;
42  import javax.ws.rs.client.Client;
43  import javax.ws.rs.client.ClientBuilder;
44  import javax.ws.rs.client.Entity;
45  import javax.ws.rs.client.WebTarget;
46  import javax.ws.rs.core.MediaType;
47  import javax.ws.rs.core.Response;
48  import javax.ws.rs.core.Response.Status;
49  
50  import org.apache.commons.lang3.StringUtils;
51  
52  import fr.paris.lutece.plugins.appointment.service.FormService;
53  import fr.paris.lutece.plugins.appointment.service.FormTraderService;
54  import fr.paris.lutece.plugins.appointment.web.rs.Constants;
55  import fr.paris.lutece.plugins.appointmentfactory.business.AppointmentFactoryDTO;
56  import fr.paris.lutece.plugins.appointmentfactory.business.InstanceDTO;
57  import fr.paris.lutece.plugins.appointmentfactory.service.InstanceService;
58  import fr.paris.lutece.portal.service.admin.AccessDeniedException;
59  import fr.paris.lutece.portal.service.util.AppPropertiesService;
60  import fr.paris.lutece.portal.util.mvc.admin.MVCAdminJspBean;
61  import fr.paris.lutece.portal.util.mvc.admin.annotations.Controller;
62  import fr.paris.lutece.portal.util.mvc.commons.annotations.Action;
63  import fr.paris.lutece.portal.util.mvc.commons.annotations.View;
64  import fr.paris.lutece.portal.util.mvc.utils.MVCUtils;
65  import fr.paris.lutece.portal.web.util.LocalizedPaginator;
66  import fr.paris.lutece.util.html.Paginator;
67  import fr.paris.lutece.util.url.UrlItem;
68  import net.sf.json.JSONObject;
69  
70  /**
71   * ManageAppointmentfactory JSP Bean abstract class for JSP Bean
72   */
73  @Controller( controllerJsp = "ManageAppointmentfactory.jsp", controllerPath = "jsp/admin/plugins/appointmentfactory/", right = ManageAppointmentfactoryJspBean.RIGHT_MANAGEAPPOINTMENTFACTORY )
74  public class ManageAppointmentfactoryJspBean extends MVCAdminJspBean
75  {
76  
77      /**
78       * UID
79       */
80      private static final long serialVersionUID = -9044694273971530510L;
81  
82      // Rights
83      public static final String RIGHT_MANAGEAPPOINTMENTFACTORY = "APPOINTMENTFACTORY_MANAGEMENT";
84  
85      // Templates
86      private static final String TEMPLATE_MANAGE_APPOINTMENT_FACTORY = "/admin/plugins/appointmentfactory/manage_appointment_factory.html";
87  
88      // Actions
89      private static final String ACTION_EXPORT_FORM = "exportForm";
90  
91      // Session keys
92      private static final String SESSION_CURRENT_PAGE_INDEX = "appointmentfactory.session.currentPageIndex";
93      private static final String SESSION_ITEMS_PER_PAGE = "appointmentfactory.session.itemsPerPage";
94      private static final String SESSION_ATTRIBUTE_APPOINTMENT_FACTORY = "appointmentfactory.session";
95  
96      // Properties for page titles
97      private static final String PROPERTY_PAGE_TITLE_MANAGE_APPOINTMENT_FACTORY = "appointmentfactory.manage.appointmentfactory.title";
98  
99      // Properties
100     private static final String PROPERTY_DEFAULT_LIST_SERVERS_PER_PAGE = "appointmentfactory.listServers.itemsPerPage";
101 
102     // Views
103     private static final String VIEW_MANAGE_APPOINTMENT_FACTORY = "manageAppointmentfactory";
104 
105     // Errors
106     private static final String ERROR_MESSAGE_NO_INSTANCE_CHECKED = "appointmentfactory.validation.export.noInstanceChecked";
107 
108     // Infos
109     private static final String INFO_MESSAGE_FORM_EXPORT_OK = "appointmentfactory.message.form.export.ok";
110 
111     // Markers
112     private static final String MARK_LIST_FORMS = "listForms";
113     private static final String MARK_LIST_INSTANCES = "listInstances";
114     private static final String MARK_NB_ITEMS_PER_PAGE = "nb_items_per_page";
115     private static final String MARK_PAGINATOR = "paginator";
116     private static final String MARK_APPOINTMENT_FACTORY = "appointmentfactory";
117 
118     // Parameters
119     private static final String PARAMETER_ID_INSTANCES = "inst";
120     private static final String PARAMETER_ID_FORM = "idForm";
121     private static final String PARAMETER_PAGE_INDEX = "page_index";
122 
123     // Constants
124     private static final String DEFAULT_CURRENT_PAGE = "1";
125 
126     // Session variable to store working values
127     private int _nDefaultItemsPerPage;
128 
129     private static final String JSP_MANAGE_APPOINTMENT_FACTORY = "jsp/admin/plugins/appointmentfactory/ManageAppointmentfactory.jsp";
130 
131     /**
132      * Default constructor
133      */
134     public ManageAppointmentfactoryJspBean( )
135     {
136         _nDefaultItemsPerPage = AppPropertiesService.getPropertyInt( PROPERTY_DEFAULT_LIST_SERVERS_PER_PAGE, 10 );
137     }
138 
139     /**
140      * Get the page to export form to instances
141      * 
142      * @param request
143      *            the request
144      * @return The HTML content to display
145      */
146     @View( value = VIEW_MANAGE_APPOINTMENT_FACTORY, defaultView = true )
147     public String getManageAppointmentFactory( HttpServletRequest request )
148     {
149         String strCurrentPageIndex = Paginator.getPageIndex( request, Paginator.PARAMETER_PAGE_INDEX,
150                 (String) request.getSession( ).getAttribute( SESSION_CURRENT_PAGE_INDEX ) );
151         if ( StringUtils.isEmpty( strCurrentPageIndex ) )
152         {
153             strCurrentPageIndex = DEFAULT_CURRENT_PAGE;
154         }
155         AppointmentFactoryDTO appointmentFactoryDTO = (AppointmentFactoryDTO) request.getSession( ).getAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FACTORY );
156         if ( appointmentFactoryDTO == null )
157         {
158             appointmentFactoryDTO = new AppointmentFactoryDTO( );
159         }
160         request.getSession( ).setAttribute( SESSION_CURRENT_PAGE_INDEX, strCurrentPageIndex );
161         int nItemsPerPage = Paginator.getItemsPerPage( request, Paginator.PARAMETER_ITEMS_PER_PAGE,
162                 getIntSessionAttribute( request.getSession( ), SESSION_ITEMS_PER_PAGE ), _nDefaultItemsPerPage );
163         request.getSession( ).setAttribute( SESSION_ITEMS_PER_PAGE, nItemsPerPage );
164         UrlItem url = new UrlItem( JSP_MANAGE_APPOINTMENT_FACTORY );
165         url.addParameter( MVCUtils.PARAMETER_VIEW, VIEW_MANAGE_APPOINTMENT_FACTORY );
166         String strUrl = url.getUrl( );
167         HashMap<Integer, InstanceDTO> mapInstances = InstanceService.getInstancesFromProperties( );
168         appointmentFactoryDTO.setInstances( mapInstances );
169         request.getSession( ).setAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FACTORY, appointmentFactoryDTO );
170         LocalizedPaginator<InstanceDTO> paginator = new LocalizedPaginator<InstanceDTO>( new ArrayList<>( mapInstances.values( ) ), nItemsPerPage, strUrl,
171                 PARAMETER_PAGE_INDEX, strCurrentPageIndex, getLocale( ) );
172         Map<String, Object> model = getModel( );
173         model.put( MARK_LIST_FORMS, FormService.findAllInReferenceList( ) );
174         model.put( MARK_NB_ITEMS_PER_PAGE, Integer.toString( nItemsPerPage ) );
175         model.put( MARK_PAGINATOR, paginator );
176         model.put( MARK_LIST_INSTANCES, paginator.getPageItems( ) );
177         model.put( MARK_APPOINTMENT_FACTORY, appointmentFactoryDTO );
178         return getPage( PROPERTY_PAGE_TITLE_MANAGE_APPOINTMENT_FACTORY, TEMPLATE_MANAGE_APPOINTMENT_FACTORY, model );
179     }
180 
181     /**
182      * Export the form selected to the instances selected in json format
183      * 
184      * @param request
185      * @return to the manage page
186      * @throws AccessDeniedException
187      */
188     @Action( ACTION_EXPORT_FORM )
189     public String doExportForm( HttpServletRequest request ) throws AccessDeniedException
190     {
191         AppointmentFactoryDTO appointmentFactoryDTO = (AppointmentFactoryDTO) request.getSession( ).getAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FACTORY );
192         if ( appointmentFactoryDTO == null )
193         {
194             appointmentFactoryDTO = new AppointmentFactoryDTO( );
195         }
196         String strIdForm = request.getParameter( PARAMETER_ID_FORM );
197         if ( StringUtils.isNotEmpty( strIdForm ) )
198         {
199             appointmentFactoryDTO.setIdForm( Integer.parseInt( strIdForm ) );
200         }
201         request.getSession( ).setAttribute( SESSION_ATTRIBUTE_APPOINTMENT_FACTORY, appointmentFactoryDTO );
202         String [ ] tabIdInstances = request.getParameterValues( PARAMETER_ID_INSTANCES );
203         if ( tabIdInstances == null || tabIdInstances.length == 0 )
204         {
205             addError( ERROR_MESSAGE_NO_INSTANCE_CHECKED, getLocale( ) );
206             return redirectView( request, VIEW_MANAGE_APPOINTMENT_FACTORY );
207         }
208         if ( callRestService( tabIdInstances, appointmentFactoryDTO.getInstances( ), FormTraderService.exportFormToJson( appointmentFactoryDTO.getIdForm( ) ) ) )
209         {
210             addInfo( INFO_MESSAGE_FORM_EXPORT_OK, getLocale( ) );
211         }
212         return redirectView( request, VIEW_MANAGE_APPOINTMENT_FACTORY );
213     }
214 
215     /**
216      * Call the rest service that will import the json file to the instances selected
217      * 
218      * @param tabIdInstances
219      *            the instances selected
220      * @param mapInstances
221      *            all the instances in the properties
222      * @param jsonToExport
223      *            the json to export
224      * @return true if all the calls are ok
225      */
226     private boolean callRestService( String [ ] tabIdInstances, HashMap<Integer, InstanceDTO> mapInstances, JSONObject jsonToExport )
227     {
228         boolean bCallOk = Boolean.TRUE;
229         WebTarget target;
230         int nIdInstance;
231         InstanceDTO instanceDTO;
232         String url;
233         Response res;
234 
235         Client client = ClientBuilder.newClient( );
236         StringBuilder stbPath = new StringBuilder( ).append( Constants.BASE_REST_PATH ).append( Constants.PLUGIN_PATH ).append( Constants.FORM_PATH )
237                 .append( Constants.IMPORT_PATH );
238         String strPath = stbPath.toString( );
239         for ( String strIdInstance : tabIdInstances )
240         {
241             nIdInstance = Integer.parseInt( strIdInstance );
242             if ( mapInstances.containsKey( nIdInstance ) )
243             {
244                 instanceDTO = mapInstances.get( nIdInstance );
245                 url = instanceDTO.getUrl( );
246                 target = client.target( url ).path( strPath );
247                 res = target.request( MediaType.APPLICATION_JSON ).post( Entity.json( jsonToExport ) );
248                 if ( res.getStatus( ) != Status.OK.getStatusCode( ) )
249                 {
250                     addError( "Error for instance " + instanceDTO.getName( ) + "; Response status = " + res.getStatus( ) );
251                     bCallOk = Boolean.FALSE;
252                 }
253             }
254         }
255         return bCallOk;
256     }
257 
258     /**
259      * Get an integer attribute from the session
260      * 
261      * @param session
262      *            The session
263      * @param strSessionKey
264      *            The session key of the item
265      * @return The value of the attribute, or 0 if the key is not associated with any value
266      */
267     private int getIntSessionAttribute( HttpSession session, String strSessionKey )
268     {
269         Integer nAttr = (Integer) session.getAttribute( strSessionKey );
270         if ( nAttr != null )
271         {
272             return nAttr;
273         }
274         return 0;
275     }
276 
277 }