source: ether_megapoli/trunk/service/implementation/com/ether/EtherServiceImpl.java @ 557

Last change on this file since 557 was 557, checked in by vmipsl, 12 years ago

simulation

  • display real data
  • getPlateformsByParameter
File size: 38.0 KB
Line 
1package com.ether;
2
3import com.ether.dao.JeuDAO;
4import com.ether.dao.McoDAO;
5import com.ether.dao.MeasureDAO;
6import com.ether.dao.ParameterDAO;
7import com.ether.dao.PersonDAO;
8import com.ether.dao.PlateformDAO;
9import com.ether.dao.UserDAO;
10import com.ether.dao.ValueDAO;
11import com.ether.dao.simulation.AttributeDAO;
12import com.ether.dao.simulation.DimensionDAO;
13import com.ether.dao.simulation.SimulationDAO;
14import com.ether.dao.simulation.VariableDAO;
15import com.ether.mco.Mco;
16import com.ether.mco.McoFilter;
17import com.ether.simulation.Attribute;
18import com.ether.simulation.Dimension;
19import com.ether.simulation.Simulation;
20import com.ether.simulation.SimulationFilter;
21import com.ether.simulation.Variable;
22import com.ether.user.User;
23import com.ether.user.UserFilter;
24import com.ether.user.UserState;
25import com.medias.annuaire.Personne;
26import com.medias.database.objects.Jeu;
27import com.medias.database.objects.Parametre;
28import com.medias.database.objects.Plateforme;
29import org.apache.commons.logging.Log;
30import org.apache.commons.logging.LogFactory;
31import org.jetbrains.annotations.NotNull;
32import org.jetbrains.annotations.Nullable;
33import org.springframework.beans.factory.annotation.Required;
34import org.springframework.transaction.annotation.Transactional;
35
36import javax.xml.bind.JAXBContext;
37import javax.xml.bind.JAXBException;
38import javax.xml.bind.Marshaller;
39import javax.xml.bind.PropertyException;
40import javax.xml.bind.Unmarshaller;
41import java.io.BufferedReader;
42import java.io.File;
43import java.io.IOException;
44import java.io.InputStreamReader;
45import java.util.ArrayList;
46import java.util.Date;
47import java.util.HashSet;
48import java.util.List;
49import java.util.Set;
50
51/**
52 * @author vmipsl
53 * @date 07 mar 2011
54 */
55public class EtherServiceImpl
56        implements EtherService
57{
58    @Nullable
59    @Transactional(readOnly = true)
60    public List<Plateforme> getAllPlateforms()
61            throws ServiceException
62    {
63        try
64        {
65            return _plateformDAO.getAllPlateforms();
66        }
67        catch( PersistenceException e )
68        {
69            throw new ServiceException( ServiceException.ServiceCode.PLATEFORM_NOT_FOUND, e );
70        }
71    }
72
73    @Nullable
74    @Transactional(readOnly = true)
75    public Plateforme getPlateformById( @Nullable final Integer plateformId )
76            throws ServiceException
77    {
78        if( null == plateformId )
79            return null;
80        try
81        {
82            return _plateformDAO.getPlateformById( plateformId );
83        }
84        catch( PersistenceException e )
85        {
86            throw new ServiceException( ServiceException.ServiceCode.PLATEFORM_NOT_FOUND, e );
87        }
88    }
89
90    @Nullable
91    @Transactional(readOnly = true)
92    public Parametre getParameterById( @Nullable final Integer parameterId )
93            throws ServiceException
94    {
95        if( null == parameterId )
96            return null;
97        try
98        {
99            return _parameterDAO.getParameterById( parameterId );
100        }
101        catch( PersistenceException e )
102        {
103            throw new ServiceException( ServiceException.ServiceCode.PARAMETER_NOT_FOUND, e );
104        }
105    }
106
107    @NotNull
108    @Transactional(readOnly = true)
109    public List<Parametre> getParametersByPlateformId( @NotNull final Integer plateformId )
110            throws ServiceException
111    {
112        try
113        {
114            return _parameterDAO.getParametersByPlateformId( plateformId );
115        }
116        catch( PersistenceException e )
117        {
118            throw new ServiceException( ServiceException.ServiceCode.PARAMETER_NOT_FOUND, e );
119        }
120    }
121
122    @NotNull
123    @Transactional(readOnly = true)
124    public <T1, T2, T3> Data<T1[], T2[], T3[]> getListsByPlateformByParameterByPeriodForTimeSerie( @NotNull final Integer plateformId, @NotNull final Integer parameterId, @Nullable final Date dateBegin, @Nullable final Date dateEnd )
125            throws ServiceException
126    {
127        try
128        {
129            return _valueDAO.getListsByPlateformByParameterByPeriodForTimeSerie( plateformId, parameterId, dateBegin, dateEnd );
130        }
131        catch( PersistenceException e )
132        {
133            throw new ServiceException( ServiceException.ServiceCode.VALUE_NOT_FOUND, e );
134        }
135    }
136
137    @NotNull
138    @Transactional(readOnly = true)
139    public <T1, T2, T3> Data<List<T1>, List<T2>, List<T3>> getListsByPlateformByParameterByPeriodFor2D( @NotNull final Integer plateformId, @NotNull final Integer parameterId, @Nullable final Date dateBegin, @Nullable final Date dateEnd )
140            throws ServiceException
141    {
142        try
143        {
144            return _valueDAO.getListsByPlateformByParameterByPeriodFor2D( plateformId, parameterId, dateBegin, dateEnd );
145        }
146        catch( PersistenceException e )
147        {
148            throw new ServiceException( ServiceException.ServiceCode.VALUE_NOT_FOUND, e );
149        }
150    }
151
152    @NotNull
153    @Transactional(readOnly = true)
154    public <T1, T2, T3> Data<T1[], T2[], T3[]> getArraysByPlateformByParameterByPeriodFor2D( @NotNull final Integer plateformId, @NotNull final Integer parameterId, @Nullable final Date dateBegin, @Nullable final Date dateEnd )
155            throws ServiceException
156    {
157        try
158        {
159            return _valueDAO.getArraysByPlateformByParameterByPeriodFor2D( plateformId, parameterId, dateBegin, dateEnd );
160        }
161        catch( PersistenceException e )
162        {
163            throw new ServiceException( ServiceException.ServiceCode.VALUE_NOT_FOUND, e );
164        }
165    }
166
167    @NotNull
168    @Transactional(readOnly = true)
169    public Integer getNumberValuesByPlateformByParameterByPeriod( @NotNull final List<Pair<Integer, Integer>> pairs, @Nullable final Date beginDate, @Nullable final Date endDate )
170            throws ServiceException
171    {
172        try
173        {
174            Integer number = 0;
175            for( final Pair pair : pairs )
176                number += _valueDAO.getNumberValuesByPlateformByParameterByPeriod( (Integer) pair.getFirstValue(), (Integer) pair.getSecondValue(), beginDate, endDate );
177
178            return number;
179        }
180        catch( PersistenceException e )
181        {
182            throw new ServiceException( ServiceException.ServiceCode.VALUE_NOT_FOUND, e );
183        }
184    }
185
186    @Nullable
187    @Transactional(readOnly = true)
188    public Date getFirstDate()
189            throws ServiceException
190    {
191        try
192        {
193            return _measureDAO.getFirstDate();
194        }
195        catch( PersistenceException e )
196        {
197            throw new ServiceException( ServiceException.ServiceCode.DATE_NOT_FOUND, e );
198        }
199    }
200
201    @Nullable
202    @Transactional(readOnly = true)
203    public Date getLastDate()
204            throws ServiceException
205    {
206        try
207        {
208            return _measureDAO.getLastDate();
209        }
210        catch( PersistenceException e )
211        {
212            throw new ServiceException( ServiceException.ServiceCode.DATE_NOT_FOUND, e );
213        }
214    }
215
216    @Nullable
217    @Transactional(readOnly = true)
218    public User getUserById( @NotNull final Integer userId )
219            throws ServiceException
220    {
221        try
222        {
223            return _userDAO.selectByPrimaryKey( userId );
224        }
225        catch( PersistenceException e )
226        {
227            throw new ServiceException( ServiceException.ServiceCode.USER_NOT_FOUND, e );
228        }
229    }
230
231    @Nullable
232    @Transactional(readOnly = true)
233    public User getUserByEmail( @NotNull final String userEmail )
234            throws ServiceException
235    {
236        try
237        {
238            return _userDAO.getUserByEmail( userEmail );
239        }
240        catch( PersistenceException e )
241        {
242            throw new ServiceException( ServiceException.ServiceCode.USER_NOT_FOUND, e );
243        }
244    }
245
246    @NotNull
247    @Transactional(rollbackFor = Exception.class)
248    public Integer createUser( @NotNull final User user )
249            throws ServiceException
250    {
251        try
252        {
253            return _userDAO.insert( user );
254        }
255        catch( PersistenceException e )
256        {
257            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
258        }
259    }
260
261    @NotNull
262    @Transactional(readOnly = true)
263    public List<User> getAllUsers()
264            throws ServiceException
265    {
266        try
267        {
268            return _userDAO.selectAll();
269        }
270        catch( PersistenceException e )
271        {
272            throw new ServiceException( ServiceException.ServiceCode.USER_NOT_FOUND, e );
273        }
274    }
275
276    @NotNull
277    @Transactional(readOnly = true)
278    public List<User> getAllUsersByNameOrder()
279            throws ServiceException
280    {
281        try
282        {
283            return _userDAO.getAllUsersByNameOrder();
284        }
285        catch( PersistenceException e )
286        {
287            throw new ServiceException( ServiceException.ServiceCode.USER_NOT_FOUND, e );
288        }
289    }
290
291    @NotNull
292    @Transactional(readOnly = true)
293    public List<User> getUsersByState( @NotNull final UserState userState )
294            throws ServiceException
295    {
296        try
297        {
298            return _userDAO.getUsersByState( userState );
299        }
300        catch( PersistenceException e )
301        {
302            throw new ServiceException( ServiceException.ServiceCode.USER_NOT_FOUND, e );
303        }
304    }
305
306    @Transactional(rollbackFor = Exception.class)
307    public void removeUserById( @NotNull final Integer userId )
308            throws ServiceException
309    {
310        try
311        {
312            _userDAO.deleteByPrimaryKey( userId );
313        }
314        catch( PersistenceException e )
315        {
316            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
317        }
318    }
319
320    @Transactional(rollbackFor = Exception.class)
321    public void updateUser( @NotNull final User user )
322            throws ServiceException
323    {
324        try
325        {
326            _userDAO.update( user );
327        }
328        catch( PersistenceException e )
329        {
330            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
331        }
332    }
333
334    @Transactional(rollbackFor = Exception.class)
335    public void acceptOrRefuseUser( @NotNull final Integer userId, final boolean isAccepted )
336            throws ServiceException
337    {
338        try
339        {
340            final User user = _userDAO.selectByPrimaryKey( userId );
341            if( isAccepted )
342                user.setState( UserState.ACCEPTED );
343            else
344                user.setState( UserState.REFUSED );
345            _userDAO.update( user );
346        }
347        catch( PersistenceException e )
348        {
349            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
350        }
351    }
352
353    @Nullable
354    @Transactional(readOnly = true)
355    public Personne getPeopleByEmail( @NotNull final String email )
356            throws ServiceException
357    {
358        try
359        {
360            return _personDAO.getPersonByEmail( email );
361        }
362        catch( PersistenceException e )
363        {
364            throw new ServiceException( ServiceException.ServiceCode.PERSON_NOT_FOUND, e );
365        }
366    }
367
368    @Transactional(readOnly = true)
369    public PaginatedResult<User> searchUsers( @NotNull final UserFilter filter )
370            throws ServiceException
371    {
372        try
373        {
374            return _userDAO.search( filter );
375        }
376        catch( PersistenceException e )
377        {
378            throw new ServiceException( ServiceException.ServiceCode.USER_NOT_FOUND, e );
379        }
380    }
381
382    @Transactional(readOnly = true)
383    public PaginatedResult<Mco> searchMcos( @NotNull final McoFilter filter )
384            throws ServiceException
385    {
386        try
387        {
388            return _mcoDAO.search( filter );
389        }
390        catch( PersistenceException e )
391        {
392            throw new ServiceException( ServiceException.ServiceCode.REQUEST_NOT_FOUND, e );
393        }
394    }
395
396    @Nullable
397    @Transactional(readOnly = true)
398    public Mco getMcoByCode( @NotNull final String code )
399            throws ServiceException
400    {
401        try
402        {
403            return _mcoDAO.getMcoByCode( code );
404        }
405        catch( PersistenceException e )
406        {
407            throw new ServiceException( ServiceException.ServiceCode.REQUEST_NOT_FOUND, e );
408        }
409    }
410
411    @NotNull
412    @Transactional(rollbackFor = Exception.class)
413    public Integer createMco( @NotNull final Mco mco )
414            throws ServiceException
415    {
416        try
417        {
418            return _mcoDAO.insert( mco );
419        }
420        catch( PersistenceException e )
421        {
422            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
423        }
424    }
425
426    @Transactional(rollbackFor = Exception.class)
427    public void removeMcoById( @NotNull final Integer mcoId )
428            throws ServiceException
429    {
430        try
431        {
432            _mcoDAO.deleteByPrimaryKey( mcoId );
433        }
434        catch( PersistenceException e )
435        {
436            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
437        }
438    }
439
440    @Transactional(rollbackFor = Exception.class)
441    public void updateMco( @NotNull final Mco mco )
442            throws ServiceException
443    {
444        try
445        {
446            _mcoDAO.update( mco );
447        }
448        catch( PersistenceException e )
449        {
450            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
451        }
452    }
453
454    @Nullable
455    @Transactional(readOnly = true)
456    public Mco getMcoById( @NotNull final Integer requestId )
457            throws ServiceException
458    {
459        try
460        {
461            return _mcoDAO.selectByPrimaryKey( requestId );
462        }
463        catch( PersistenceException e )
464        {
465            throw new ServiceException( ServiceException.ServiceCode.REQUEST_NOT_FOUND, e );
466        }
467    }
468
469    /**
470     * This method manage the sub-menus for the list of parameters (to avoid multiple "Particle Concentration" by example)
471     * The fullParameters must be ordered with parameterName ascendant
472     *
473     * @param fullParameters
474     * @return
475     */
476    @NotNull
477    public List<List<Parametre>> manageMenusForParameterList( @NotNull final List<Parametre> fullParameters )
478    {
479        final List<List<Parametre>> parameterListWithMenu = new ArrayList<List<Parametre>>();
480
481        int i = 0;
482        while( i < fullParameters.size() )
483        {
484            final Parametre fullParameter = fullParameters.get( i );
485            final int firstIndex = fullParameters.indexOf( fullParameter );
486            final int lastIndex = fullParameters.lastIndexOf( fullParameter );
487            final List<Parametre> parameters = fullParameters.subList( firstIndex, lastIndex + 1 );
488            parameterListWithMenu.add( parameters );
489            i += parameters.size();
490        }
491
492        return parameterListWithMenu;
493    }
494
495    @Nullable
496    @Transactional(readOnly = true)
497    public List<Parametre> getAllParametersOrderByCategoryByName()
498            throws ServiceException
499    {
500        try
501        {
502            return _parameterDAO.getAllParametersOrderByCategoryByName();
503        }
504        catch( PersistenceException e )
505        {
506            throw new ServiceException( ServiceException.ServiceCode.PARAMETER_NOT_FOUND, e );
507        }
508    }
509
510    @Nullable
511    @Transactional(readOnly = true)
512    public List<Date> getAllMeasureDateByPlateformId( @NotNull final Integer plateformId )
513            throws ServiceException
514    {
515        try
516        {
517            return _measureDAO.getAllMeasureDateByPlateformId( plateformId );
518        }
519        catch( PersistenceException e )
520        {
521            throw new ServiceException( ServiceException.ServiceCode.DATE_NOT_FOUND, e );
522        }
523    }
524
525    @Nullable
526    @Transactional(readOnly = true)
527    public PaginatedResult<Jeu> searchJeux( @NotNull final JeuFilter filter )
528            throws ServiceException
529    {
530        try
531        {
532            return _jeuDAO.search( filter );
533        }
534        catch( PersistenceException e )
535        {
536            throw new ServiceException( ServiceException.ServiceCode.JEU_NOT_FOUND, e );
537        }
538    }
539
540    @Transactional(rollbackFor = Exception.class)
541    public void removeJeuAndDataByName( @NotNull final String datasetName )
542            throws ServiceException
543    {
544        try
545        {
546            _jeuDAO.removeJeuAndDataByName( datasetName );
547        }
548        catch( PersistenceException e )
549        {
550            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
551        }
552    }
553
554    @Transactional(rollbackFor = Exception.class)
555    public void cleanLocalisationAndFlagTables()
556            throws ServiceException
557    {
558        try
559        {
560            _jeuDAO.cleanLocalisationAndFlagTables();
561        }
562        catch( PersistenceException e )
563        {
564            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
565        }
566    }
567
568    @Nullable
569    @Transactional(readOnly = true)
570    public Jeu getJeuById( @NotNull final Integer jeuId )
571            throws ServiceException
572    {
573        try
574        {
575            return _jeuDAO.selectByPrimaryKey( jeuId );
576        }
577        catch( PersistenceException e )
578        {
579            throw new ServiceException( ServiceException.ServiceCode.JEU_NOT_FOUND, e );
580        }
581    }
582
583    @Nullable
584    @Transactional(readOnly = true)
585    public String getDatasetNameById( @NotNull final Integer jeuId )
586            throws ServiceException
587    {
588        try
589        {
590            return _jeuDAO.getDatasetNameById( jeuId );
591        }
592        catch( PersistenceException e )
593        {
594            throw new ServiceException( ServiceException.ServiceCode.JEU_NOT_FOUND, e );
595        }
596    }
597
598    @Nullable
599    public PaginatedResult<Dimension> searchDimensions( @NotNull final SimulationFilter filter )
600            throws ServiceException
601    {
602        try
603        {
604            return _dimensionDAO.search( filter );
605        }
606        catch( PersistenceException e )
607        {
608            throw new ServiceException( ServiceException.ServiceCode.DIMENSION_NOT_FOUND, e );
609        }
610    }
611
612    @Nullable
613    public PaginatedResult<Attribute> searchAttributes( @NotNull final SimulationFilter filter )
614            throws ServiceException
615    {
616        try
617        {
618            return _attributeDAO.search( filter );
619        }
620        catch( PersistenceException e )
621        {
622            throw new ServiceException( ServiceException.ServiceCode.ATTRIBUTE_NOT_FOUND, e );
623        }
624    }
625
626    @Nullable
627    public PaginatedResult<Variable> searchVariables( @NotNull final SimulationFilter filter )
628            throws ServiceException
629    {
630        try
631        {
632            return _variableDAO.search( filter );
633        }
634        catch( PersistenceException e )
635        {
636            throw new ServiceException( ServiceException.ServiceCode.VARIABLE_NOT_FOUND, e );
637        }
638    }
639
640    @Nullable
641    public PaginatedResult<Simulation> searchSimulations( @NotNull final SimulationFilter filter )
642            throws ServiceException
643    {
644        try
645        {
646            return _simulationDAO.search( filter );
647        }
648        catch( PersistenceException e )
649        {
650            throw new ServiceException( ServiceException.ServiceCode.SIMULATION_NOT_FOUND, e );
651        }
652    }
653
654    /**
655     * This method create a directory for all ".nc" files in the simulation directory
656     * And create for each a "header_init.xml" file which contents the attributes, variables, dimensions, etc... for the simulation
657     * The second line of the "header_init.xml" file is changed by "xmlnsHeader" because of the term "xmlns" which is not ok for the "unmarshall" method
658     * The real file to work becomes "header.xml"
659     *
660     * @param simulationPath
661     */
662    public void launchNCDumpInSimulationDirectory( @NotNull final String simulationPath )
663            throws ServiceException
664    {
665        final File simulationsDirectory = new File( simulationPath );
666        for( final String fileName : simulationsDirectory.list() )
667        {
668            if( fileName.endsWith( FORMAT_FILE ) )
669            {
670                // Create directory and move simulation file into
671                final String shortFileName = fileName.substring( 0, fileName.lastIndexOf( '.' ) );
672                final String directoryName = simulationPath + File.separatorChar + shortFileName;
673                final File directory = new File( directoryName );
674                final File file = new File( simulationPath + File.separatorChar + fileName );
675                if( !directory.exists() )
676                {
677                    directory.mkdir();
678                    file.renameTo( new File( directoryName + File.separatorChar + fileName ) );
679                    try
680                    {
681                        final Runtime runtime = Runtime.getRuntime();
682                        final String headerInit = directoryName + File.separatorChar + "header_init.xml";
683                        final String[] argsNcdump = {"/bin/sh", "-c", "/usr/bin/ncdump -h -x " + directoryName + File.separatorChar + fileName + " > " + headerInit};
684                        runtime.exec( argsNcdump );
685                        EtherHelper.waitForFileWithMax( new File( headerInit ), 5000 );
686                        final String[] argsSed = {"/bin/sh", "-c", "sed s/xmlns/xmlnsHeader/ " + directoryName + File.separatorChar + "header_init.xml > " + directoryName + File.separatorChar + FILE_HEADER_NAME};
687                        runtime.exec( argsSed );
688                    }
689                    catch( IOException e )
690                    {
691                        throw new ServiceException( ServiceException.ServiceCode.ERROR_PROCESS_SIMULATION_NCDUMP, e );
692                    }
693                    catch( InterruptedException e )
694                    {
695                        throw new ServiceException( ServiceException.ServiceCode.ERROR_PROCESS_SIMULATION_NCDUMP_WAIT, e );
696                    }
697                }
698            }
699        }
700    }
701
702    /**
703     * This method insert the header and the dates (variable "Times") in database
704     * The dates are saved in database as a unique String (use to split when we need to have the real values)
705     * The new variables are separatly created in the table ....
706     * The metadata are saved in the table ....
707     *
708     * @param simulationPath
709     * @param directoryName
710     */
711    @Transactional(rollbackFor = Exception.class)
712    public void insertHeader( @NotNull final String simulationPath, @NotNull final String directoryName )
713            throws ServiceException
714    {
715        try
716        {
717            final String fileName = simulationPath + File.separatorChar + directoryName + File.separatorChar + FILE_HEADER_NAME;
718
719            final JAXBContext context = JAXBContext.newInstance( Simulation.class );
720            final Marshaller marshaller = context.createMarshaller();
721            marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
722            final Unmarshaller uMarshaller = context.createUnmarshaller();
723            final Simulation simulation = (Simulation) uMarshaller.unmarshal( new File( fileName ) );
724
725            // Extract dates for the simulation
726            final Runtime runtime = Runtime.getRuntime();
727            final String[] argsNcdump = {"/bin/sh", "-c", "ncdump -v Times " + simulationPath + File.separatorChar + directoryName + File.separatorChar + directoryName + FORMAT_FILE + " | sed -e '1,/data:/d' -e '1,/Times/d' -e '$d'"};
728            final Process exec = runtime.exec( argsNcdump );
729
730            final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( exec.getInputStream() ) );
731            final StringBuffer stringBuffer = new StringBuffer();
732            String line;
733            while( ( line = bufferedReader.readLine() ) != null )
734                stringBuffer.append( line );
735
736            final String dates = stringBuffer.toString().replaceAll( "\"", "" ).replaceAll( " ", "" ).replaceAll( ";", "" );
737            simulation.setDates( dates );
738
739            final Integer simulationId = insertSimulation( simulation );
740        }
741        catch( PropertyException e )
742        {
743            throw new ServiceException( ServiceException.ServiceCode.ERROR_PROPERTY, e );
744        }
745        catch( JAXBException e )
746        {
747            throw new ServiceException( ServiceException.ServiceCode.ERROR_JAXB, e );
748        }
749        catch( IOException e )
750        {
751            throw new ServiceException( ServiceException.ServiceCode.ERROR_PROCESS_SIMULATION_NCDUMP, e );
752        }
753    }
754
755    /**
756     * This method extract data (parameters, latitudes, longitutes) from the file corresponding to the simulation for the megapoliPlot
757     * We use ncks to extract only data for a geographic area and a date
758     * http://linux.die.net/man/1/ncks
759     * Example to see easily : ncks -H -d Time,0 -d bottom_top,0 -v APINEN out.20090701_20090705_01_SMPV4_complet.nc
760     *
761     * @param modelId
762     * @param variableName
763     * @param dateNumber            : the number of the date among all the available dates
764     * @param level
765     * @param writeInTemporaryFiles : use to debug and see the result of the process
766     * @return
767     * @throws IOException
768     * @throws ServiceException
769     */
770    @Nullable
771    @Transactional(readOnly = true)
772    public List<Double> extractValuesByModelByVariableByDateByLevelFromFile( @NotNull final Integer modelId, @NotNull final String variableName, @NotNull final Integer dateNumber, @NotNull final Integer level, final boolean writeInTemporaryFiles )
773            throws ServiceException
774    {
775        final String filePath = getLocationByModelId( modelId );
776        final String resultFile = filePath + '_' + variableName;
777
778        try
779        {
780            final Runtime runtime = Runtime.getRuntime();
781            // TODO : voir pour la précision -s "%f\n"
782            final String processString = "ncks -s \"%16.30f\\n\" -d Time," + dateNumber + " -d bottom_top," + level + " -v " + variableName + ' ' + filePath + " | sed '/^" + variableName + "/d'";
783            final String[] argsNcdump = {"/bin/sh", "-c", processString};
784            final Process exec = runtime.exec( argsNcdump );
785
786            if( writeInTemporaryFiles )
787                runtime.exec( new String[]{"/bin/sh", "-c", processString + " > " + resultFile} );
788
789            // TODO : voir avec java 7 pour utiliser le Files.readAllLines() et obtenir directement une List<>, http://adiguba.developpez.com/tutoriels/java/7/
790            final BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( exec.getInputStream() ) );
791            final List<Double> valuesList = new ArrayList<Double>();
792            String line;
793            while( ( line = bufferedReader.readLine() ) != null )
794                if( !line.isEmpty() )
795                    valuesList.add( Double.valueOf( line ) );
796
797            return valuesList;
798        }
799        catch( IOException e )
800        {
801            if( new File( resultFile ).exists() )
802                new File( resultFile ).delete();
803
804            throw new ServiceException( ServiceException.ServiceCode.ERROR_PROCESS_SIMULATION_NCDUMP, e );
805        }
806    }
807
808    @Nullable
809    @Transactional(readOnly = true)
810    public Dimension getDimensionById( @NotNull final Integer dimensionId )
811            throws ServiceException
812    {
813        try
814        {
815            return _dimensionDAO.selectByPrimaryKey( dimensionId );
816        }
817        catch( PersistenceException e )
818        {
819            throw new ServiceException( ServiceException.ServiceCode.DIMENSION_NOT_FOUND, e );
820        }
821    }
822
823    @Transactional(rollbackFor = Exception.class)
824    public void removeDimension( @NotNull final Integer dimensionId )
825            throws ServiceException
826    {
827        try
828        {
829            _dimensionDAO.deleteByPrimaryKey( dimensionId );
830        }
831        catch( PersistenceException e )
832        {
833            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
834        }
835    }
836
837    @Nullable
838    @Transactional(readOnly = true)
839    public Attribute getAttributeById( @NotNull final Integer attributeId )
840            throws ServiceException
841    {
842        try
843        {
844            return _attributeDAO.selectByPrimaryKey( attributeId );
845        }
846        catch( PersistenceException e )
847        {
848            throw new ServiceException( ServiceException.ServiceCode.ATTRIBUTE_NOT_FOUND, e );
849        }
850    }
851
852    @Transactional(rollbackFor = Exception.class)
853    public void removeAttribute( @NotNull final Integer attributeId )
854            throws ServiceException
855    {
856        try
857        {
858            _attributeDAO.deleteByPrimaryKey( attributeId );
859        }
860        catch( PersistenceException e )
861        {
862            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
863        }
864    }
865
866    @Nullable
867    @Transactional(readOnly = true)
868    public Variable getVariableById( @NotNull final Integer variableId )
869            throws ServiceException
870    {
871        try
872        {
873            return _variableDAO.selectByPrimaryKey( variableId );
874        }
875        catch( PersistenceException e )
876        {
877            throw new ServiceException( ServiceException.ServiceCode.VARIABLE_NOT_FOUND, e );
878        }
879    }
880
881    @Transactional(rollbackFor = Exception.class)
882    public void removeVariable( @NotNull final Integer variableId )
883            throws ServiceException
884    {
885        try
886        {
887            _variableDAO.deleteByPrimaryKey( variableId );
888        }
889        catch( PersistenceException e )
890        {
891            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
892        }
893    }
894
895    @Nullable
896    @Transactional(readOnly = true)
897    public Simulation getSimulationById( @NotNull final Integer simulationId )
898            throws ServiceException
899    {
900        try
901        {
902            return _simulationDAO.selectByPrimaryKey( simulationId );
903        }
904        catch( PersistenceException e )
905        {
906            throw new ServiceException( ServiceException.ServiceCode.SIMULATION_NOT_FOUND, e );
907        }
908    }
909
910    @Transactional(rollbackFor = Exception.class)
911    public void removeSimulation( @NotNull final Integer simulationId )
912            throws ServiceException
913    {
914        try
915        {
916            _simulationDAO.deleteByPrimaryKey( simulationId );
917        }
918        catch( PersistenceException e )
919        {
920            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
921        }
922    }
923
924    @Nullable
925    @Transactional(readOnly = true)
926    public List<Simulation> getAllSimulations()
927            throws ServiceException
928    {
929        try
930        {
931            return _simulationDAO.selectAll();
932        }
933        catch( PersistenceException e )
934        {
935            throw new ServiceException( ServiceException.ServiceCode.SIMULATION_NOT_FOUND, e );
936        }
937    }
938
939    @Nullable
940    @Transactional(readOnly = true)
941    public List<List<String>> getAllModels()
942            throws ServiceException
943    {
944        try
945        {
946            return _simulationDAO.getAllModels();
947        }
948        catch( PersistenceException e )
949        {
950            throw new ServiceException( ServiceException.ServiceCode.MODEL_NOT_FOUND, e );
951        }
952    }
953
954    @Nullable
955    @Transactional(readOnly = true)
956    public List<Variable> getVariablesByModelId( @NotNull final Integer modelId )
957            throws ServiceException
958    {
959        try
960        {
961            return _variableDAO.getVariablesByModelId( modelId );
962        }
963        catch( PersistenceException e )
964        {
965            throw new ServiceException( ServiceException.ServiceCode.VARIABLE_NOT_FOUND, e );
966        }
967    }
968
969    @Nullable
970    @Transactional(readOnly = true)
971    public String getLocationByModelId( @NotNull final Integer modelId )
972            throws ServiceException
973    {
974        try
975        {
976            return _simulationDAO.getLocationByModelId( modelId );
977        }
978        catch( PersistenceException e )
979        {
980            throw new ServiceException( ServiceException.ServiceCode.SIMULATION_NOT_FOUND, e );
981        }
982    }
983
984    @Nullable
985    @Transactional(readOnly = true)
986    public List<Plateforme> getPlateformsByParameter( @NotNull final String parameterCode )
987            throws ServiceException
988    {
989        try
990        {
991            return _plateformDAO.getPlateformsByParameter( parameterCode );
992        }
993        catch( PersistenceException e )
994        {
995            throw new ServiceException( ServiceException.ServiceCode.PLATEFORM_NOT_FOUND, e );
996        }
997    }
998
999    @Nullable
1000    @Transactional(readOnly = true)
1001    public Integer getParameterByCode( @NotNull final String parameterCode )
1002            throws ServiceException
1003    {
1004        try
1005        {
1006            return _parameterDAO.getParameterByCode( parameterCode );
1007        }
1008        catch( PersistenceException e )
1009        {
1010            throw new ServiceException( ServiceException.ServiceCode.PARAMETER_NOT_FOUND, e );
1011        }
1012    }
1013
1014    /**
1015     * This method insert in database the new dimensions, attributes, variables and simulation
1016     * We use HashSet to avoid doublon ( no new insertion for a parameter already in DB )
1017     *
1018     * @param simulation
1019     * @return
1020     * @throws ServiceException
1021     */
1022    private Integer insertSimulation( final Simulation simulation )
1023            throws ServiceException
1024    {
1025        try
1026        {
1027            // Insert dimensions
1028            final Set<Dimension> dimensionsInDB = new HashSet<Dimension>( _dimensionDAO.selectAll() );
1029            final Set<Dimension> dimensionsInSimulation = simulation.getDimension();
1030            final Set<Dimension> dimensionsInDBAndSimulation = new HashSet<Dimension>( dimensionsInDB );
1031            dimensionsInDBAndSimulation.retainAll( dimensionsInSimulation );
1032            _dimensionDAO.updateAll( dimensionsInDBAndSimulation );
1033            final Set<Dimension> dimensionsToAdd = new HashSet<Dimension>( dimensionsInSimulation );
1034            dimensionsToAdd.removeAll( dimensionsInDB );
1035            _dimensionDAO.insertAll( dimensionsToAdd );
1036            dimensionsInDBAndSimulation.addAll( dimensionsToAdd );
1037            simulation.setDimension( dimensionsInDBAndSimulation );
1038
1039            // Insert Attributes
1040            final Set<Attribute> attributesInDB = new HashSet<Attribute>( _attributeDAO.selectAll() );
1041            final Set<Attribute> attributesInSimulation = simulation.getAttribute();
1042            final Set<Attribute> attributesInDBAndSimulation = new HashSet<Attribute>( attributesInDB );
1043            attributesInDBAndSimulation.retainAll( attributesInSimulation );
1044            _attributeDAO.updateAll( attributesInDBAndSimulation );
1045            final Set<Attribute> attributesToAdd = new HashSet<Attribute>( attributesInSimulation );
1046            attributesToAdd.removeAll( attributesInDB );
1047            _attributeDAO.insertAll( attributesToAdd );
1048            attributesInDBAndSimulation.addAll( attributesToAdd );
1049            simulation.setAttribute( attributesInDBAndSimulation );
1050
1051            // Insert variables
1052            final Set<Variable> variablesInDB = new HashSet<Variable>( _variableDAO.selectAll() );
1053            final Set<Variable> variablesInSimulation = simulation.getVariable();
1054            final Set<Variable> variablesInDBAndSimulation = new HashSet<Variable>( variablesInDB );
1055            variablesInDBAndSimulation.retainAll( variablesInSimulation );
1056            _variableDAO.updateAll( variablesInDBAndSimulation );
1057            final Set<Variable> variablesToAdd = new HashSet<Variable>( variablesInSimulation );
1058            variablesToAdd.removeAll( variablesInDB );
1059            _variableDAO.insertAll( variablesToAdd );
1060            variablesInDBAndSimulation.addAll( variablesToAdd );
1061            simulation.setVariable( variablesInDBAndSimulation );
1062
1063            // Insert header
1064            final Simulation simulationInDB = _simulationDAO.getSimulationByLocation( simulation.getLocation() );
1065            if( null != simulationInDB )
1066            {
1067                simulationInDB.setXmlnsHeader( simulation.getXmlnsHeader() );
1068                simulationInDB.setDimension( simulation.getDimension() );
1069                simulationInDB.setAttribute( simulation.getAttribute() );
1070                simulationInDB.setVariable( simulation.getVariable() );
1071                _simulationDAO.update( simulationInDB );
1072                return simulationInDB.getId();
1073            }
1074            else
1075                return _simulationDAO.insert( simulation );
1076        }
1077        catch( PersistenceException e )
1078        {
1079            throw new ServiceException( ServiceException.ServiceCode.PERSISTENCE, e );
1080        }
1081    }
1082
1083    @Required
1084    public void setPlateformDAO( final PlateformDAO plateformDAO )
1085    {
1086        _plateformDAO = plateformDAO;
1087    }
1088
1089    @Required
1090    public void setParameterDAO( final ParameterDAO parameterDAO )
1091    {
1092        _parameterDAO = parameterDAO;
1093    }
1094
1095    @Required
1096    public void setValueDAO( final ValueDAO valueDAO )
1097    {
1098        _valueDAO = valueDAO;
1099    }
1100
1101    @Required
1102    public void setMeasureDAO( final MeasureDAO measureDAO )
1103    {
1104        _measureDAO = measureDAO;
1105    }
1106
1107    @Required
1108    public void setUserDAO( final UserDAO userDAO )
1109    {
1110        _userDAO = userDAO;
1111    }
1112
1113    @Required
1114    public void setPersonDAO( final PersonDAO personDAO )
1115    {
1116        _personDAO = personDAO;
1117    }
1118
1119    @Required
1120    public void setMcoDAO( final McoDAO mcoDAO )
1121    {
1122        _mcoDAO = mcoDAO;
1123    }
1124
1125    @Required
1126    public void setJeuDAO( final JeuDAO jeuDAO )
1127    {
1128        _jeuDAO = jeuDAO;
1129    }
1130
1131    @Required
1132    public void setDimensionDAO( final DimensionDAO dimensionDAO )
1133    {
1134        _dimensionDAO = dimensionDAO;
1135    }
1136
1137    @Required
1138    public void setAttributeDAO( final AttributeDAO attributeDAO )
1139    {
1140        _attributeDAO = attributeDAO;
1141    }
1142
1143    @Required
1144    public void setVariableDAO( final VariableDAO variableDAO )
1145    {
1146        _variableDAO = variableDAO;
1147    }
1148
1149    @Required
1150    public void setSimulationDAO( final SimulationDAO simulationDAO )
1151    {
1152        _simulationDAO = simulationDAO;
1153    }
1154
1155    private static final Log LOGGER = LogFactory.getLog( EtherServiceImpl.class );
1156
1157    private static String FILE_HEADER_NAME = "header.xml";
1158    private static String FORMAT_FILE = ".nc";
1159
1160    private PlateformDAO _plateformDAO;
1161    private ParameterDAO _parameterDAO;
1162    private ValueDAO _valueDAO;
1163    private MeasureDAO _measureDAO;
1164    private UserDAO _userDAO;
1165    private PersonDAO _personDAO;
1166    private McoDAO _mcoDAO;
1167    private JeuDAO _jeuDAO;
1168    private DimensionDAO _dimensionDAO;
1169    private AttributeDAO _attributeDAO;
1170    private VariableDAO _variableDAO;
1171    private SimulationDAO _simulationDAO;
1172}
Note: See TracBrowser for help on using the repository browser.