1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package fr.paris.lutece.plugins.indicator.service;
35
36 import fr.paris.lutece.plugins.indicator.business.Indicator;
37 import fr.paris.lutece.plugins.indicator.business.IndicatorHistory;
38 import fr.paris.lutece.plugins.indicator.business.IndicatorHistoryHome;
39 import fr.paris.lutece.plugins.indicator.business.IndicatorHome;
40 import fr.paris.lutece.portal.service.spring.SpringContextService;
41 import fr.paris.lutece.portal.service.util.AppLogService;
42
43 import java.util.List;
44
45
46
47
48
49 public class IndicatorUpdaterService
50 {
51 private static List<IndicatorFetcher> _listFetchers;
52 private static IndicatorUpdaterService _singleton;
53
54
55
56
57
58 public static synchronized IndicatorUpdaterService instance( )
59 {
60 if ( _singleton == null )
61 {
62 _singleton = new IndicatorUpdaterService( );
63 _singleton.registerFetchers( );
64 }
65
66 return _singleton;
67 }
68
69
70
71
72 private void registerFetchers( )
73 {
74 _listFetchers = SpringContextService.getBeansOfType( IndicatorFetcher.class );
75
76 for ( IndicatorFetcher fetcher : _listFetchers )
77 {
78 AppLogService.info( "New Indicator fetcher registered : " + fetcher.getName( ) );
79 }
80 }
81
82
83
84
85
86 public String doFetch( )
87 {
88 StringBuilder sbLogs = new StringBuilder( );
89
90 for ( IndicatorFetcher fetcher : _listFetchers )
91 {
92 try
93 {
94 List<Indicator> listIndicators = fetcher.fetch( );
95
96 for ( Indicator indicator : listIndicators )
97 {
98 IndicatorHome.updateValue( indicator );
99 sbLogs.append( "Indicator '" ).append( indicator.getIndKey( ) ).append( "' updated. New value is : " )
100 .append( indicator.getValue( ) ).append( '\n' );
101
102 createHistory( indicator );
103 }
104 }
105 catch ( Exception e )
106 {
107 AppLogService.error( "Error fetching indicator " + e.getMessage( ), e );
108 }
109 }
110
111 return sbLogs.toString( );
112 }
113
114
115
116
117
118 private void createHistory( Indicator indicator )
119 {
120 Indicator indicatorFull = IndicatorHome.findByKey( indicator.getIndKey( ) );
121 String strTimeCode = TimeCodeService.getCurrentTimeCode( indicatorFull.getHistoryPeriod( ) );
122
123 IndicatorHistory history = IndicatorHistoryHome.findByPrimaryKey( indicator.getIndKey( ), strTimeCode );
124
125 if ( history != null )
126 {
127 IndicatorHistoryHome.remove( indicator.getIndKey( ), strTimeCode );
128 }
129
130 history = new IndicatorHistory( );
131 history.setIndKey( indicator.getIndKey( ) );
132 history.setTimeCode( strTimeCode );
133 history.setIndValue( indicator.getValue( ) );
134
135 if ( indicator.getIndTarget( ) != 0 )
136 {
137 history.setIndTarget( indicator.getIndTarget( ) );
138 }
139 else
140 {
141 history.setIndTarget( indicatorFull.getIndTarget( ) );
142 }
143
144 IndicatorHistoryHome.create( history );
145 }
146 }