View Javadoc
1   /*
2    * Copyright (c) 2002-2020, City of 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.appcenter.modules.fastdeployapplication.util;
35  
36  import java.io.File;
37  import java.io.IOException;
38  import java.nio.file.Files;
39  import java.nio.file.Path;
40  import java.nio.file.Paths;
41  import java.util.ArrayList;
42  import java.util.Collection;
43  import java.util.Iterator;
44  import java.util.List;
45  import java.util.Locale;
46  import java.util.Map;
47  import java.util.Map.Entry;
48  
49  import javax.servlet.http.HttpServletRequest;
50  
51  import org.apache.commons.collections.CollectionUtils;
52  import org.apache.commons.io.FileUtils;
53  import org.apache.commons.lang.StringUtils;
54  
55  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.CommandResult;
56  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.FastDeployApplicationData;
57  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.ServerApplicationInstance;
58  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.context.AbstractWorkflowDeployContext;
59  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.fastaction.ActionParameter;
60  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.fastaction.IAction;
61  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.vcs.AbstractVCSUser;
62  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.vcs.GitUser;
63  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.business.vcs.SvnUser;
64  import fr.paris.lutece.plugins.appcenter.modules.fastdeployapplication.service.vcs.IVCSService;
65  import fr.paris.lutece.plugins.workflowcore.business.action.Action;
66  import fr.paris.lutece.plugins.workflowcore.business.state.State;
67  import fr.paris.lutece.portal.business.user.attribute.AdminUserField;
68  import fr.paris.lutece.portal.service.i18n.I18nService;
69  import fr.paris.lutece.portal.service.spring.SpringContextService;
70  import fr.paris.lutece.portal.service.user.attribute.AdminUserFieldService;
71  import fr.paris.lutece.portal.service.util.AppException;
72  import fr.paris.lutece.portal.service.util.AppLogService;
73  import fr.paris.lutece.portal.service.util.AppPropertiesService;
74  import fr.paris.lutece.portal.service.workflow.WorkflowService;
75  import fr.paris.lutece.util.ReferenceItem;
76  import fr.paris.lutece.util.ReferenceList;
77  import fr.paris.lutece.util.httpaccess.HttpAccess;
78  import fr.paris.lutece.util.httpaccess.HttpAccessException;
79  import net.sf.json.JSONArray;
80  import net.sf.json.JSONException;
81  import net.sf.json.JSONObject;
82  import net.sf.json.JSONSerializer;
83  
84  public class DeploymentUtils
85  {
86  
87      public static List<String> getJSONDictionary( String dictionaryName, String strJSONFlux )
88      {
89          List<String> jsonCollection = new ArrayList<String>( );
90          JSONObject jo = (JSONObject) JSONSerializer.toJSON( strJSONFlux );
91          JSONArray jsonArray = jo.getJSONArray( dictionaryName );
92          Iterator iterator = jsonArray.iterator( );
93  
94          while ( iterator.hasNext( ) )
95          {
96              jsonCollection.add( (String) iterator.next( ) );
97          }
98  
99          return jsonCollection;
100     }
101 
102     public static List<String> getJSONDictionary( String objectName, String dictionaryName, String strJSONFlux )
103     {
104         List<String> jsonCollection = new ArrayList<String>( );
105         JSONObject jo = (JSONObject) JSONSerializer.toJSON( strJSONFlux );
106 
107         JSONArray jsonArray = jo.getJSONObject( objectName ).getJSONArray( dictionaryName );
108         Iterator iterator = jsonArray.iterator( );
109 
110         while ( iterator.hasNext( ) )
111         {
112             jsonCollection.add( (String) iterator.next( ) );
113         }
114 
115         return jsonCollection;
116     }
117 
118     public static JSONObject getJSONOBject( String strJSONFlux )
119     {
120         JSONObject jo = (JSONObject) JSONSerializer.toJSON( strJSONFlux );
121 
122         return jo;
123     }
124 
125     /**
126      * Builds a query with filters placed in parameters. Consider using {@link #buildQueryWithFilter(StringBuilder, List, String)} instead.
127      *
128      * @param strSelect
129      *            the select of the query
130      * @param listStrFilter
131      *            the list of filter to add in the query
132      * @param strOrder
133      *            the order by of the query
134      * @return a query
135      */
136     public static String buildRequetteWithFilter( String strSelect, List<String> listStrFilter, String strOrder )
137     {
138         return buildQueryWithFilter( new StringBuilder( strSelect ), listStrFilter, strOrder );
139     }
140 
141     /**
142      * Builds a query with filters placed in parameters
143      *
144      * @param sbSQL
145      *            the beginning of the query
146      * @param listFilter
147      *            the list of filter to add in the query
148      * @param strOrder
149      *            the order by of the query
150      * @return a query
151      */
152     public static String buildQueryWithFilter( StringBuilder sbSQL, List<String> listFilter, String strOrder )
153     {
154         int nCount = 0;
155 
156         for ( String strFilter : listFilter )
157         {
158             if ( ++nCount == 1 )
159             {
160                 sbSQL.append( ConstanteUtils.CONSTANTE_SQL_WHERE );
161             }
162 
163             sbSQL.append( strFilter );
164 
165             if ( nCount != listFilter.size( ) )
166             {
167                 sbSQL.append( ConstanteUtils.CONSTANTE_SQL_AND );
168             }
169         }
170 
171         if ( strOrder != null )
172         {
173             sbSQL.append( strOrder );
174         }
175 
176         return sbSQL.toString( );
177     }
178 
179     /**
180      * Retourne l'emplacement du pom
181      *
182      * @param strBasePath
183      * @param strPluginName
184      * @return
185      */
186     public static String getPathPomFile( String strPathSite )
187     {
188         return strPathSite + File.separator + ConstanteUtils.CONSTANTE_POM_XML;
189     }
190 
191     /**
192      * Retourne l'emplacement du pom
193      *
194      * @param strBasePath
195      * @param strPluginName
196      * @return
197      */
198     public static String getPathUpgradeFiles( String strPathSite )
199     {
200 
201         String strPath = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_UPGRADE_DIRECTORY_PATH );
202         StringBuffer strBuffer = new StringBuffer( strPathSite );
203 
204         for ( String strP : strPath.split( ConstanteUtils.CONSTANTE_SEPARATOR_SLASH ) )
205         {
206             strBuffer.append( File.separator );
207             strBuffer.append( strP );
208 
209         }
210 
211         return strBuffer.toString( );
212     }
213 
214     /**
215      * Retourne l'emplacement du pom
216      *
217      * @param strBasePath
218      * @param strPluginName
219      * @return
220      */
221     public static String getPathUpgradeFile( String strPathSite, String strFileName )
222     {
223 
224         StringBuffer strBuffer = new StringBuffer( getPathUpgradeFiles( strPathSite ) );
225         strBuffer.append( File.separator );
226         strBuffer.append( strFileName );
227         return strBuffer.toString( );
228     }
229 
230     /**
231      * Retourne l'emplacement du pom
232      *
233      * @param strBasePath
234      * @param strPluginName
235      * @return
236      */
237     public static String getPathArchiveGenerated( String strPathSite, String strWarName, String strExtension )
238     {
239         // Return the only one WAR file in target folder
240         List<String> listFileInTarget = FileUtil.list( strPathSite + File.separator + ConstanteUtils.CONSTANTE_TARGET, strExtension, false );
241         if ( !CollectionUtils.isEmpty( listFileInTarget ) && listFileInTarget.size( ) == 1 )
242         {
243             return strPathSite + File.separator + ConstanteUtils.CONSTANTE_TARGET + File.separator + listFileInTarget.get( 0 );
244         }
245         // Else return the specific WAR
246         else
247             if ( strWarName != null )
248             {
249                 return strPathSite + File.separator + ConstanteUtils.CONSTANTE_TARGET + File.separator + strWarName + strExtension;
250             }
251             else
252             {
253                 // Else return the first WAR found recursively
254                 List<String> listFileInTargetRecursive = FileUtil.list( strPathSite + File.separator + ConstanteUtils.CONSTANTE_TARGET, strExtension, true );
255                 if ( !listFileInTargetRecursive.isEmpty( ) && listFileInTargetRecursive.size( ) == 1 )
256                 {
257                     return strPathSite + File.separator + ConstanteUtils.CONSTANTE_TARGET + File.separator + listFileInTarget.get( 0 );
258                 }
259             }
260         return null;
261     }
262 
263     /**
264      * Retourne l'emplacement du pom
265      *
266      * @param strBasePath
267      * @param strPluginName
268      * @return
269      */
270     public static String getPathCheckoutSite( String strSiteName )
271     {
272         String strCheckoutBasePath = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_CHECKOUT_BASE_PAH );
273 
274         return strCheckoutBasePath + File.separator + strSiteName;
275     }
276 
277     /**
278      * convert a string to int
279      *
280      * @param strParameter
281      *            the string parameter to convert
282      * @return the conversion
283      */
284     public static int getIntegerParameter( String strParameter )
285     {
286         int nIdParameter = -1;
287 
288         try
289         {
290             if ( ( strParameter != null ) && strParameter.matches( ConstanteUtils.REGEX_ID ) )
291             {
292                 nIdParameter = Integer.parseInt( strParameter );
293             }
294         }
295         catch( NumberFormatException ne )
296         {
297             AppLogService.error( ne );
298         }
299 
300         return nIdParameter;
301     }
302 
303     public static SvnUser getSvnUser( int nIdAdminUser, Locale locale )
304     {
305 
306         SvnUser mavenUser = null;
307         boolean bUsedApplicationAccount = AppPropertiesService.getPropertyBoolean( ConstanteUtils.PROPERTY_SVN_USED_DEPLOYMENT_ACCOUNT, false );
308         if ( !bUsedApplicationAccount )
309 
310         {
311 
312             String strIdAttributeLogin = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_ADMINUSER_ID_ATTRIBUTE_SVN_LOGIN );
313             String strIdAttributePasssword = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_ADMINUSER_ID_ATTRIBUTE_SVN_PASSWORD );
314             String strLoginValue = null;
315             String strPasswordValue = null;
316 
317             Map<String, Object> mapAttributeUser = AdminUserFieldService.getAdminUserFields( nIdAdminUser, locale );
318 
319             if ( mapAttributeUser.containsKey( strIdAttributeLogin ) && mapAttributeUser.containsKey( strIdAttributePasssword ) )
320             {
321                 strLoginValue = ( (ArrayList<AdminUserField>) mapAttributeUser.get( strIdAttributeLogin ) ).get( 0 ).getValue( );
322                 strPasswordValue = ( (ArrayList<AdminUserField>) mapAttributeUser.get( strIdAttributePasssword ) ).get( 0 ).getValue( );
323 
324                 if ( !StringUtils.isEmpty( strLoginValue ) && !( StringUtils.isEmpty( strPasswordValue ) ) )
325                 {
326                     mavenUser = new SvnUser( );
327                     mavenUser.setLogin( strLoginValue );
328                     mavenUser.setPassword( strPasswordValue );
329                 }
330             }
331         }
332         else
333         {
334             String strApplicationLogin = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_SVN_LOGIN_APPLICATION_DEPLOYMENT );
335             String strApplicationPasssword = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_SVN_PASSWORD_APPLICATION_DEPLOYMENT );
336 
337             mavenUser = new SvnUser( );
338             mavenUser.setLogin( strApplicationLogin );
339             mavenUser.setPassword( strApplicationPasssword );
340         }
341 
342         return mavenUser;
343     }
344 
345     public static JSONObject getJSONForCommandResult( CommandResult result )
346     {
347         JSONObject jo = new JSONObject( );
348         JSONObject joResult = new JSONObject( );
349 
350         try
351         {
352             jo.put( ConstanteUtils.JSON_STATUS, result.getStatus( ) );
353 
354             // pour les logs tr�s longs, on ne prend que la fin
355             StringBuffer sbLog = result.getLog( );
356             int nMaxLogSize = AppPropertiesService.getPropertyInt( ConstanteUtils.PROPERTY_MAX_LOG_SIZE, ConstanteUtils.CONSTANTE_ID_NULL );
357             String strLog;
358 
359             if ( nMaxLogSize == -ConstanteUtils.CONSTANTE_ID_NULL )
360             {
361                 nMaxLogSize = ConstanteUtils.CONSTANTE_DEFAULT_LOG_SIZE;
362             }
363 
364             // sbLog null entre le lancement du thread et la premiere requete
365             if ( sbLog != null )
366             {
367                 if ( sbLog.length( ) > nMaxLogSize )
368                 {
369                     strLog = sbLog.substring( sbLog.length( ) - nMaxLogSize );
370                 }
371                 else
372                 {
373                     strLog = sbLog.toString( );
374                 }
375             }
376             else
377             {
378                 strLog = ConstanteUtils.CONSTANTE_EMPTY_STRING;
379             }
380 
381             jo.put( ConstanteUtils.JSON_LOG, strLog );
382             jo.put( ConstanteUtils.JSON_RUNNING, result.isRunning( ) );
383             jo.put( ConstanteUtils.JSON_ERROR, result.getError( ) );
384             jo.put( ConstanteUtils.JSON_ERROR_TYPE, result.getErrorType( ) );
385 
386             for ( Entry<String, String> resultInformations : result.getResultInformations( ).entrySet( ) )
387             {
388 
389                 joResult.put( resultInformations.getKey( ), resultInformations.getValue( ) );
390             }
391             jo.put( ConstanteUtils.JSON_RESULT, joResult );
392 
393         }
394         catch( JSONException e )
395         {
396             AppLogService.error( "JSON error : " + e.getMessage( ), e );
397         }
398 
399         return jo;
400     }
401 
402     public static JSONObject getJSONForWorkflowAction( String strJspForceRedirect, String strFormError, CommandResult result, State state,
403             Collection<Action> listAction )
404     {
405         JSONObject jo = new JSONObject( );
406 
407         try
408         {
409             jo.put( ConstanteUtils.JSON_JSP_FOM_DISPLAY, ( strJspForceRedirect != null ) ? strJspForceRedirect : ConstanteUtils.CONSTANTE_EMPTY_STRING );
410 
411             jo.put( ConstanteUtils.JSON_STATE, ( state != null ) ? state.getName( ) : ConstanteUtils.CONSTANTE_EMPTY_STRING );
412             jo.put( ConstanteUtils.JSON_FORM_ERROR, ( strFormError != null ) ? strFormError : ConstanteUtils.CONSTANTE_EMPTY_STRING );
413 
414             JSONObject joAction;
415             JSONArray joListAction = new JSONArray( );
416 
417             if ( listAction != null )
418             {
419                 for ( Action action : listAction )
420                 {
421                     joAction = new JSONObject( );
422                     joAction.put( ConstanteUtils.JSON_ACTION_ID, action.getId( ) );
423                     joAction.put( ConstanteUtils.JSON_ACTION_NAME, action.getName( ) );
424                     joAction.put( ConstanteUtils.JSON_ACTION_DESCRIPTION, action.getDescription( ) );
425 
426                     joListAction.add( joAction );
427                 }
428             }
429 
430             jo.put( ConstanteUtils.JSON_ACTION_LIST, joListAction );
431 
432             jo.put( ConstanteUtils.JSON_RUNNING, ( result != null ) ? result.isRunning( ) : ConstanteUtils.CONSTANTE_EMPTY_STRING );
433             jo.put( ConstanteUtils.JSON_ERROR, ( result != null ) ? result.getError( ) : ConstanteUtils.CONSTANTE_EMPTY_STRING );
434         }
435         catch( JSONException e )
436         {
437             AppLogService.error( "JSON error : " + e.getMessage( ), e );
438         }
439 
440         return jo;
441     }
442 
443     public static JSONObject getJSONForServerAction( int nIdApplication, String strCodeEnvironment, String strServerCodeInstance,
444             String strServerApplicationType, String strJspForceRedirect, CommandResult result, List<IAction> listServersActions, Integer newServerStatus,
445             Integer nIdFastApplicationData )
446     {
447         JSONObject jo = getJSONForCommandResult( result );
448 
449         try
450         {
451             jo.put( ConstanteUtils.JSON_JSP_FOM_DISPLAY, ( strJspForceRedirect != null ) ? strJspForceRedirect : ConstanteUtils.CONSTANTE_EMPTY_STRING );
452 
453         }
454         catch( JSONException e )
455         {
456             AppLogService.error( "JSON error : " + e.getMessage( ), e );
457         }
458         JSONObject joAction;
459         JSONArray joListAction = new JSONArray( );
460 
461         if ( listServersActions != null )
462         {
463             for ( IAction action : listServersActions )
464             {
465                 if ( action.isDisplay( ) && ( action.getStatus( ) == null || action.getStatus( ).equals( newServerStatus ) ) )
466                 {
467 
468                     joAction = new JSONObject( );
469                     joAction.put( ConstanteUtils.JSON_ACTION_CODE, action.getCode( ) );
470                     joAction.put( ConstanteUtils.JSON_ACTION_NAME, action.getName( ) );
471                     joAction.put( ConstanteUtils.JSON_ACTION_ICON_CSS_CLASS, action.getIconCssClass( ) );
472                     joListAction.add( joAction );
473                 }
474             }
475         }
476         jo.put( ConstanteUtils.JSON_ACTION_LIST, joListAction );
477         jo.put( ConstanteUtils.JSON_SERVER_STATUS, ( newServerStatus != null ) ? newServerStatus : ConstanteUtils.CONSTANTE_EMPTY_STRING );
478         jo.put( ConstanteUtils.JSON_ID_APPLIACTION, nIdApplication );
479         jo.put( ConstanteUtils.JSON_CODE_ENVIRONMENT, strCodeEnvironment );
480         jo.put( ConstanteUtils.JSON_CODE_SERVER_APPLICATION_INSTANCE, strServerCodeInstance );
481         jo.put( ConstanteUtils.JSON_SERVER_APPLICATION_TYPE, strServerApplicationType );
482         jo.put( ConstanteUtils.JSON_ID_FAST_APPLICATION_DATA, nIdFastApplicationData );
483         return jo;
484     }
485 
486     public static int getIdWorkflowDeploy( String strWorkflowType )
487     {
488 
489         int nIdWorkflow = AppPropertiesService.getPropertyInt( ConstanteUtils.PROPERTY_ID_WORKFLOW_PREFIX + strWorkflowType, ConstanteUtils.CONSTANTE_ID_NULL );
490         return nIdWorkflow;
491     }
492 
493     public static void startCommandResult( AbstractWorkflowDeployContext context )
494     {
495         CommandResultter/modules/fastdeployapplication/business/CommandResult.html#CommandResult">CommandResult commandResult = new CommandResult( );
496         startCommandResult( commandResult );
497         context.setCommandResult( commandResult );
498 
499     }
500 
501     public static void startCommandResult( CommandResult commandResult )
502     {
503 
504         commandResult.setLog( new StringBuffer( ) );
505         commandResult.setRunning( true );
506         commandResult.setStatus( CommandResult.STATUS_OK );
507     }
508 
509     public static void stopCommandResult( AbstractWorkflowDeployContext context )
510     {
511         stopCommandResult( context.getCommandResult( ) );
512     }
513 
514     public static void stopCommandResult( CommandResult commandResult )
515     {
516         commandResult.setRunning( false );
517     }
518 
519     public static void addTechnicalError( CommandResult commandResult, String strError, Exception e )
520     {
521 
522         if ( e != null )
523         {
524             AppLogService.error( strError, e );
525         }
526         else
527         {
528             AppLogService.error( strError );
529         }
530 
531         if ( commandResult != null )
532         {
533             commandResult.setError( strError );
534             commandResult.setStatus( CommandResult.STATUS_ERROR );
535             commandResult.setRunning( false );
536             commandResult.setErrorType( CommandResult.ERROR_TYPE_STOP );
537         }
538     }
539 
540     public static void addTechnicalError( CommandResult commandResult, String strError )
541     {
542         addTechnicalError( commandResult, strError, null );
543     }
544 
545     public static ReferenceList addEmptyRefenceItem( ReferenceList referenceList )
546     {
547         ReferenceList referenceList2 = new ReferenceList( );
548 
549         ReferenceItem referenceItem = new ReferenceItem( );
550 
551         referenceItem.setCode( ConstanteUtils.CONSTANTE_EMPTY_STRING );
552         referenceItem.setName( ConstanteUtils.CONSTANTE_EMPTY_STRING );
553 
554         referenceList2.add( 0, referenceItem );
555         referenceList2.addAll( referenceList );
556 
557         return referenceList2;
558     }
559 
560     public static ActionParameter [ ] getActionParameters( HttpServletRequest request, List<String> listParameterNames )
561     {
562         if ( listParameterNames != null )
563         {
564             List<ActionParameter> listActionParameters = new ArrayList<ActionParameter>( );
565             ActionParameter actionParameter;
566 
567             for ( String param : listParameterNames )
568             {
569                 actionParameter = new ActionParameter( );
570                 actionParameter.setName( param );
571                 actionParameter.setValue( request.getParameter( param ) );
572                 listActionParameters.add( actionParameter );
573             }
574 
575             return listActionParameters.toArray( new ActionParameter [ listParameterNames.size( )] );
576         }
577 
578         return null;
579     }
580 
581     public static ReferenceList getReferenceListServerType( Locale locale )
582     {
583         ReferenceList referenceList = new ReferenceList( );
584         referenceList.addItem( ConstanteUtils.CONSTANTE_EMPTY_STRING, ConstanteUtils.CONSTANTE_EMPTY_STRING );
585         referenceList.addItem( ConstanteUtils.CONSTANTE_SERVER_TOMCAT,
586                 I18nService.getLocalizedString( ConstanteUtils.PROPERTY_SERVER_TYPE_TOMCAT_LABEL, locale ) );
587         referenceList.addItem( ConstanteUtils.CONSTANTE_SERVER_MYSQL,
588                 I18nService.getLocalizedString( ConstanteUtils.PROPERTY_SERVER_TYPE_MYSQL_LABEL, locale ) );
589         referenceList.addItem( ConstanteUtils.CONSTANTE_SERVER_HTTPD,
590                 I18nService.getLocalizedString( ConstanteUtils.PROPERTY_SERVER_TYPE_HTTPD_LABEL, locale ) );
591 
592         return referenceList;
593     }
594 
595     public static ReferenceList getReferenceListAction( List<IAction> listAction )
596     {
597         ReferenceList referenceList = new ReferenceList( );
598         referenceList.addItem( ConstanteUtils.CONSTANTE_EMPTY_STRING, ConstanteUtils.CONSTANTE_EMPTY_STRING );
599 
600         for ( IAction action : listAction )
601         {
602             referenceList.addItem( getActionKey( action.getCode( ), action.getServerType( ) ), action.getName( ) );
603         }
604 
605         return referenceList;
606     }
607 
608     public static String getActionKey( String strCode, String strServerType )
609     {
610         return strCode + "_" + strServerType;
611     }
612 
613     public static ReferenceList getSimpleReferenceList( List<String> list )
614     {
615         ReferenceList reflist = new ReferenceList( );
616         if ( list != null )
617         {
618 
619             for ( String strCode : list )
620             {
621                 reflist.addItem( strCode, strCode );
622 
623             }
624         }
625         return reflist;
626     }
627 
628     /**
629      * Get the VCS service from the repo type
630      * 
631      * @param strKey
632      *            the repo type key
633      * @return the VCS service
634      */
635     public static IVCSService getVCSService( String strKey )
636     {
637         switch( strKey )
638         {
639             case ConstanteUtils.CONSTANTE_REPO_TYPE_GITHUB:
640                 return SpringContextService.getBean( ConstanteUtils.BEAN_GITHUB_SERVICE );
641             case ConstanteUtils.CONSTANTE_REPO_TYPE_SVN:
642                 return SpringContextService.getBean( ConstanteUtils.BEAN_SVN_SERVICE );
643             case ConstanteUtils.CONSTANTE_REPO_TYPE_GITLAB:
644                 return SpringContextService.getBean( ConstanteUtils.BEAN_GITLAB_SERVICE );
645         }
646         return null;
647     }
648 
649     /**
650      * Get an empty VCS user based on the repo type of the provided application
651      * 
652      * @param application
653      *            the Application
654      * @return an empty VCS user based on the repo type of the provided application
655      */
656     public static AbstractVCSUser getVCSUser( FastDeployApplicationData application )
657     {
658         switch( application.getRepoType( ) )
659         {
660             case ConstanteUtils.CONSTANTE_REPO_TYPE_GITHUB:
661                 return new GitUser( );
662             case ConstanteUtils.CONSTANTE_REPO_TYPE_SVN:
663                 return new SvnUser( );
664             case ConstanteUtils.CONSTANTE_REPO_TYPE_GITLAB:
665                 return new GitUser( );
666         }
667         return null;
668     }
669 
670     /**
671      * Get the VCS user from the request and the given application
672      * 
673      * @param request
674      *            the HttpServletRequest
675      * @param application
676      *            the Application
677      * @return the VCS user
678      */
679     public static AbstractVCSUser getVCSUser( HttpServletRequest request, FastDeployApplicationData application )
680     {
681         String strLogin = request.getParameter( ConstanteUtils.PARAM_LOGIN );
682         String strPassword = request.getParameter( ConstanteUtils.PARAM_PASSWORD );
683         AbstractVCSUser user = getVCSUser( application );
684         if ( strLogin != null && strPassword != null )
685         {
686 
687             user.setLogin( strLogin );
688             user.setPassword( strPassword );
689         }
690         return user;
691     }
692 
693     /**
694      * Delete the local repository of the application sources
695      * 
696      * @param context
697      * @param application
698      * @return
699      */
700     public static String deleteLocalRepository( AbstractWorkflowDeployContext context, FastDeployApplicationData application )
701     {
702         String strLocalPath = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_CHECKOUT_BASE_PAH ) + ConstanteUtils.CONSTANTE_SEPARATOR_SLASH
703                 + application.getArtifactId( );
704         Path path = Paths.get( strLocalPath );
705         try
706         {
707             if ( Files.exists( path ) )
708             {
709                 FileUtils.forceDelete( path.toFile( ) );
710             }
711         }
712         catch( IOException e )
713         {
714             context.getCommandResult( ).getLog( ).append( "Unable to delete the local directory " + strLocalPath + " \n" );
715             throw new AppException( "Unable to delete the local directory " + strLocalPath, e );
716         }
717         return null;
718     }
719 
720     public static boolean isPrivateRepo( FastDeployApplicationData application )
721     {
722         IVCSService vcsService = DeploymentUtils.getVCSService( application.getRepoType( ) );
723         return vcsService.isPrivate( );
724     }
725 
726     public static Collection<Action> getActionList( AbstractWorkflowDeployContext context )
727     {
728         return WorkflowService.getInstance( ).getActions( context.getId( ), AbstractWorkflowDeployContext.WORKFLOW_RESOURCE_TYPE, context.getIdWorkflow( ),
729                 null );
730     }
731 
732     public static State getState( AbstractWorkflowDeployContext context )
733     {
734         return WorkflowService.getInstance( ).getState( context.getId( ), AbstractWorkflowDeployContext.WORKFLOW_RESOURCE_TYPE, context.getIdWorkflow( ),
735                 ConstanteUtils.CONSTANTE_ID_NULL );
736     }
737 
738     public static String getDownloadUrl( ServerApplicationInstance serverApplicationInstance, FastDeployApplicationData data, String strDatabase,
739             String strDumpFileName )
740     {
741 
742         return "jsp/site/Portal.jsp?page=fastDeployDownloadXPage&action=doDownloadDumpFile&code_application=" + data.getApplicationCode( )
743                 + "&code_environment=" + serverApplicationInstance.getCodeEnvironment( ) + "&code_server_application_instance_sql="
744                 + serverApplicationInstance.getCode( ) + "&code_database=" + strDatabase + "&plugin_name=deployment" + "&server_application_type="
745                 + serverApplicationInstance.getType( ) + "&id_fast_application_data=" + data.getIdApplicationData( ) + "&id=" + data.getIdApplication( ) + "&"
746                 + ConstanteUtils.PARAM_DUMP_FILE_NAME + "=" + strDumpFileName;
747 
748     }
749 }