001/*
002 $Id: Install.java 4365 2012-10-24 14:25:28Z olle $
003
004 Copyright (C) 2006, 2007 Fredrik Levander, Gregory Vincic, Olle Mansson
005
006 This file is part of Proteios.
007 Available at http://www.proteios.org/
008
009 Proteios is free software; you can redistribute it and/or modify it
010 under the terms of the GNU General Public License as published by
011 the Free Software Foundation; either version 2 of the License, or
012 (at your option) any later version.
013
014 Proteios is distributed in the hope that it will be useful, but
015 WITHOUT ANY WARRANTY; without even the implied warranty of
016 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
017 General Public License for more details.
018
019 You should have received a copy of the GNU General Public License
020 along with this program; if not, write to the Free Software
021 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
022 02111-1307, USA.
023 */
024package org.proteios.core;
025
026import org.proteios.core.data.AnnotationTypeData;
027import org.proteios.core.data.ClientData;
028import org.proteios.core.data.DirectoryData;
029import org.proteios.core.data.FileTypeData;
030import org.proteios.core.data.GroupData;
031import org.proteios.core.data.HardwareData;
032import org.proteios.core.data.HardwareTypeData;
033import org.proteios.core.data.ItemKeyData;
034import org.proteios.core.data.LabelData;
035import org.proteios.core.data.MappingCoordinate;
036import org.proteios.core.data.MimeTypeData;
037import org.proteios.core.data.NewsData;
038import org.proteios.core.data.ParameterValueData;
039import org.proteios.core.data.PluginTypeData;
040import org.proteios.core.data.ProtocolTypeData;
041import org.proteios.core.data.QuotaData;
042import org.proteios.core.data.QuotaIndex;
043import org.proteios.core.data.QuotaTypeData;
044import org.proteios.core.data.RoleData;
045import org.proteios.core.data.RoleKeyData;
046import org.proteios.core.data.SchemaVersionData;
047import org.proteios.core.data.SoftwareData;
048import org.proteios.core.data.SoftwareTypeData;
049import org.proteios.core.data.UserData;
050import org.proteios.util.MD5;
051import java.util.Arrays;
052import java.util.Collections;
053import java.util.Date;
054import java.util.HashMap;
055import java.util.Map;
056import java.util.Set;
057import java.util.TimerTask;
058
059/**
060 * This class contains static methods used to install items into an empty
061 * database.
062 * 
063 * @author Nicklas
064 * @version 2.0
065 * @base.modified $Date: 2012-10-24 16:25:28 +0200 (Wed, 24 Oct 2012) $
066 */
067public final class Install
068{
069        /**
070         * Log core events.
071         */
072        private static final org.apache.log4j.Logger log = org.apache.log4j.LogManager
073                .getLogger("org.proteios.core");
074        private static org.hibernate.Session session = null;
075        // private static SchemaVersionData schemaVersion = null;
076        private static SessionControl sessionControl = null;
077        /**
078         * The schema version to give to new installations. Already existing
079         * installations will be updated to this version number by the
080         * {@link Update#updateDatabase(ProgressReporter, String, String)} method.
081         */
082        public static final int NEW_SCHEMA_VERSION = 10;
083
084
085        public static synchronized void createTables(boolean update,
086                        final ProgressReporter progress)
087                        throws BaseException
088        {
089                String message = "";
090                TimerTask timer = null;
091                if (progress != null)
092                {
093                        progress.display(0, "Building database...");
094                        // The timer will append a dot to the progress reporter every second
095                        timer = new TimerTask()
096                        {
097                                @Override
098                                public void run()
099                                {
100                                        progress.append(".");
101                                }
102                        };
103                }
104                try
105                {
106                        if (timer != null)
107                                Application.getCoreTimer().schedule(timer, 1000, 1000);
108                        Application.start(true);
109                        // Try to catch installation problem before starting install
110                        if (!update && !HibernateUtil.isEmptyDatabase())
111                        {
112                                message = "Building database failed: Database already has tables.";
113                        }
114                        else
115                        {
116                                HibernateUtil.createStaticTables(update);
117                                message = "Database built successfully.";
118                        }
119                }
120                catch (BaseException ex)
121                {
122                        message = "Building database failed: " + ex.getMessage() + "\n";
123                        throw ex;
124                }
125                finally
126                {
127                        if (timer != null)
128                        {
129                                timer.cancel();
130                                timer = null;
131                        }
132                        if (progress != null)
133                        {
134                                progress.display(100, message);
135                        }
136                        Application.stop();
137                }
138        }
139
140
141        /**
142         * Initialise the database by creating all items that are required for
143         * Proteios to work properly. Items that already exists will not be
144         * modified.
145         * 
146         * @param progress An object implementing the {@link ProgressReporter}
147         *        interface
148         * @throws BaseException This exception is thrown if there is an error
149         */
150        public static synchronized void initDatabase(ProgressReporter progress,
151                        String rootPassword)
152                        throws BaseException
153        {
154                Application.start(false);
155                session = HibernateUtil.newSession();
156                final int total_progress_steps = 22;
157                final float progress_factor = 100 / total_progress_steps;
158                if (progress != null)
159                        progress.display(0, "Initialising dataProteios...");
160                try
161                {
162                        // SchemaVersion
163                        createSchemaVersion(NEW_SCHEMA_VERSION);
164                        /*******************************************************************
165                         * Helper class for creating RoleKey's
166                         */
167                        {
168                                class PermissionSet
169                                {
170                                        private String name;
171                                        private String description;
172                                        private Item type;
173                                        private HashMap<RoleData, Integer> permissions;
174
175
176                                        public PermissionSet(Item type, String name,
177                                                        String description)
178                                        {
179                                                super();
180                                                this.name = name;
181                                                this.description = description;
182                                                this.type = type;
183                                                this.permissions = new HashMap<RoleData, Integer>();
184                                        }
185
186
187                                        public void add(RoleData role, Permission... permissions)
188                                        {
189                                                this.permissions.put(role, Permission
190                                                        .grant(permissions));
191                                        }
192
193
194                                        public String getDescription()
195                                        {
196                                                return description;
197                                        }
198
199
200                                        public String getName()
201                                        {
202                                                return name;
203                                        }
204
205
206                                        @SuppressWarnings("unused")
207                                        public HashMap<RoleData, Integer> getPermissions()
208                                        {
209                                                return permissions;
210                                        }
211
212
213                                        public Item getType()
214                                        {
215                                                return type;
216                                        }
217
218
219                                        public RoleKeyData save()
220                                        {
221                                                return Install.createRoleKey(type, name, description,
222                                                        permissions);
223                                        }
224
225
226                                        @Override
227                                        public String toString()
228                                        {
229                                                return getName() + " : " + getType() + " : " + getDescription();
230                                        }
231                                }
232                                /***************************************************************
233                                 * QuotaTypes
234                                 */
235                                if (progress != null)
236                                        progress.display((int) (1 * progress_factor),
237                                                "--Creating quota types...");
238                                createQuotaType(QuotaType.TOTAL, "Total", "Total quota", true);
239                                createQuotaType(QuotaType.FILE, "Files", "Quota for files",
240                                        true);
241
242                                /***************************************************************
243                                 * Quota
244                                 */
245                                if (progress != null)
246                                        progress.display((int) (2 * progress_factor),
247                                                "--Creating quota...");
248                                createQuota(
249                                        Quota.DEFAULT,
250                                        "Default quota",
251                                        "This quota is assigned to new users unless nothing else is specified.",
252                                        10 * 1024 * 1024);
253                                QuotaData quotaUnlimit = createQuota(Quota.UNRESTRICTED,
254                                        "Unlimited quota",
255                                        "This quota gives a user unlimited disc space.",
256                                        (int) Quota.UNLIMITED);
257                                createQuota(null, "100 MB total", "100 MB total quota.",
258                                        100 * 1024 * 1024);
259                                createQuota(null, "200 MB total", "200 MB total quota.",
260                                        200 * 1024 * 1024);
261                                createQuota(null, "500 MB total", "500 MB total quota.",
262                                        500 * 1024 * 1024);
263                                createQuota(null, "1 GB total", "1 GB total quota.",
264                                        1024 * 1024 * 1024);
265                                /***************************************************************
266                                 * Roles
267                                 */
268                                if (progress != null)
269                                        progress.display((int) (3 * progress_factor),
270                                                "--Creating roles...");
271                                RoleData roleAdmin = createRole(Role.ADMINISTRATOR,
272                                        "Administrator",
273                                        "Users with this role get full permission to Proteios.");
274                                RoleData roleSuper = createRole(Role.SUPERVISOR, "Supervisor",
275                                        "Users with this role get full READ permission to everyting in Proteios.");
276                                RoleData rolePower = createRole(Role.POWER_USER, "Power user",
277                                        "Users with this role may do some things that an ordinary user may not.");
278                                RoleData roleUser = createRole(Role.USER, "User",
279                                        "This permissions in this role should be sufficient for most regular users.");
280                                RoleData roleGuest = createRole(
281                                        Role.GUEST,
282                                        "Guest",
283                                        "For users wanting to have a peek at Proteios. Has very limited access to create new things.");
284                                /***************************************************************
285                                 * Root user
286                                 */
287                                if (progress != null)
288                                        progress.display((int) (4 * progress_factor),
289                                                "--Creating users...");
290                                UserData rootUser = createUser(
291                                        User.ROOT,
292                                        "root",
293                                        rootPassword,
294                                        "Root",
295                                        "This is the root user account of Proteios. It has full permission to everything.",
296                                        roleAdmin, quotaUnlimit);
297                                // Add all users to the role User, to enable login through web
298                                // gui
299                                roleUser.getUsers().add(rootUser);
300                                // Now that we have a root user let's create a session
301                                sessionControl = Application
302                                        .newSessionControl(null, null, null);
303                                sessionControl.login("root", rootPassword, "InitDBSessionId",
304                                        false);
305                                if (progress != null)
306                                        progress.display((int) (5 * progress_factor),
307                                                "--Creating groups...");
308                                GroupData groupEveryone = createGroup(Group.EVERYONE,
309                                        "Everyone", "Everyone are members of this group.");
310                                if (progress != null)
311                                        progress.display((int) (6 * progress_factor),
312                                                "--Creating keys...");
313                                int PERMISSION_USE = Permission.grant(Permission.USE);
314                                int PERMISSION_READ = Permission.grant(Permission.READ);
315                                //
316                                HashMap<RoleData, Integer> systemPermissions = new HashMap<RoleData, Integer>();
317                                systemPermissions.put(roleAdmin, Permission
318                                        .grant(Permission.SHARE_TO_EVERYONE));
319                                systemPermissions.put(rolePower, Permission
320                                        .grant(Permission.SHARE_TO_EVERYONE));
321                                /***************************************************************
322                                 * Role permissions
323                                 */
324                                Permission R = Permission.READ;
325                                Permission W = Permission.WRITE;
326                                Permission U = Permission.USE;
327                                Permission C = Permission.CREATE;
328                                Permission D = Permission.DELETE;
329                                Permission STE = Permission.SHARE_TO_EVERYONE;
330                                Permission SO = Permission.SET_OWNER;
331                                Permission SP = Permission.SET_PERMISSION;
332                                Permission[] ALL =
333                                        {
334                                                        R, W, U, C, D, STE, SO, SP
335                                        };
336                                //
337                                PermissionSet systemPS = new PermissionSet(Item.SYSTEM,
338                                        "System", "System-level permissions");
339                                systemPS.add(roleAdmin, STE);
340                                systemPS.add(rolePower, STE);
341                                systemPS.save();
342                                //
343                                PermissionSet groupPS = new PermissionSet(Item.GROUP, "Groups",
344                                        "Gives access to groups.");
345                                groupPS.add(roleAdmin, ALL);
346                                groupPS.save();
347                                //
348                                PermissionSet rolePS = new PermissionSet(Item.ROLE, "Roles",
349                                        "Gives access to roles");
350                                rolePS.add(roleAdmin, ALL);
351                                rolePS.save();
352                                //              
353                                PermissionSet userPS = new PermissionSet(Item.USER, "Users",
354                                        "Gives access to users.");
355                                userPS.add(roleAdmin, ALL);
356                                userPS.add(roleUser, R, W);
357                                userPS.save();
358                                //                              
359                                PermissionSet projectPS = new PermissionSet(Item.PROJECT,
360                                        "Projects", "Gives access to projects.");
361                                projectPS.add(roleAdmin, ALL);
362                                projectPS.add(rolePower, C);
363                                projectPS.add(roleSuper, R);
364                                projectPS.add(roleUser, C);
365                                projectPS.save();
366                                //
367                                PermissionSet roleKeyPS = new PermissionSet(Item.ROLEKEY,
368                                        "Role keys", "Gives access to role keys");
369                                roleKeyPS.add(roleAdmin, ALL);
370                                roleKeyPS.save();
371                                //
372                                PermissionSet itemKeyPS = new PermissionSet(Item.ITEMKEY,
373                                        "Item keys", "Gives access to item keys");
374                                itemKeyPS.add(roleAdmin, ALL);
375                                itemKeyPS.save();
376                                //
377                                PermissionSet projectKeyPS = new PermissionSet(Item.PROJECTKEY,
378                                        "Project keys", "Gives access to project keys");
379                                projectKeyPS.add(roleAdmin, ALL);
380                                projectKeyPS.add(rolePower, C);
381                                projectKeyPS.add(roleSuper, R);
382                                projectKeyPS.add(roleUser, C);
383                                projectKeyPS.save();
384                                // Files, directories and quota
385                                PermissionSet directoryPS = new PermissionSet(Item.DIRECTORY,
386                                        "Directories", "Gives access to directories");
387                                directoryPS.add(roleAdmin, ALL);
388                                directoryPS.add(rolePower, C);
389                                directoryPS.add(roleSuper, R);
390                                directoryPS.add(roleUser, C, U);
391                                directoryPS.save();
392                                //
393                                PermissionSet fileTypePS = new PermissionSet(Item.FILETYPE,
394                                        "File types", "Gives access to file types");
395                                fileTypePS.add(roleAdmin, C);
396                                fileTypePS.add(rolePower, R);
397                                fileTypePS.add(roleUser, R);
398                                fileTypePS.add(roleGuest, R);
399                                fileTypePS.add(roleSuper, R);
400                                fileTypePS.save();
401                                //
402                                PermissionSet filePS = new PermissionSet(Item.FILE, "Files",
403                                        "Gives access to files");
404                                filePS.add(roleGuest, C);
405                                filePS.add(roleAdmin, ALL);
406                                filePS.add(rolePower, C);
407                                filePS.add(roleUser, C);
408                                filePS.add(roleSuper, R);
409                                filePS.save();
410                                //
411                                PermissionSet permPS = new PermissionSet(Item.QUOTATYPE,
412                                        "Quota types", "Gives access to quota types");
413                                permPS.add(roleAdmin, W);
414                                permPS.add(rolePower, R);
415                                permPS.add(roleUser, R);
416                                permPS.add(roleGuest, R);
417                                permPS.add(roleSuper, R);
418                                permPS.save();
419                                //
420                                PermissionSet quotaPS = new PermissionSet(Item.QUOTA, "Quota",
421                                        "Gives access to quota");
422                                quotaPS.add(roleAdmin, ALL);
423                                quotaPS.add(roleSuper, R);
424                                quotaPS.save();
425                                //
426                                PermissionSet discPS = new PermissionSet(Item.DISKUSAGE,
427                                        "Disc usage", "Gives access disc usage");
428                                discPS.add(roleAdmin, R);
429                                discPS.add(roleSuper, R);
430                                discPS.save();
431                                //
432                                PermissionSet protocolTypePS = new PermissionSet(
433                                        Item.PROTOCOLTYPE, "Protocol types",
434                                        "Gives access to protocol types");
435                                protocolTypePS.add(roleAdmin, ALL);
436                                protocolTypePS.add(rolePower, ALL);
437                                protocolTypePS.add(roleUser, U);
438                                protocolTypePS.add(roleGuest, U);
439                                protocolTypePS.add(roleSuper, R);
440                                protocolTypePS.save();
441                                //
442                                PermissionSet protocolPS = new PermissionSet(Item.PROTOCOL,
443                                        "Protocols", "Gives access to protocols");
444                                protocolPS.add(roleAdmin, ALL);
445                                protocolPS.add(rolePower, C);
446                                protocolPS.add(roleSuper, R);
447                                protocolPS.add(roleUser, C);
448                                protocolPS.save();
449                                //
450                                // Protocols, hardware, software
451                                PermissionSet hardwareTypePS = new PermissionSet(
452                                        Item.HARDWARETYPE, "Hardware types",
453                                        "Gives access to hardware types");
454                                hardwareTypePS.add(roleAdmin, ALL);
455                                hardwareTypePS.add(rolePower, U);
456                                hardwareTypePS.add(roleUser, U);
457                                hardwareTypePS.add(roleGuest, U);
458                                hardwareTypePS.add(roleSuper, R);
459                                hardwareTypePS.save();
460                                //
461                                PermissionSet hardwarePS = new PermissionSet(Item.HARDWARE,
462                                        "Hardware", "Gives access to hardware");
463                                hardwarePS.add(roleAdmin, ALL);
464                                hardwarePS.add(rolePower, C);
465                                hardwarePS.add(roleUser, C, U);
466                                hardwarePS.add(roleSuper, R);
467                                hardwarePS.save();
468                                //
469                                PermissionSet hwConfPS = new PermissionSet(
470                                        Item.HARDWARECONFIGURATION, "Hardware configuration",
471                                        "Gives access to hardware configuration");
472                                hwConfPS.add(roleAdmin, ALL);
473                                hwConfPS.add(roleUser, C, U);
474                                hwConfPS.save();
475                                //
476                                PermissionSet softwareTypePS = new PermissionSet(
477                                        Item.SOFTWARETYPE, "Software types",
478                                        "Gives access to software types");
479                                softwareTypePS.add(roleAdmin, ALL);
480                                softwareTypePS.add(rolePower, U);
481                                softwareTypePS.add(roleUser, U);
482                                softwareTypePS.add(roleGuest, U);
483                                softwareTypePS.add(roleSuper, R);
484                                softwareTypePS.save();
485                                //
486                                PermissionSet softwarePS = new PermissionSet(Item.SOFTWARE,
487                                        "Software", "Gives access to software");
488                                softwarePS.add(roleAdmin, ALL);
489                                softwarePS.add(rolePower, C);
490                                softwarePS.add(roleUser, C, U);
491                                softwarePS.add(roleSuper, R);
492                                softwarePS.save();
493                                //
494                                PermissionSet swConfPS = new PermissionSet(
495                                        Item.SOFTWARECONFIGURATION, "Software configuration",
496                                        "Gives access to software configuration");
497                                swConfPS.add(roleAdmin, ALL);
498                                swConfPS.add(roleUser, C, U);
499                                swConfPS.save();
500                                //
501                                PermissionSet acquisitionPS = new PermissionSet(
502                                        Item.PROTEIOS_ACQUISITION, "Acquisition",
503                                        "Gives access to Acquisition");
504                                acquisitionPS.add(roleUser, C, U);
505                                acquisitionPS.add(roleAdmin, ALL);
506                                acquisitionPS.save();
507                                //
508                                PermissionSet peakListSetPS = new PermissionSet(
509                                        Item.PROTEIOS_PEAKLISTSET, "Peaklistset",
510                                        "Gives access to Peaklistset");
511                                peakListSetPS.add(roleAdmin, ALL);
512                                peakListSetPS.add(roleUser, C, U);
513                                peakListSetPS.save();
514                                //
515                                PermissionSet peaklistPS = new PermissionSet(
516                                        Item.PROTEIOS_PEAKLIST, "Peaklist",
517                                        "Gives access to Peaklist");
518                                peaklistPS.add(roleAdmin, ALL);
519                                peaklistPS.add(roleUser, C, U);
520                                peaklistPS.save();
521                                //
522                                PermissionSet processingStepPS = new PermissionSet(
523                                        Item.PROTEIOS_DATAPROCESSINGSTEP, "Data Procesing Step",
524                                        "Gives access to Data Processing Step");
525                                processingStepPS.add(roleAdmin, ALL);
526                                processingStepPS.add(roleUser, C, U);
527                                processingStepPS.save();
528                                //
529                                PermissionSet precursorPS = new PermissionSet(
530                                        Item.PROTEIOS_PRECURSOR, "Precursor",
531                                        "Gives access to Precursor");
532                                precursorPS.add(roleAdmin, ALL);
533                                precursorPS.add(roleUser, C, U);
534                                precursorPS.save();
535                                // 
536                                PermissionSet peakPS = new PermissionSet(Item.PROTEIOS_PEAK,
537                                        "Peak", "Gives access to Peak");
538                                peakPS.add(roleAdmin, ALL);
539                                peakPS.add(roleUser, C, U);
540                                peakPS.save();
541                                //
542                                PermissionSet spectrumSearchPS = new PermissionSet(
543                                        Item.PROTEIOS_SPECTRUMSEARCH, "SpectrumSearch",
544                                        "Gives access to SpectrumSearch");
545                                spectrumSearchPS.add(roleAdmin, ALL);
546                                spectrumSearchPS.add(roleUser, C, U);
547                                spectrumSearchPS.save();
548                                //
549                                PermissionSet digestPS = new PermissionSet(
550                                        Item.PROTEIOS_DIGESTPARAMETER, "DigestParameter",
551                                        "Gives access to DigestParameter");
552                                digestPS.add(roleAdmin, ALL);
553                                digestPS.add(roleUser, C, U);
554                                digestPS.save();
555                                //
556                                PermissionSet observedModificationPS = new PermissionSet(
557                                        Item.PROTEIOS_OBSERVEDMODIFICATION, "ObservedModification",
558                                        "Gives access to ObservedModification");
559                                observedModificationPS.add(roleAdmin, ALL);
560                                observedModificationPS.add(roleUser, C, U);
561                                observedModificationPS.save();
562                                //
563                                PermissionSet searchDatabasePS = new PermissionSet(
564                                        Item.PROTEIOS_SEARCHDATABASE, "SearchDatabase",
565                                        "Gives access to SearchDatabase");
566                                searchDatabasePS.add(roleAdmin, ALL);
567                                searchDatabasePS.add(roleUser, C, U);
568                                searchDatabasePS.save();
569                                //
570                                PermissionSet searchModificationPS = new PermissionSet(
571                                        Item.PROTEIOS_SEARCHMODIFICATION, "SearchModification",
572                                        "Gives access to SearchModification");
573                                searchModificationPS.add(roleAdmin, ALL);
574                                searchModificationPS.add(roleUser, C, U);
575                                searchModificationPS.save();
576                                //
577                                PermissionSet searchResultPS = new PermissionSet(
578                                        Item.PROTEIOS_SEARCHRESULT, "SearchResult",
579                                        "Gives access to SearchResult");
580                                searchResultPS.add(roleAdmin, ALL);
581                                searchResultPS.add(roleUser, C, U);
582                                searchResultPS.save();
583                                //
584                                PermissionSet proteinPS = new PermissionSet(
585                                        Item.PROTEIOS_PROTEIN, "Protein", "Gives access to Protein");
586                                proteinPS.add(roleAdmin, ALL);
587                                proteinPS.add(roleUser, C, U);
588                                proteinPS.save();
589                                //
590                                PermissionSet peptidePS = new PermissionSet(
591                                        Item.PROTEIOS_PEPTIDE, "Peptide", "Gives access to Peptide");
592                                peptidePS.add(roleAdmin, ALL);
593                                peptidePS.add(roleUser, C, U);
594                                peptidePS.save();
595                                //
596                                PermissionSet annoTypePS = new PermissionSet(
597                                        Item.ANNOTATIONTYPE, "Annotation types",
598                                        "Gives access to annotation types");
599                                annoTypePS.add(roleAdmin, ALL);
600                                annoTypePS.add(roleUser, C, U, STE);
601                                annoTypePS.save();
602                                //
603                                PermissionSet annotationSetPS = new PermissionSet(
604                                        Item.ANNOTATIONSET, "Annotation sets",
605                                        "Gives access to annotation sets");
606                                annotationSetPS.add(roleAdmin, ALL);
607                                annotationSetPS.add(roleUser, C, U);
608                                annotationSetPS.save();
609                                //
610                                PermissionSet annotationPS = new PermissionSet(Item.ANNOTATION,
611                                        "Annotations", "Gives access to annotations");
612                                annotationPS.add(roleAdmin, ALL);
613                                annotationPS.add(roleUser, C, U);
614                                annotationPS.save();
615                                //
616                                PermissionSet labelPS = new PermissionSet(Item.LABEL, "Labels",
617                                        "Gives access to labels");
618                                labelPS.add(roleAdmin, ALL);
619                                labelPS.add(rolePower, C);
620                                labelPS.add(roleSuper, R);
621                                labelPS.save();
622                                //
623                                PermissionSet biosourcePS = new PermissionSet(Item.BIOSOURCE,
624                                        "BioSource", "Gives access to biosources");
625                                biosourcePS.add(roleAdmin, ALL);
626                                biosourcePS.add(roleUser, C, U);
627                                biosourcePS.save();
628                                //
629                                PermissionSet samplePS = new PermissionSet(Item.SAMPLE,
630                                        "Samples", "Gives access to samples");
631                                samplePS.add(roleAdmin, ALL);
632                                samplePS.add(roleUser, C, U);
633                                samplePS.save();
634                                //
635                                PermissionSet extractPS = new PermissionSet(Item.EXTRACT,
636                                        "Extracts", "Gives access to extracts");
637                                extractPS.add(roleAdmin, ALL);
638                                extractPS.add(roleUser, C, U);
639                                extractPS.save();
640                                //
641                                PermissionSet labeledExtractPS = new PermissionSet(
642                                        Item.LABELEDEXTRACT, "Labeled extracts",
643                                        "Gives access to labeled extracts");
644                                labeledExtractPS.add(roleAdmin, ALL);
645                                labeledExtractPS.add(roleUser, C, U);
646                                labeledExtractPS.save();
647                                //
648                                PermissionSet pluginTypePS = new PermissionSet(Item.PLUGINTYPE,
649                                        "Plugin types", "Gives access to plugin types");
650                                pluginTypePS.add(roleAdmin, ALL);
651                                pluginTypePS.add(roleSuper, R);
652                                pluginTypePS.save();
653                                //
654                                PermissionSet pluginDefPS = new PermissionSet(
655                                        Item.PLUGINDEFINITION, "Plugin definitions",
656                                        "Gives access to plugin definitions");
657                                pluginDefPS.add(roleAdmin, ALL);
658                                pluginDefPS.add(roleSuper, R);
659                                pluginDefPS.save();
660                                //
661                                PermissionSet pluginConfPS = new PermissionSet(
662                                        Item.PLUGINCONFIGURATION, "Plugin configurations",
663                                        "Gives access to plugin configurations");
664                                pluginConfPS.add(roleAdmin, ALL);
665                                pluginConfPS.add(rolePower, C);
666                                pluginConfPS.add(roleSuper, R);
667                                pluginConfPS.save();
668                                //
669                                PermissionSet jobPS = new PermissionSet(Item.JOB, "Jobs",
670                                        "Gives access to jobs");
671                                jobPS.add(roleAdmin, ALL);
672                                jobPS.add(roleUser, C);
673                                jobPS.save();
674                                //
675                                PermissionSet clientPS = new PermissionSet(Item.CLIENT,
676                                        "Client applications",
677                                        "Gives access to client applications");
678                                clientPS.add(roleAdmin, ALL);
679                                clientPS.add(roleSuper, R);
680                                clientPS.save();
681                                //
682                                PermissionSet newsPS = new PermissionSet(Item.NEWS, "News",
683                                        "Gives access to news");
684                                newsPS.add(roleAdmin, ALL);
685                                newsPS.add(roleSuper, R);
686                                newsPS.save();
687                                //
688                                PermissionSet mimePS = new PermissionSet(Item.MIMETYPE,
689                                        "Mime types", "Gives access to mime types");
690                                mimePS.add(roleAdmin, ALL);
691                                mimePS.add(roleSuper, R);
692                                mimePS.save();
693                                //
694                                PermissionSet sessionPS = new PermissionSet(Item.SESSION,
695                                        "Sessions", "Gives access to sessions");
696                                sessionPS.add(roleAdmin, R);
697                                sessionPS.add(roleSuper, R);
698                                sessionPS.save();
699                                //
700                                PermissionSet settingPS = new PermissionSet(Item.SETTING,
701                                        "Settings", "Gives access to settings");
702                                settingPS.add(roleAdmin, ALL);
703                                settingPS.add(roleSuper, R);
704                                settingPS.save();
705                                //
706                                PermissionSet messagePS = new PermissionSet(Item.MESSAGE,
707                                        "Messages", "Gives access to messages");
708                                messagePS.add(roleAdmin, ALL);
709                                messagePS.add(roleUser, C);
710                                messagePS.save();
711                                //
712                                PermissionSet hitPS = new PermissionSet(Item.PROTEIOS_HIT,
713                                        "Hit", "Gives access to hits");
714                                hitPS.add(roleAdmin, ALL);
715                                hitPS.add(roleUser, C, U, R, W, D);
716                                hitPS.save();
717                                //
718                                PermissionSet featurePS = new PermissionSet(Item.PROTEIOS_FEATURE,
719                                        "Feature", "Gives access to features");
720                                featurePS.add(roleAdmin, ALL);
721                                featurePS.add(roleUser, C, U, R, W, D);
722                                featurePS.save();
723                                //
724                                PermissionSet gelElectroPhoresisPS = new PermissionSet(
725                                        Item.PROTEIOS_GELELECTROPHORESIS, "GelElectroPhoresis",
726                                        "Gives access to gel elctrophoresis items");
727                                gelElectroPhoresisPS.add(roleUser, C);
728                                gelElectroPhoresisPS.add(roleAdmin, ALL);
729                                gelElectroPhoresisPS.save();
730                                //
731                                PermissionSet ipgPS = new PermissionSet(Item.PROTEIOS_IPG,
732                                        "IsolectricFocusing",
733                                        "Gives access to isoelectric focusing items");
734                                ipgPS.add(roleUser, C);
735                                ipgPS.add(roleAdmin, ALL);
736                                ipgPS.save();
737                                //
738                                PermissionSet gelscanPS = new PermissionSet(
739                                        Item.PROTEIOS_GELSCANEVENT, "GelScanEvent",
740                                        "Gives access to gel scan events");
741                                gelscanPS.add(roleUser, R);
742                                gelscanPS.add(roleAdmin, ALL);
743                                gelscanPS.save();
744                                //
745                                PermissionSet xTandemParameterSetStoragePS = new PermissionSet(
746                                        Item.PROTEIOS_XTANDEMPARAMETERSETSTORAGE, "XTandemParameterSetStorage",
747                                        "Gives access to X!Tandem parameter set storage");
748                                xTandemParameterSetStoragePS.add(roleUser, C, U, R, W);
749                                xTandemParameterSetStoragePS.add(roleAdmin, ALL);
750                                xTandemParameterSetStoragePS.save();
751                                //
752                                PermissionSet omssaParameterSetStoragePS = new PermissionSet(
753                                        Item.PROTEIOS_OMSSAPARAMETERSETSTORAGE, "OMSSAParameterSetStorage",
754                                        "Gives access to OMSSA parameter set storage");
755                                omssaParameterSetStoragePS.add(roleUser, C, U, R, W);
756                                omssaParameterSetStoragePS.add(roleAdmin, ALL);
757                                omssaParameterSetStoragePS.save();
758                                //
759                                PermissionSet mascotParameterSetStoragePS = new PermissionSet(
760                                        Item.PROTEIOS_MASCOTPARAMETERSETSTORAGE, "MascotParameterSetStorage",
761                                        "Gives access to Mascot parameter set storage");
762                                mascotParameterSetStoragePS.add(roleUser, C, U, R, W);
763                                mascotParameterSetStoragePS.add(roleAdmin, ALL);
764                                mascotParameterSetStoragePS.save();
765                                /***************************************************************
766                                 * Group permissions
767                                 */
768                                HashMap<GroupData, Integer> everyoneRead = new HashMap<GroupData, Integer>();
769                                everyoneRead.put(groupEveryone, PERMISSION_READ);
770                                HashMap<GroupData, Integer> everyoneUse = new HashMap<GroupData, Integer>();
771                                everyoneUse.put(groupEveryone, PERMISSION_USE);
772                                ItemKeyData keyEveryoneRead = createItemKey("EVERYONE=READ",
773                                        null, everyoneRead);
774                                ItemKeyData keyEveryoneUse = createItemKey("EVERYONE=USE",
775                                        null, everyoneUse);
776                                // ProtocolTypes
777                                if (progress != null)
778                                        progress.display((int) (7 * progress_factor),
779                                                "--Creating protocol types...");
780                                createProtocolType(ProtocolType.SAMPLING, "Sampling",
781                                        "Protocols used for creating samples.");
782                                createProtocolType(ProtocolType.EXTRACTION, "Extraction",
783                                        "Protocols used for creating extracts.");
784                                createProtocolType(ProtocolType.LABELING, "Labeling",
785                                        "Protocols used for creating labeled extracts.");
786                                createProtocolType(ProtocolType.POOLING, "Pooling",
787                                        "Protocols used for creating pooled biomaterials.");
788                                createProtocolType(ProtocolType.SEPARATION, "Separation",
789                                        "Protocols used for separation av a sample or extract.");
790                                createProtocolType(ProtocolType.STAINING, "Staining",
791                                        "Protocols used for staining of a gel.");
792                                createProtocolType(ProtocolType.SCANNING, "Scanning",
793                                        "Protocols used for scanning of a gel.");
794                                createProtocolType(ProtocolType.FEATURE_EXTRACTION,
795                                        "Feature extraction",
796                                        "Protocols used for extracting features from images.");
797                                // HardwareTypes
798                                if (progress != null)
799                                        progress.display((int) (8 * progress_factor),
800                                                "--Creating hardware types...");
801                                HardwareTypeData scanner = createHardwareType(
802                                        HardwareType.SCANNER, "Scanner", "");
803                                HardwareTypeData robot = createHardwareType(HardwareType.ROBOT,
804                                        "Robot", "");
805                                HardwareTypeData ms = createHardwareType(
806                                        HardwareType.MASS_SPECTROMETER, "Mass spectrometer", "");
807                                // Hardware
808                                if (progress != null)
809                                        progress.display((int) (9 * progress_factor),
810                                                "--Creating hardware...");
811                                // Scanners
812                                createHardware("Agilent DNA Microarray Scanner", "G2565BA",
813                                        null, scanner, rootUser, keyEveryoneUse);
814                                createHardware("GenePix Scanner", "4200A", null, scanner,
815                                        rootUser, keyEveryoneUse);
816                                createHardware("ScanArray", null, null, scanner, rootUser,
817                                        keyEveryoneUse);
818                                createHardware("GeneTAC", null, null, scanner, rootUser,
819                                        keyEveryoneUse);
820                                // Print robots
821                                createHardware("BioRobotics", "MicroGrid II", "", robot,
822                                        rootUser, keyEveryoneUse);
823                                createHardware("OmniGrid", "100", "", robot, rootUser,
824                                        keyEveryoneUse);
825                                createHardware("Qarray", "Max", "", robot, rootUser,
826                                        keyEveryoneUse);
827                                // Mass spectrometers
828                                createHardware("QTOF", "Ultima", "Waters", ms, rootUser,
829                                        keyEveryoneUse);
830                                createHardware("LCQ", "DecaXP plus", "Thermo Electron", ms,
831                                        rootUser, keyEveryoneUse);
832                                // SoftwareTypes
833                                if (progress != null)
834                                        progress.display((int) (10 * progress_factor),
835                                                "--Creating software types...");
836                                SoftwareTypeData feature = createSoftwareType(
837                                        SoftwareType.FEATURE_EXTRACTION, "Feature extraction",
838                                        "Extracts features from microarray images.");
839                                createSoftwareType(SoftwareType.PROTEIN_IDENTIFICATION,
840                                        "Protein identification",
841                                        "Identifies proteins from peak lists");
842                                // Software
843                                if (progress != null)
844                                        progress.display((int) (11 * progress_factor),
845                                                "--Creating software...");
846                                createSoftware("BZScan", null, null, feature, rootUser,
847                                        keyEveryoneUse);
848                                // createSoftware("AIDA", null, null, feature, rootUser,
849                                // keyEveryoneUse);
850                                createSoftware("GenePix Pro", "6.0", null, feature, rootUser,
851                                        keyEveryoneUse);
852                                createSoftware("ImaGene", null, null, feature, rootUser,
853                                        keyEveryoneUse);
854                                createSoftware("TIGR Spotfinder", null, null, feature,
855                                        rootUser, keyEveryoneUse);
856                                createSoftware("Agilent Feature Extraction Software", "8.5",
857                                        null, feature, rootUser, keyEveryoneUse);
858                                createSoftware("ChipSkipper", null, null, feature, rootUser,
859                                        keyEveryoneUse);
860                                createSoftware("GeneTAC", null, null, feature, rootUser,
861                                        keyEveryoneUse);
862                                createSoftware("ScanArray", null, null, feature, rootUser,
863                                        keyEveryoneUse);
864                                // Directory
865                                if (progress != null)
866                                        progress.display((int) (12 * progress_factor),
867                                                "--Creating directories...");
868                                DirectoryData rootDirectory = createDirectory(rootUser, null,
869                                        Directory.ROOT, "root", "This is the root directory",
870                                        keyEveryoneRead);
871                                // CreationInterface homeDirectory =
872                                createDirectory(
873                                        rootUser,
874                                        rootDirectory,
875                                        Directory.HOME,
876                                        "home",
877                                        "This is the directory where the user's home directories are located",
878                                        keyEveryoneRead);
879                                DirectoryData templateDirectory = createDirectory(
880                                        rootUser,
881                                        rootDirectory,
882                                        Directory.TEMPLATE,
883                                        "template",
884                                        "The substructure of this directory is used to create the directory structure for new home directories",
885                                        null);
886                                createDirectory(rootUser, templateDirectory, null, "images",
887                                        "Place your images here", null);
888                                createDirectory(
889                                        rootUser,
890                                        templateDirectory,
891                                        null,
892                                        "projects",
893                                        "Create a subdirectory for project-related files in this directory.",
894                                        null);
895                                // FileTypes
896                                if (progress != null)
897                                        progress.display((int) (13 * progress_factor),
898                                                "--Creating file types...");
899                                createFileType(FileType.PROTOCOL, "Protocol", "Protocol files");
900                                createFileType(FileType.PRINT_MAP, "Print map",
901                                        "Print map files");
902                                createFileType(FileType.IMAGE, "Image", "Image files");
903                                // Proteios specific file types
904                                createFileType(FileType.SCANNED_GEL_IMAGE, "Scanned Gel Image",
905                                        "Scanned gel images");
906                                createFileType(FileType.PICK_LIST, "Picklist",
907                                        "Pick list files");
908                                createFileType(FileType.SHW_RESULT,
909                                        "Spot Handling Workstation result",
910                                        "Spot Handling Workstation result files");
911                                createFileType(FileType.RAW_SPECTRUM, "Raw spectrum",
912                                        "Raw spectrum files");
913                                createFileType(FileType.DTA_PEAK_LIST, "DTA format peaklist",
914                                        "DTA peak list files");
915                                createFileType(FileType.MGF_PEAK_LIST, "MGF format peaklist",
916                                "MGF peak list files");
917                                createFileType(FileType.PKL_PEAK_LIST, "PKL format peaklist",
918                                        "PKL peak list files");
919                                createFileType(FileType.PLGS_PEAK_LIST, "PLGS format peaklist",
920                                        "PLGS peak list files");
921                                createFileType(FileType.MZDATA, "mzData", "mzData files");
922                                createFileType(FileType.MZML, "mzML file", "mzML files");
923                                createFileType(FileType.MZXML, "mzXML file", "mzXML files");
924                                createFileType(FileType.MASCOT_PARAMETERS, "Mascot search parameters",
925                                        "Mascot search parameter files");
926                                createFileType(FileType.MASCOT_XML, "Mascot XML result",
927                                        "Mascot XML result files");
928                                createFileType(FileType.PEP_XML, "pepXML search result",
929                                "pepXML result files");
930                                createFileType(FileType.XTANDEM_PARAMETERS, "X!Tandem search parameters",
931                                        "X!Tandem search parameter files");
932                                createFileType(FileType.TANDEM_RESULT, "Tandem result",
933                                        "Tandem result files");
934                                createFileType(FileType.PIUMS_MATCHER, "PIUMS Matcher result",
935                                        "PIUMS Matcher result files");
936                                createFileType(FileType.PIUMS_PEPEX, "PIUMS Pepex result",
937                                        "PIUMS Pepex result files");
938                                createFileType(FileType.PIUMS_PEPFIL, "PIUMS Pepfil result",
939                                        "PIUMS Pepfil result files");
940                                createFileType(FileType.DECYDER_BVA_XML, "Decyder BVA XML",
941                                        "Decyder BVA XML files");
942                                createFileType(FileType.OMSSA_PARAMETERS, "OMSSA search parameters",
943                                "OMSSA search parameter files");
944                                createFileType(FileType.OMSSA_RESULT_XML, "OMSSA result",
945                                "OMSSA result files");
946                                createFileType(FileType.MSINSPECT_FEATURES, "msInspect features",
947                                "msInspect features files");
948                                createFileType(FileType.OPENMS_FEATURES, "OpenMS featureXML",
949                                "OpenMS features files");
950                                // MimeTypes
951                                if (progress != null)
952                                        progress.display((int) (14 * progress_factor),
953                                                "--Creating MIME types...");
954                                createMimeType("text/css", "Cascading style sheet", "css");
955                                createMimeType("text/plain", "Text files", "txt");
956                                createMimeType("text/html", "Hypertext markup language files",
957                                        "htm");
958                                createMimeType("text/html", "Hypertext markup language files",
959                                        "html");
960                                createMimeType("image/jpeg", "JPEG image", "jpg");
961                                createMimeType("image/jpeg", "JPEG image", "jpeg");
962                                createMimeType("image/jpeg", "JPEG image", "jpe");
963                                createMimeType("image/gif", "GIF image", "gif");
964                                createMimeType("image/png", "PNG image", "png");
965                                createMimeType("image/tiff", "TIFF image", "tiff");
966                                createMimeType("image/tiff", "TIFF image", "tif");
967                                createMimeType("image/rgb", "RGB image", "rgb");
968                                createMimeType("image/x-pict", "Macintosh PICT format", "pict");
969                                createMimeType("image/x-ms-bmp", "Microsoft Windows bitmap",
970                                        "bmp");
971                                createMimeType("application/postscript", "PostScript", "ai");
972                                createMimeType("application/postscript", "PostScript", "eps");
973                                createMimeType("application/postscript", "PostScript", "ps");
974                                createMimeType("application/pdf", "Adobe Acrobat PDF", "pdf");
975                                createMimeType("application/x-latex", "LaTeX document", "latex");
976                                createMimeType("application/msword", "MS word document", "doc");
977                                createMimeType("application/rtf", "Microsoft Rich Text Format",
978                                        "rtf");
979                                createMimeType("application/octet-stream", "PC executable",
980                                        "exe");
981                                createMimeType("application/x-perl", "Perl program", "pl");
982                                createMimeType("application/xml", "Extended markup language",
983                                        "xml");
984                                createMimeType("application/xml-dtd",
985                                        "Document type definition for XML", "dtd");
986                                createMimeType("application/vnd.ms-powerpoint",
987                                        "PowerPoint (Microsoft)", "ppt");
988                                createMimeType("application/vnd.ms-powerpoint",
989                                        "PowerPoint (Microsoft)", "ppz");
990                                createMimeType("application/vnd.ms-powerpoint",
991                                        "PowerPoint (Microsoft)", "pps");
992                                createMimeType("application/vnd.ms-powerpoint",
993                                        "PowerPoint (Microsoft)", "pot");
994                                createMimeType("application/vnd.ms-excel",
995                                        "Excel spreadsheet (Microsoft)", "xls");
996                                createMimeType("application/vnd.ms-excel",
997                                        "Excel spreadsheet (Microsoft)", "xlc");
998                                createMimeType("application/vnd.ms-excel",
999                                        "Excel spreadsheet (Microsoft)", "xll");
1000                                createMimeType("application/vnd.ms-excel",
1001                                        "Excel spreadsheet (Microsoft)", "xlm");
1002                                createMimeType("application/vnd.ms-excel",
1003                                        "Excel spreadsheet (Microsoft)", "xlw");
1004                                createMimeType("application/x-compress",
1005                                        "Unix compressed file", "z");
1006                                createMimeType("application/zip", "DOS/PC - Pkzipped archive",
1007                                        "zip");
1008                                createMimeType("application/x-compressed",
1009                                        "Gzip compressed archive", "tgz");
1010                                createMimeType("application/x-gtar", "Gzipped archive", "gtar");
1011                                createMimeType("application/x-gzip", "Gzip compressed file",
1012                                        "gz");
1013                                // Microarray/Proteios-specific mime types
1014                                createMimeType("text/plain", "GenePix Results file", "gpr");
1015                                createMimeType("text/plain", "GenePix Array List file", "gal");
1016                                createMimeType("text/plain", "Spot file format", "spot");
1017                                createMimeType("text/plain", "Spotfinder file format", "tav");
1018                                createMimeType("text/plain", "FASTA formatted file", "fasta");
1019                                createMimeType("text/plain", "Proteiosfile formatted file",
1020                                        "Proteios");
1021                                createMimeType("text/plain", "Biorobotics TAM format", "tam");
1022                                createMimeType("text/plain", "Molecularware MWBR format",
1023                                        "mvbr");
1024                                // Labels
1025                                if (progress != null)
1026                                        progress.display((int) (17 * progress_factor),
1027                                                "--Creating labels...");
1028                                createLabel("cy2", "", rootUser, keyEveryoneUse);
1029                                createLabel("cy3", "", rootUser, keyEveryoneUse);
1030                                createLabel("cy5", "", rootUser, keyEveryoneUse);
1031                                // Annotation types
1032                                Map<String, String> useRadio = Collections.singletonMap(
1033                                        "displayAsList", "0");
1034                                // Clients
1035                                if (progress != null)
1036                                        progress.display((int) (19 * progress_factor),
1037                                                "--Creating clients...");
1038                                createClient(rootUser, "org.proteios.clients.test",
1039                                        "Test programs", "This client is used by test programs",
1040                                        keyEveryoneUse);
1041                                createClient(rootUser, "org.proteios.default", "Web client",
1042                                        "The web interface to Proteios", keyEveryoneUse);
1043                                createClient(rootUser, "org.proteios.service", "Web service",
1044                                        "The service interface to Proteios", keyEveryoneUse);
1045                                // News
1046                                if (progress != null)
1047                                        progress.display((int) (20 * progress_factor),
1048                                                "--Creating news...");
1049                                createNews("Proteios server installed",
1050                                        "Welcome to your new Proteios server.");
1051                                // Plugins
1052                                if (progress != null)
1053                                        progress.display((int) (21 * progress_factor),
1054                                                "--Updating plugin definitions...");
1055                                if (progress != null)
1056                                        progress.display(100,
1057                                                "DataProteios initialised sucessfully.");
1058                        }
1059                }
1060                catch (BaseException ex)
1061                {
1062                        if (progress != null)
1063                                progress
1064                                        .display(100, "DataProteios initialisation failed: " + ex
1065                                                .getMessage() + "\n");
1066                        throw ex;
1067                }
1068                finally
1069                {
1070                        HibernateUtil.close(session);
1071                        session = null;
1072                        Application.stop();
1073                }
1074        }
1075
1076
1077        /**
1078         * Create the schema version, if not existing. If the schema version already
1079         * exists, no change is made.
1080         * 
1081         * @param sv int the schemaVersion value to initialize to.
1082         * @return SchemaVersionData the current schema version item.
1083         */
1084        private static SchemaVersionData createSchemaVersion(int sv)
1085                        throws BaseException
1086        {
1087                org.hibernate.Transaction tx = null;
1088                SchemaVersionData schemaVersion = null;
1089                try
1090                {
1091                        tx = HibernateUtil.newTransaction(session);
1092                        org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1093                                session, "GET_SCHEMA_VERSION");
1094                        schemaVersion = HibernateUtil.loadData(SchemaVersionData.class,
1095                                query);
1096                        if (schemaVersion != null)
1097                        {
1098                                log.info("createSchemaVersion: EXISTS");
1099                                HibernateUtil.commit(tx);
1100                        }
1101                        else
1102                        {
1103                                schemaVersion = new SchemaVersionData();
1104                                schemaVersion.setBuild(Application.getBuild());
1105                                schemaVersion.setSchemaVersion(sv);
1106                                HibernateUtil.saveData(session, schemaVersion);
1107                                HibernateUtil.commit(tx);
1108                                log.info("createSchemaVersion: OK");
1109                        }
1110                }
1111                catch (BaseException ex)
1112                {
1113                        if (tx != null)
1114                        {
1115                                HibernateUtil.rollback(tx);
1116                        }
1117                        log.error("createSchemaVersion: FAILED", ex);
1118                        throw ex;
1119                }
1120                return schemaVersion;
1121        }
1122
1123
1124        /**
1125         * Create a {@link Directory}.
1126         */
1127        private static DirectoryData createDirectory(UserData owner,
1128                        DirectoryData parent, String systemId, String name,
1129                        String description, ItemKeyData itemKey)
1130                        throws BaseException
1131        {
1132                int id = SystemItems.getId(systemId);
1133                org.hibernate.Transaction tx = null;
1134                DirectoryData directory = null;
1135                try
1136                {
1137                        tx = HibernateUtil.newTransaction(session);
1138                        if (id != 0)
1139                        {
1140                                directory = HibernateUtil.loadData(session,
1141                                        DirectoryData.class, id);
1142                        }
1143                        if (directory == null && parent != null)
1144                        {
1145                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1146                                        session, "GET_SUBDIRECTORY_WITH_NAME");
1147                                query.setString("name", name);
1148                                query.setEntity("parent", parent);
1149                                directory = HibernateUtil.loadData(DirectoryData.class, query);
1150                        }
1151                        if (directory != null)
1152                        {
1153                                log
1154                                        .info("createDirectory: EXISTS [parent=" + parent + "; name=" + name + "]");
1155                                HibernateUtil.commit(tx);
1156                        }
1157                        else
1158                        {
1159                                directory = new DirectoryData();
1160                                if (systemId != null)
1161                                        directory.setSystemId(systemId);
1162                                directory.setParent(parent);
1163                                directory.setName(name);
1164                                directory.setDescription(description);
1165                                directory.setOwner(owner);
1166                                directory.setItemKey(itemKey);
1167                                directory.setCreated(new Date());
1168                                HibernateUtil.saveData(session, directory);
1169                                HibernateUtil.commit(tx);
1170                                if (systemId != null)
1171                                        SystemItems.add(directory);
1172                                log
1173                                        .info("createDirectory: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1174                        }
1175                }
1176                catch (BaseException ex)
1177                {
1178                        if (tx != null)
1179                                HibernateUtil.rollback(tx);
1180                        log
1181                                .error(
1182                                        "createDirectory: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1183                                        ex);
1184                        throw ex;
1185                }
1186                return directory;
1187        }
1188
1189
1190        /**
1191         * Create a {@link MimeType}.
1192         */
1193        private static MimeTypeData createMimeType(String name, String description,
1194                        String extension)
1195                        throws BaseException
1196        {
1197                org.hibernate.Transaction tx = null;
1198                MimeTypeData mimeType = null;
1199                try
1200                {
1201                        tx = HibernateUtil.newTransaction(session);
1202                        if (mimeType == null)
1203                        {
1204                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1205                                        session, "GET_MIME_TYPE_FROM_EXTENSION");
1206                                query.setString("extension", extension);
1207                                mimeType = HibernateUtil.loadData(MimeTypeData.class, query);
1208                        }
1209                        if (mimeType != null)
1210                        {
1211                                log
1212                                        .info("createMimeType: EXISTS [extension=" + extension + "; name=" + name + "]");
1213                                HibernateUtil.commit(tx);
1214                        }
1215                        else
1216                        {
1217                                mimeType = new MimeTypeData();
1218                                mimeType.setName(name);
1219                                mimeType.setDescription(description);
1220                                mimeType.setExtension(extension);
1221                                HibernateUtil.saveData(session, mimeType);
1222                                HibernateUtil.commit(tx);
1223                                log
1224                                        .info("createMimeType: OK [extension=" + extension + "; name=" + name + "]");
1225                        }
1226                }
1227                catch (BaseException ex)
1228                {
1229                        if (tx != null)
1230                                HibernateUtil.rollback(tx);
1231                        log
1232                                .error(
1233                                        "createMimeType: FAILED [extension=" + extension + "; name=" + name + "]",
1234                                        ex);
1235                        throw ex;
1236                }
1237                return mimeType;
1238        }
1239
1240
1241        /**
1242         * Create a {@link FileType}.
1243         */
1244        private static FileTypeData createFileType(String systemId, String name,
1245                        String description)
1246                        throws BaseException
1247        {
1248                int id = SystemItems.getId(systemId);
1249                org.hibernate.Transaction tx = null;
1250                FileTypeData fileType = null;
1251                try
1252                {
1253                        tx = HibernateUtil.newTransaction(session);
1254                        if (id != 0)
1255                        {
1256                                fileType = HibernateUtil.loadData(session, FileTypeData.class,
1257                                        id);
1258                        }
1259                        if (fileType == null && systemId == null)
1260                        {
1261                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1262                                        session, "GET_FILE_TYPE_WITH_NAME");
1263                                query.setString("name", name);
1264                                fileType = HibernateUtil.loadData(FileTypeData.class, query);
1265                        }
1266                        if (fileType != null)
1267                        {
1268                                log
1269                                        .info("createFileType: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1270                                HibernateUtil.commit(tx);
1271                        }
1272                        else
1273                        {
1274                                fileType = new FileTypeData();
1275                                if (systemId != null)
1276                                        fileType.setSystemId(systemId);
1277                                fileType.setName(name);
1278                                fileType.setDescription(description);
1279                                HibernateUtil.saveData(session, fileType);
1280                                HibernateUtil.commit(tx);
1281                                if (systemId != null)
1282                                        SystemItems.add(fileType);
1283                                log
1284                                        .info("createFileType: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1285                        }
1286                }
1287                catch (BaseException ex)
1288                {
1289                        if (tx != null)
1290                                HibernateUtil.rollback(tx);
1291                        log
1292                                .error(
1293                                        "createFileType: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1294                                        ex);
1295                        throw ex;
1296                }
1297                return fileType;
1298        }
1299
1300
1301        /**
1302         * Create a {@link QuotaType}.
1303         */
1304        private static QuotaTypeData createQuotaType(String systemId, String name,
1305                        String description, boolean secondaryLocation)
1306                        throws BaseException
1307        {
1308                int id = SystemItems.getId(systemId);
1309                org.hibernate.Transaction tx = null;
1310                QuotaTypeData quotaType = null;
1311                try
1312                {
1313                        tx = HibernateUtil.newTransaction(session);
1314                        if (id != 0)
1315                        {
1316                                quotaType = HibernateUtil.loadData(session,
1317                                        QuotaTypeData.class, id);
1318                        }
1319                        if (quotaType == null && systemId == null)
1320                        {
1321                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1322                                        session, "GET_QUOTA_TYPE_WITH_NAME");
1323                                query.setString("name", name);
1324                                quotaType = HibernateUtil.loadData(QuotaTypeData.class, query);
1325                        }
1326                        if (quotaType != null)
1327                        {
1328                                log
1329                                        .info("createQuotaType: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1330                                HibernateUtil.commit(tx);
1331                        }
1332                        else
1333                        {
1334                                quotaType = new QuotaTypeData();
1335                                if (systemId != null)
1336                                        quotaType.setSystemId(systemId);
1337                                quotaType.setName(name);
1338                                quotaType.setDescription(description);
1339                                quotaType.setSecondaryLocation(secondaryLocation);
1340                                HibernateUtil.saveData(session, quotaType);
1341                                HibernateUtil.commit(tx);
1342                                if (systemId != null)
1343                                        SystemItems.add(quotaType);
1344                                log
1345                                        .info("createQuotaType: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1346                        }
1347                }
1348                catch (BaseException ex)
1349                {
1350                        if (tx != null)
1351                                HibernateUtil.rollback(tx);
1352                        log
1353                                .error(
1354                                        "createQuotaType: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1355                                        ex);
1356                        throw ex;
1357                }
1358                return quotaType;
1359        }
1360
1361
1362        /**
1363         * Create a {@link Quota}.
1364         */
1365        private static QuotaData createQuota(String systemId, String name,
1366                        String description, long totalPrimaryQuota)
1367                        throws BaseException
1368        {
1369                int id = SystemItems.getId(systemId);
1370                org.hibernate.Transaction tx = null;
1371                QuotaData quota = null;
1372                try
1373                {
1374                        tx = HibernateUtil.newTransaction(session);
1375                        if (id != 0)
1376                        {
1377                                quota = HibernateUtil.loadData(session, QuotaData.class, id);
1378                        }
1379                        if (quota == null && systemId == null)
1380                        {
1381                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1382                                        session, "GET_QUOTA_WITH_NAME");
1383                                query.setString("name", name);
1384                                quota = HibernateUtil.loadData(QuotaData.class, query);
1385                        }
1386                        if (quota != null)
1387                        {
1388                                log
1389                                        .info("createQuota: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1390                                HibernateUtil.commit(tx);
1391                        }
1392                        else
1393                        {
1394                                quota = new QuotaData();
1395                                if (systemId != null)
1396                                        quota.setSystemId(systemId);
1397                                quota.setName(name);
1398                                quota.setDescription(description);
1399                                QuotaTypeData total = HibernateUtil.loadData(session,
1400                                        QuotaTypeData.class, SystemItems.getId(QuotaType.TOTAL));
1401                                quota.getQuotaValues().put(
1402                                        new QuotaIndex(total, Location.PRIMARY.getValue()),
1403                                        totalPrimaryQuota);
1404                                HibernateUtil.saveData(session, quota);
1405                                HibernateUtil.commit(tx);
1406                                if (systemId != null)
1407                                        SystemItems.add(quota);
1408                                log
1409                                        .info("createQuota: OK [SYSTEM ID=" + systemId + "; name=" + name + "; name=" + name + "]");
1410                        }
1411                }
1412                catch (BaseException ex)
1413                {
1414                        if (tx != null)
1415                                HibernateUtil.rollback(tx);
1416                        log
1417                                .error(
1418                                        "createQuota: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1419                                        ex);
1420                        throw ex;
1421                }
1422                return quota;
1423        }
1424
1425
1426        /**
1427         * Create a {@link User}.
1428         */
1429        private static UserData createUser(String systemId, String login,
1430                        String password, String name, String description, RoleData role,
1431                        QuotaData quota)
1432                        throws BaseException
1433        {
1434                int id = SystemItems.getId(systemId);
1435                org.hibernate.Transaction tx = null;
1436                UserData user = null;
1437                try
1438                {
1439                        tx = HibernateUtil.newTransaction(session);
1440                        if (id != 0)
1441                        {
1442                                user = HibernateUtil.loadData(session, UserData.class, id);
1443                        }
1444                        if (user == null && systemId == null)
1445                        {
1446                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1447                                        session, "GET_USER_FOR_LOGIN");
1448                                query.setString("login", login);
1449                                user = HibernateUtil.loadData(UserData.class, query);
1450                        }
1451                        if (user != null)
1452                        {
1453                                log
1454                                        .info("createUser: EXISTS [SYSTEM ID=" + systemId + "; login=" + login + "]");
1455                                HibernateUtil.commit(tx);
1456                        }
1457                        else
1458                        {
1459                                user = new UserData();
1460                                if (systemId != null)
1461                                        user.setSystemId(systemId);
1462                                user.setLogin(login);
1463                                user.getPassword().setMd5Password(MD5.getHashString(password));
1464                                user.setName(name);
1465                                user.setDescription(description);
1466                                user.setQuota(quota);
1467                                if (role != null)
1468                                {
1469                                        role.getUsers().add(user);
1470                                }
1471                                HibernateUtil.saveData(session, user);
1472                                HibernateUtil.commit(tx);
1473                                if (systemId != null)
1474                                        SystemItems.add(user);
1475                                log
1476                                        .info("createUser: OK [SYSTEM ID=" + systemId + "; login=" + login + "]");
1477                        }
1478                }
1479                catch (BaseException ex)
1480                {
1481                        if (tx != null)
1482                                HibernateUtil.rollback(tx);
1483                        log
1484                                .error(
1485                                        "createUser: FAILED [SYSTEM ID=" + systemId + "; login=" + login + "]",
1486                                        ex);
1487                        throw ex;
1488                }
1489                return user;
1490        }
1491
1492
1493        /**
1494         * Create a {@link Group}.
1495         */
1496        private static GroupData createGroup(String systemId, String name,
1497                        String description)
1498                        throws BaseException
1499        {
1500                int id = SystemItems.getId(systemId);
1501                org.hibernate.Transaction tx = null;
1502                GroupData group = null;
1503                try
1504                {
1505                        tx = HibernateUtil.newTransaction(session);
1506                        if (id != 0)
1507                        {
1508                                group = HibernateUtil.loadData(session, GroupData.class, id);
1509                        }
1510                        if (group == null && systemId == null)
1511                        {
1512                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1513                                        session, "GET_GROUP_WITH_NAME");
1514                                query.setString("name", name);
1515                                group = HibernateUtil.loadData(GroupData.class, query);
1516                        }
1517                        if (group != null)
1518                        {
1519                                log
1520                                        .info("createGroup: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1521                                HibernateUtil.commit(tx);
1522                        }
1523                        else
1524                        {
1525                                group = new GroupData();
1526                                if (systemId != null)
1527                                        group.setSystemId(systemId);
1528                                group.setName(name);
1529                                group.setDescription(description);
1530                                HibernateUtil.saveData(session, group);
1531                                HibernateUtil.commit(tx);
1532                                if (systemId != null)
1533                                        SystemItems.add(group);
1534                                log
1535                                        .info("createGroup: OK [SYSTEM ID=" + systemId + " name=" + name + "]");
1536                        }
1537                }
1538                catch (BaseException ex)
1539                {
1540                        if (tx != null)
1541                                HibernateUtil.rollback(tx);
1542                        log
1543                                .error(
1544                                        "createGroup: FAILED [SYSTEM ID=" + systemId + " name=" + name + "]",
1545                                        ex);
1546                        throw ex;
1547                }
1548                return group;
1549        }
1550
1551
1552        /**
1553         * Create a {@link Role}.
1554         */
1555        private static RoleData createRole(String systemId, String name,
1556                        String description)
1557                        throws BaseException
1558        {
1559                int id = SystemItems.getId(systemId);
1560                org.hibernate.Transaction tx = null;
1561                RoleData role = null;
1562                try
1563                {
1564                        tx = HibernateUtil.newTransaction(session);
1565                        if (id != 0)
1566                        {
1567                                role = HibernateUtil.loadData(session, RoleData.class, id);
1568                        }
1569                        if (role == null && systemId == null)
1570                        {
1571                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1572                                        session, "GET_ROLE_WITH_NAME");
1573                                query.setString("name", name);
1574                                role = HibernateUtil.loadData(RoleData.class, query);
1575                        }
1576                        if (role != null)
1577                        {
1578                                log
1579                                        .info("createRole: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1580                                HibernateUtil.commit(tx);
1581                        }
1582                        else
1583                        {
1584                                role = new RoleData();
1585                                if (systemId != null)
1586                                        role.setSystemId(systemId);
1587                                role.setName(name);
1588                                role.setDescription(description);
1589                                HibernateUtil.saveData(session, role);
1590                                HibernateUtil.commit(tx);
1591                                if (systemId != null)
1592                                        SystemItems.add(role);
1593                                log
1594                                        .info("createRole: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1595                        }
1596                }
1597                catch (BaseException ex)
1598                {
1599                        if (tx != null)
1600                                HibernateUtil.rollback(tx);
1601                        log
1602                                .error(
1603                                        "createRole: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1604                                        ex);
1605                        throw ex;
1606                }
1607                return role;
1608        }
1609
1610
1611        /**
1612         * Create a {@link ProtocolType}.
1613         */
1614        private static ProtocolTypeData createProtocolType(String systemId,
1615                        String name, String description)
1616                        throws BaseException
1617        {
1618                int id = SystemItems.getId(systemId);
1619                org.hibernate.Transaction tx = null;
1620                ProtocolTypeData pt = null;
1621                try
1622                {
1623                        tx = HibernateUtil.newTransaction(session);
1624                        if (id != 0)
1625                        {
1626                                pt = HibernateUtil
1627                                        .loadData(session, ProtocolTypeData.class, id);
1628                        }
1629                        if (pt == null && systemId == null)
1630                        {
1631                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1632                                        session, "GET_PROTOCOL_TYPE_WITH_NAME");
1633                                query.setString("name", name);
1634                                pt = HibernateUtil.loadData(ProtocolTypeData.class, query);
1635                        }
1636                        if (pt != null)
1637                        {
1638                                log
1639                                        .info("createProtocolType: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1640                                HibernateUtil.commit(tx);
1641                        }
1642                        else
1643                        {
1644                                pt = new ProtocolTypeData();
1645                                if (systemId != null)
1646                                        pt.setSystemId(systemId);
1647                                pt.setName(name);
1648                                pt.setDescription(description);
1649                                HibernateUtil.saveData(session, pt);
1650                                HibernateUtil.commit(tx);
1651                                if (systemId != null)
1652                                        SystemItems.add(pt);
1653                                log
1654                                        .info("createProtocolType: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1655                        }
1656                }
1657                catch (BaseException ex)
1658                {
1659                        if (tx != null)
1660                                HibernateUtil.rollback(tx);
1661                        log
1662                                .error(
1663                                        "createProtocolType: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1664                                        ex);
1665                        throw ex;
1666                }
1667                return pt;
1668        }
1669
1670
1671        /**
1672         * Create a {@link SoftwareType}.
1673         */
1674        private static SoftwareTypeData createSoftwareType(String systemId,
1675                        String name, String description)
1676                        throws BaseException
1677        {
1678                int id = SystemItems.getId(systemId);
1679                org.hibernate.Transaction tx = null;
1680                SoftwareTypeData st = null;
1681                try
1682                {
1683                        tx = HibernateUtil.newTransaction(session);
1684                        if (id != 0)
1685                        {
1686                                st = HibernateUtil
1687                                        .loadData(session, SoftwareTypeData.class, id);
1688                        }
1689                        if (st == null && systemId == null)
1690                        {
1691                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1692                                        session, "GET_SOFTWARE_TYPE_WITH_NAME");
1693                                query.setString("name", name);
1694                                st = HibernateUtil.loadData(SoftwareTypeData.class, query);
1695                        }
1696                        if (st != null)
1697                        {
1698                                log
1699                                        .info("createSoftwareType: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1700                                HibernateUtil.commit(tx);
1701                        }
1702                        else
1703                        {
1704                                st = new SoftwareTypeData();
1705                                if (systemId != null)
1706                                        st.setSystemId(systemId);
1707                                st.setName(name);
1708                                st.setDescription(description);
1709                                HibernateUtil.saveData(session, st);
1710                                HibernateUtil.commit(tx);
1711                                if (systemId != null)
1712                                        SystemItems.add(st);
1713                                log
1714                                        .info("createSoftwareType: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1715                        }
1716                }
1717                catch (BaseException ex)
1718                {
1719                        if (tx != null)
1720                                HibernateUtil.rollback(tx);
1721                        log
1722                                .error(
1723                                        "createSoftwareType: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1724                                        ex);
1725                        throw ex;
1726                }
1727                return st;
1728        }
1729
1730
1731        /**
1732         * Create a {@link Software}.
1733         */
1734        private static SoftwareData createSoftware(String name, String version,
1735                        String description, SoftwareTypeData type, UserData owner,
1736                        ItemKeyData shareTo)
1737                        throws BaseException
1738        {
1739                org.hibernate.Transaction tx = null;
1740                SoftwareData sw = null;
1741                try
1742                {
1743                        tx = HibernateUtil.newTransaction(session);
1744                        if (sw == null)
1745                        {
1746                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1747                                        session, "GET_SOFTWARE_WITH_NAME");
1748                                query.setString("name", name);
1749                                sw = HibernateUtil.loadData(SoftwareData.class, query);
1750                        }
1751                        if (sw != null)
1752                        {
1753                                log.info("createSoftware: EXISTS [name=" + name + "]");
1754                                HibernateUtil.commit(tx);
1755                        }
1756                        else
1757                        {
1758                                sw = new SoftwareData();
1759                                sw.setName(name);
1760                                sw.setDescription(description);
1761                                sw.setVersionString(version);
1762                                sw.setSoftwareType(type);
1763                                sw.setOwner(owner);
1764                                sw.setItemKey(shareTo);
1765                                HibernateUtil.saveData(session, sw);
1766                                HibernateUtil.commit(tx);
1767                                log.info("createSoftware: OK [name=" + name + "]");
1768                        }
1769                }
1770                catch (BaseException ex)
1771                {
1772                        if (tx != null)
1773                                HibernateUtil.rollback(tx);
1774                        log.error("createSoftware: FAILED [name=" + name + "]", ex);
1775                        throw ex;
1776                }
1777                return sw;
1778        }
1779
1780
1781        /**
1782         * Create a {@link HardwareType}.
1783         */
1784        private static HardwareTypeData createHardwareType(String systemId,
1785                        String name, String description)
1786                        throws BaseException
1787        {
1788                int id = SystemItems.getId(systemId);
1789                org.hibernate.Transaction tx = null;
1790                HardwareTypeData ht = null;
1791                try
1792                {
1793                        tx = HibernateUtil.newTransaction(session);
1794                        if (id != 0)
1795                        {
1796                                ht = HibernateUtil
1797                                        .loadData(session, HardwareTypeData.class, id);
1798                        }
1799                        if (ht == null && systemId == null)
1800                        {
1801                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1802                                        session, "GET_HARDWARE_TYPE_WITH_NAME");
1803                                query.setString("name", name);
1804                                ht = HibernateUtil.loadData(HardwareTypeData.class, query);
1805                        }
1806                        if (ht != null)
1807                        {
1808                                log
1809                                        .info("createHardwareType: EXISTS [SYSTEM ID=" + systemId + "; name=" + name + "]");
1810                                HibernateUtil.commit(tx);
1811                        }
1812                        else
1813                        {
1814                                ht = new HardwareTypeData();
1815                                if (systemId != null)
1816                                        ht.setSystemId(systemId);
1817                                ht.setName(name);
1818                                ht.setDescription(description);
1819                                HibernateUtil.saveData(session, ht);
1820                                HibernateUtil.commit(tx);
1821                                if (systemId != null)
1822                                        SystemItems.add(ht);
1823                                log
1824                                        .info("createHardwareType: OK [SYSTEM ID=" + systemId + "; name=" + name + "]");
1825                        }
1826                }
1827                catch (BaseException ex)
1828                {
1829                        if (tx != null)
1830                                HibernateUtil.rollback(tx);
1831                        log
1832                                .error(
1833                                        "createHardwareType: FAILED [SYSTEM ID=" + systemId + "; name=" + name + "]",
1834                                        ex);
1835                        throw ex;
1836                }
1837                return ht;
1838        }
1839
1840
1841        /**
1842         * Create a {@link HardwareData}.
1843         */
1844        private static HardwareData createHardware(String name, String version,
1845                        String description, HardwareTypeData type, UserData owner,
1846                        ItemKeyData shareTo)
1847                        throws BaseException
1848        {
1849                org.hibernate.Transaction tx = null;
1850                HardwareData hw = null;
1851                try
1852                {
1853                        tx = HibernateUtil.newTransaction(session);
1854                        if (hw == null)
1855                        {
1856                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1857                                        session, "GET_HARDWARE_WITH_NAME");
1858                                query.setString("name", name);
1859                                hw = HibernateUtil.loadData(HardwareData.class, query);
1860                        }
1861                        if (hw != null)
1862                        {
1863                                log.info("createHardware: EXISTS [name=" + name + "]");
1864                                HibernateUtil.commit(tx);
1865                        }
1866                        else
1867                        {
1868                                hw = new HardwareData();
1869                                hw.setName(name);
1870                                hw.setDescription(description);
1871                                hw.setVersionString(version);
1872                                hw.setHardwareType(type);
1873                                hw.setOwner(owner);
1874                                hw.setItemKey(shareTo);
1875                                HibernateUtil.saveData(session, hw);
1876                                HibernateUtil.commit(tx);
1877                                log.info("createHardware: OK [name=" + name + "]");
1878                        }
1879                }
1880                catch (BaseException ex)
1881                {
1882                        if (tx != null)
1883                                HibernateUtil.rollback(tx);
1884                        log.error("createHardware: FAILED [name=" + name + "]", ex);
1885                        throw ex;
1886                }
1887                return hw;
1888        }
1889
1890
1891
1892        /**
1893         * Create a {@link Label}.
1894         */
1895        private static LabelData createLabel(String name, String description,
1896                        UserData owner, ItemKeyData shareTo)
1897                        throws BaseException
1898        {
1899                org.hibernate.Transaction tx = null;
1900                LabelData label = null;
1901                try
1902                {
1903                        tx = HibernateUtil.newTransaction(session);
1904                        if (label == null)
1905                        {
1906                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1907                                        session, "GET_LABEL_WITH_NAME");
1908                                query.setString("name", name);
1909                                label = HibernateUtil.loadData(LabelData.class, query);
1910                        }
1911                        if (label != null)
1912                        {
1913                                log.info("createLabel: EXISITS [NAME=" + name + "]");
1914                                HibernateUtil.commit(tx);
1915                        }
1916                        else
1917                        {
1918                                label = new LabelData();
1919                                label.setName(name);
1920                                label.setDescription(description);
1921                                label.setOwner(owner);
1922                                label.setItemKey(shareTo);
1923                                HibernateUtil.saveData(session, label);
1924                                HibernateUtil.commit(tx);
1925                                log.info("createLabel: OK [NAME=" + name + "]");
1926                        }
1927                }
1928                catch (BaseException ex)
1929                {
1930                        if (tx != null)
1931                                HibernateUtil.rollback(tx);
1932                        log.info("createLabel: FAILED [NAME=" + name + "]", ex);
1933                        throw ex;
1934                }
1935                return label;
1936        }
1937
1938
1939        /**
1940         * Create an {@link AnnotationType}.
1941         */
1942        private static AnnotationTypeData createAnnotationType(String name,
1943                        String description, Type type, int multiplicity,
1944                        Object[] enumeration, Item[] itemTypes,
1945                        Map<String, String> options, boolean requiredForMiame,
1946                        UserData owner, ItemKeyData shareTo)
1947        {
1948                org.hibernate.Transaction tx = null;
1949                AnnotationTypeData at = null;
1950                try
1951                {
1952                        tx = HibernateUtil.newTransaction(session);
1953                        if (at == null)
1954                        {
1955                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
1956                                        session, "GET_ANNOTATION_TYPE_WITH_NAME");
1957                                query.setString("name", name);
1958                                at = HibernateUtil.loadData(AnnotationTypeData.class, query);
1959                        }
1960                        if (at != null)
1961                        {
1962                                log
1963                                        .info("createAnnotationType: OK [EXISTS=" + name + "; TYPE=" + type);
1964                                HibernateUtil.commit(tx);
1965                        }
1966                        else
1967                        {
1968                                at = new AnnotationTypeData();
1969                                at.setName(name);
1970                                at.setDescription(description);
1971                                at.setOwner(owner);
1972                                at.setItemKey(shareTo);
1973                                at.setValueType(type.getValue());
1974                                at.setMultiplicity(multiplicity);
1975                                at.setWidth(30);
1976                                at.setHeight(1);
1977                                at.setRequiredForMiame(requiredForMiame);
1978                                if (options != null)
1979                                        at.getOptions().putAll(options);
1980                                if (itemTypes != null)
1981                                {
1982                                        Set<Integer> itemCodes = at.getItemTypes();
1983                                        for (Item item : itemTypes)
1984                                        {
1985                                                itemCodes.add(item.getValue());
1986                                        }
1987                                }
1988                                if (enumeration != null)
1989                                {
1990                                        ParameterValueData<?> enumValues = type
1991                                                .newParameterValueData();
1992                                        enumValues.replaceValues(Arrays.asList(enumeration));
1993                                        at.setEnumeration(true);
1994                                        at.setEnumerationValues(enumValues);
1995                                }
1996                                HibernateUtil.saveData(session, at);
1997                                HibernateUtil.commit(tx);
1998                                log
1999                                        .info("createAnnotationType: OK [NAME=" + name + "; TYPE=" + type);
2000                        }
2001                }
2002                catch (BaseException ex)
2003                {
2004                        if (tx != null)
2005                                HibernateUtil.rollback(tx);
2006                        log
2007                                .info(
2008                                        "createAnnotationType: FAILED [NAME=" + name + "; TYPE=" + type,
2009                                        ex);
2010                        throw ex;
2011                }
2012                return at;
2013        }
2014
2015
2016        /**
2017         * Create a {@link RoleKey}.
2018         * 
2019         * @param permissions A map with RoleData as keys and permission codes as
2020         *        values
2021         */
2022        private static RoleKeyData createRoleKey(Item itemType, String name,
2023                        String description, Map<RoleData, Integer> permissions)
2024                        throws BaseException
2025        {
2026                int id = SystemItems.getRoleKeyId(itemType);
2027                org.hibernate.Transaction tx = null;
2028                RoleKeyData key = null;
2029                try
2030                {
2031                        tx = HibernateUtil.newTransaction(session);
2032                        if (id != 0)
2033                        {
2034                                log.info("createRoleKey: EXISTS [NAME=" + name + "]");
2035                                key = HibernateUtil.loadData(session, RoleKeyData.class, id);
2036                                HibernateUtil.commit(tx);
2037                        }
2038                        else
2039                        {
2040                                key = new RoleKeyData();
2041                                key.setItemType(itemType.getValue());
2042                                key.setName(name);
2043                                key.setDescription(description);
2044                                Map<RoleData, Integer> roleKeyPermissions = key.getRoles();
2045                                int definedPermissions = Permission.grant(itemType
2046                                        .getDefinedPermissions());
2047                                for (Map.Entry<RoleData, Integer> entry : permissions
2048                                        .entrySet())
2049                                {
2050                                        roleKeyPermissions.put(entry.getKey(),
2051                                                entry.getValue() & definedPermissions);
2052                                }
2053                                HibernateUtil.saveData(session, key);
2054                                HibernateUtil.commit(tx);
2055                                SystemItems.addRoleKey(key);
2056                                log.info("createRoleKey: OK [NAME=" + name + "]");
2057                        }
2058                }
2059                catch (BaseException ex)
2060                {
2061                        if (tx != null)
2062                                HibernateUtil.rollback(tx);
2063                        log.error("createRoleKey: FAILED [NAME=" + name + "]", ex);
2064                        throw ex;
2065                }
2066                return key;
2067        }
2068
2069
2070        /**
2071         * Create an {@link ItemKey}.
2072         * 
2073         * @param message Message will be written to the log
2074         * @param userPermissions A map with UserData as keys and permission codes
2075         *        as values
2076         * @param groupPermissions A map with GroupData as keys and permission codes
2077         *        as values
2078         */
2079        private static ItemKeyData createItemKey(String message,
2080                        Map<UserData, Integer> userPermissions,
2081                        Map<GroupData, Integer> groupPermissions)
2082                        throws BaseException
2083        {
2084                org.hibernate.Transaction tx = null;
2085                try
2086                {
2087                        tx = HibernateUtil.newTransaction(session);
2088                        ItemKeyData key = new ItemKeyData();
2089                        if (userPermissions != null)
2090                                key.getUsers().putAll(userPermissions);
2091                        if (groupPermissions != null)
2092                                key.getGroups().putAll(groupPermissions);
2093                        HibernateUtil.saveData(session, key);
2094                        HibernateUtil.commit(tx);
2095                        log.info("createItemKey: OK [" + message + "]");
2096                        return key;
2097                }
2098                catch (BaseException ex)
2099                {
2100                        if (tx != null)
2101                                HibernateUtil.rollback(tx);
2102                        log.error("createItemKey: FAILED [" + message + "]", ex);
2103                        throw ex;
2104                }
2105        }
2106
2107
2108        /**
2109         * Create a {@link Client}.
2110         */
2111        private static ClientData createClient(UserData owner, String externalId,
2112                        String name, String description, ItemKeyData key)
2113                        throws BaseException
2114        {
2115                org.hibernate.Transaction tx = null;
2116                ClientData client = null;
2117                try
2118                {
2119                        tx = HibernateUtil.newTransaction(session);
2120                        if (client == null)
2121                        {
2122                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
2123                                        session, "GET_CLIENT_FOR_EXTERNAL_ID");
2124                                query.setString("externalId", externalId);
2125                                client = HibernateUtil.loadData(ClientData.class, query);
2126                        }
2127                        if (client != null)
2128                        {
2129                                log
2130                                        .info("createClient: EXISTS [externalId=" + externalId + "]");
2131                                HibernateUtil.commit(tx);
2132                        }
2133                        else
2134                        {
2135                                client = new ClientData();
2136                                client.setOwner(owner);
2137                                client.setExternalId(externalId);
2138                                client.setName(name);
2139                                client.setDescription(description);
2140                                client.setItemKey(key);
2141                                HibernateUtil.saveData(session, client);
2142                                HibernateUtil.commit(tx);
2143                                log.info("createClient: OK [externalId=" + externalId + "]");
2144                        }
2145                }
2146                catch (BaseException ex)
2147                {
2148                        if (tx != null)
2149                                HibernateUtil.rollback(tx);
2150                        log.error("createClient: FAILED [externalId=" + externalId + "]",
2151                                ex);
2152                        throw ex;
2153                }
2154                return client;
2155        }
2156
2157
2158        /**
2159         * Create a {@link News}.
2160         */
2161        private static NewsData createNews(String name, String description)
2162                        throws BaseException
2163        {
2164                NewsData news = null;
2165                org.hibernate.Transaction tx = null;
2166                try
2167                {
2168                        tx = HibernateUtil.newTransaction(session);
2169                        if (news == null)
2170                        {
2171                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
2172                                        session, "GET_NEWS_WITH_NAME");
2173                                query.setString("name", name);
2174                                news = HibernateUtil.loadData(NewsData.class, query);
2175                        }
2176                        if (news != null)
2177                        {
2178                                log.info("createNews: EXISTS [name=" + name + "]");
2179                                HibernateUtil.commit(tx);
2180                        }
2181                        else
2182                        {
2183                                news = new NewsData();
2184                                news.setName(name);
2185                                news.setDescription(description);
2186                                Date today = new Date();
2187                                news.setStartDate(today);
2188                                news.setNewsDate(today);
2189                                news.setEndDate(new Date(
2190                                        System.currentTimeMillis() + 1000 * 3600 * 24 * 7)); // 1
2191                                // week
2192                                // from
2193                                // now
2194                                HibernateUtil.saveData(session, news);
2195                                HibernateUtil.commit(tx);
2196                                log.info("createNews: OK [name=" + name + "]");
2197                        }
2198                }
2199                catch (BaseException ex)
2200                {
2201                        if (tx != null)
2202                                HibernateUtil.rollback(tx);
2203                        log.error("createNews: FAILED [name=" + name + "]", ex);
2204                        throw ex;
2205                }
2206                return news;
2207        }
2208
2209
2210        /**
2211         * Create a {@link PluginType}.
2212         */
2213        @SuppressWarnings("unused")
2214        private static PluginTypeData createPluginType(String name,
2215                        String description, String interfaceName, String jarPath)
2216                        throws BaseException
2217        {
2218                org.hibernate.Transaction tx = null;
2219                PluginTypeData pluginType = null;
2220                try
2221                {
2222                        tx = HibernateUtil.newTransaction(session);
2223                        if (pluginType == null)
2224                        {
2225                                org.hibernate.Query query = HibernateUtil.getPredefinedQuery(
2226                                        session, "GET_PLUGINTYPE_FOR_INTERFACENAME");
2227                                query.setString("interfaceName", interfaceName);
2228                                pluginType = HibernateUtil
2229                                        .loadData(PluginTypeData.class, query);
2230                        }
2231                        if (pluginType != null)
2232                        {
2233                                log
2234                                        .info("createPluginType: EXISTS [interfaceName=" + interfaceName + "]");
2235                                HibernateUtil.commit(tx);
2236                        }
2237                        else
2238                        {
2239                                pluginType = new PluginTypeData();
2240                                pluginType.setName(name);
2241                                pluginType.setDescription(description);
2242                                pluginType.setInterfaceName(interfaceName);
2243                                pluginType.setJarPath(jarPath);
2244                                HibernateUtil.saveData(session, pluginType);
2245                                HibernateUtil.commit(tx);
2246                                log
2247                                        .info("createPluginType: OK [interfaceName=" + interfaceName + "]");
2248                        }
2249                }
2250                catch (BaseException ex)
2251                {
2252                        if (tx != null)
2253                                HibernateUtil.rollback(tx);
2254                        log
2255                                .error(
2256                                        "createPluginType: FAILED [interfaceName=" + interfaceName + "]",
2257                                        ex);
2258                        throw ex;
2259                }
2260                return pluginType;
2261        }
2262
2263
2264        /**
2265         * Update existing plugin definitions a {@link PluginType}.
2266         */
2267        private static void updatePluginDefinitions()
2268        {
2269                PluginDefinition pd = null;
2270                DbControl dc = null;
2271                dc = sessionControl.newDbControl();
2272                QueryFactory queryFactory = new QueryFactory();
2273                ItemQuery<PluginDefinition> query = queryFactory
2274                        .select(PluginDefinition.class);
2275                ItemResultIterator<PluginDefinition> pdIter = query.iterate(dc);
2276                while (pdIter.hasNext())
2277                {
2278                        pd = pdIter.next();
2279                        String jarPath = pd.getJarPath();
2280                        String className = pd.getClassName();
2281                        try
2282                        {
2283                                pd.loadPluginInformation(jarPath, className);
2284                                log
2285                                        .info("updatePluginDefinitions: UPDATE : [className=" + className + "]");
2286                        }
2287                        catch (Exception e)
2288                        {
2289                                log
2290                                        .info("updatePluginDefinitions: Could not update " + className + " definition");
2291                        }
2292                }
2293                dc.commit();
2294                if (dc != null)
2295                        dc.close();
2296        }
2297
2298
2299        /**
2300         * Create a {@link PluginDefinition}.
2301         */
2302        private static PluginDefinition createPluginDefinition(String className,
2303                        ItemKeyData shareTo)
2304                        throws BaseException
2305        {
2306                PluginDefinition pd = null;
2307                DbControl dc = null;
2308                try
2309                {
2310                        dc = sessionControl.newDbControl();
2311                        try
2312                        {
2313                                pd = PluginDefinition.getByClassName(dc, className);
2314                        }
2315                        catch (ItemNotFoundException ex)
2316                        {}
2317                        if (pd != null)
2318                        {
2319                                log
2320                                        .info("createPluginDefinition: EXISTS [className=" + className + "]");
2321                        }
2322                        else
2323                        {
2324                                pd = PluginDefinition.getNew(dc, className);
2325                                pd.getData().setItemKey(shareTo);
2326                                dc.saveItem(pd);
2327                                dc.commit();
2328                                log
2329                                        .info("createPluginDefinition: OK [className=" + className + "]");
2330                        }
2331                }
2332                catch (BaseException ex)
2333                {
2334                        log.error(
2335                                "createPluginDefinition: FAILED [className=" + className + "]",
2336                                ex);
2337                        throw ex;
2338                }
2339                finally
2340                {
2341                        if (dc != null)
2342                                dc.close();
2343                }
2344                return pd;
2345        }
2346}