Exemplo n.º 1
0
 private void updatePlugins(DatabaseSession session) throws BimserverDatabaseException {
   Collection<Plugin> allPlugins = pluginManager.getAllPlugins(false);
   for (Plugin plugin : allPlugins) {
     Condition pluginCondition =
         new AttributeCondition(
             StorePackage.eINSTANCE.getPluginDescriptor_PluginClassName(),
             new StringLiteral(plugin.getClass().getName()));
     Map<Long, PluginDescriptor> results =
         session.query(pluginCondition, PluginDescriptor.class, Query.getDefault());
     if (results.size() == 0) {
       PluginContext pluginContext = pluginManager.getPluginContext(plugin);
       PluginDescriptor pluginDescriptor = session.create(PluginDescriptor.class);
       pluginDescriptor.setPluginClassName(plugin.getClass().getName());
       pluginDescriptor.setSimpleName(plugin.getClass().getSimpleName());
       pluginDescriptor.setDescription(plugin.getDescription() + " " + plugin.getVersion());
       pluginDescriptor.setLocation(pluginContext.getLocation().toString());
       pluginDescriptor.setPluginInterfaceClassName(getPluginInterfaceClass(plugin).getName());
       pluginDescriptor.setEnabled(true); // New plugins are enabled by default
     } else if (results.size() == 1) {
       PluginContext pluginContext = pluginManager.getPluginContext(plugin);
       PluginDescriptor pluginDescriptor = results.values().iterator().next();
       pluginDescriptor.setPluginClassName(plugin.getClass().getName());
       pluginDescriptor.setSimpleName(plugin.getClass().getSimpleName());
       pluginDescriptor.setDescription(plugin.getDescription() + " " + plugin.getVersion());
       pluginDescriptor.setLocation(pluginContext.getLocation().toString());
       pluginDescriptor.setPluginInterfaceClassName(getPluginInterfaceClass(plugin).getName());
       session.store(pluginDescriptor);
       pluginManager.getPluginContext(plugin).setEnabled(pluginDescriptor.getEnabled(), false);
     } else {
       LOGGER.error(
           "Multiple plugin descriptor objects found with the same name: "
               + plugin.getClass().getName());
     }
   }
 }
 public Deserializer createDeserializer(long deserializerOid)
     throws PluginException, UserException {
   DatabaseSession session = bimDatabase.createSession();
   try {
     DeserializerPluginConfiguration deserializerPluginConfiguration =
         session.get(
             StorePackage.eINSTANCE.getDeserializerPluginConfiguration(),
             deserializerOid,
             Query.getDefault());
     if (deserializerPluginConfiguration != null) {
       DeserializerPlugin deserializerPlugin =
           (DeserializerPlugin)
               pluginManager.getPlugin(
                   deserializerPluginConfiguration.getPluginDescriptor().getPluginClassName(),
                   true);
       if (deserializerPlugin != null) {
         ObjectType settings = deserializerPluginConfiguration.getSettings();
         return deserializerPlugin.createDeserializer(new PluginConfiguration(settings));
       } else {
         throw new UserException("No (enabled) deserializer found with oid " + deserializerOid);
       }
     }
   } catch (BimserverDatabaseException e) {
     LOGGER.error("", e);
   } finally {
     session.close();
   }
   return null;
 }
 @Override
 public Set<Revision> execute()
     throws UserException, BimserverLockConflictException, BimserverDatabaseException {
   User user = getUserByUoid(uoid);
   Condition condition =
       new HasReferenceToCondition(StorePackage.eINSTANCE.getRevision_User(), user);
   return CollectionUtils.mapToSet(
       getDatabaseSession().query(condition, Revision.class, Query.getDefault()));
 }
Exemplo n.º 4
0
 /*
  * Serializers, deserializers, renderengines etc... all have counterparts as
  * objects in the database for configuration purposes, this methods syncs
  * both versions
  */
 private void createDatabaseObjects(DatabaseSession session)
     throws BimserverLockConflictException, BimserverDatabaseException, PluginException,
         BimserverConcurrentModificationDatabaseException {
   IfcModelInterface allOfType =
       session.getAllOfType(StorePackage.eINSTANCE.getUser(), Query.getDefault());
   for (User user : allOfType.getAll(User.class)) {
     updateUserSettings(session, user);
   }
 }
 @Override
 public Void execute()
     throws UserException, BimserverLockConflictException, BimserverDatabaseException {
   DeserializerPluginConfiguration object =
       getDatabaseSession().get(geteClass(), getOid(), Query.getDefault());
   UserSettings settings = object.getUserSettings();
   settings.getDeserializers().remove(object);
   getDatabaseSession().store(settings);
   return super.execute();
 }
 @Override
 public List<SProjectSmall> execute()
     throws UserException, BimserverLockConflictException, BimserverDatabaseException {
   List<SProjectSmall> list = new ArrayList<SProjectSmall>();
   Project project =
       getDatabaseSession().get(StorePackage.eINSTANCE.getProject(), poid, Query.getDefault());
   Project rootProject = getRootProject(project);
   addProjects(list, rootProject);
   return list;
 }
Exemplo n.º 7
0
 public void update() {
   try {
     serverInfo.setVersion(
         bimServer
             .getSConverter()
             .convertFromSObject(bimServer.getVersionChecker().getLocalVersion(), null));
   } catch (BimserverDatabaseException e) {
     LOGGER.error("", e);
   }
   if (bimServer.getDatabase().getMigrator().migrationRequired()) {
     setServerState(ServerState.MIGRATION_REQUIRED);
     if (bimServer.getConfig().isAutoMigrate()) {
       try {
         bimServer.getDatabase().getMigrator().migrate();
         setServerState(ServerState.RUNNING);
       } catch (MigrationException | InconsistentModelsException e) {
         LOGGER.error("", e);
       }
     }
   } else if (bimServer.getDatabase().getMigrator().migrationImpossible()) {
     setServerState(ServerState.MIGRATION_IMPOSSIBLE);
   } else {
     DatabaseSession session = bimServer.getDatabase().createSession();
     try {
       boolean adminFound = false;
       ServerSettings settings = bimServer.getServerSettingsCache().getServerSettings();
       IfcModelInterface users =
           session.getAllOfType(StorePackage.eINSTANCE.getUser(), Query.getDefault());
       for (IdEObject idEObject : users.getValues()) {
         if (idEObject instanceof User) {
           User user = (User) idEObject;
           if (user.getUserType() == UserType.ADMIN) {
             adminFound = true;
             break;
           }
         }
       }
       if (settings.getSiteAddress().isEmpty()
           || settings.getSmtpServer().isEmpty()
           || !adminFound) {
         setServerState(ServerState.NOT_SETUP);
       } else {
         setServerState(ServerState.RUNNING);
       }
     } catch (BimserverDatabaseException e) {
       LOGGER.error("", e);
     } finally {
       session.close();
     }
   }
 }
  @Override
  public Long execute()
      throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    Long execute = super.execute();
    // Make sure the backreferences are stored as well, someday this should be automatic
    if (getIdEObject().getRenderEngine() != null) {
      getDatabaseSession().store(getIdEObject().getRenderEngine());
    }
    if (getIdEObject().getObjectIDM() != null) {
      getDatabaseSession().store(getIdEObject().getObjectIDM());
    }
    User user =
        getDatabaseSession()
            .get(StorePackage.eINSTANCE.getUser(), authorization.getUoid(), Query.getDefault());
    user.getUserSettings().getSerializers().add(getIdEObject());
    getDatabaseSession().store(user.getUserSettings());

    return execute;
  }
 public String getFileNameWithoutExtension() {
   switch (downloadType) {
     case DOWNLOAD_REVISION:
       return getRoidsString();
     case DOWNLOAD_BY_GUIDS:
       return getRoidsString() + "-" + getGuidsString();
     case DOWNLOAD_BY_NAMES:
       return getRoidsString() + "-" + getNamesString();
     case DOWNLOAD_BY_OIDS:
       return getRoidsString() + "-" + getOidsString();
     case DOWNLOAD_OF_TYPE:
       return getRoidsString() + "-" + classNames;
     case DOWNLOAD_PROJECTS:
       DatabaseSession session = bimServer.getDatabase().createSession();
       StringBuilder fileName = new StringBuilder();
       for (long roid : roids) {
         Revision revision;
         try {
           revision =
               session.get(
                   session.getEClassForName("store", "Revision"), roid, Query.getDefault());
           for (ConcreteRevision concreteRevision : revision.getConcreteRevisions()) {
             fileName.append(concreteRevision.getProject().getName() + "-");
           }
         } catch (BimserverDatabaseException e) {
           e.printStackTrace();
         }
       }
       fileName.delete(fileName.length() - 1, fileName.length());
       return fileName.toString();
     case DOWNLOAD_COMPARE:
       return "compare";
     case DOWNLOAD_JSON_QUERY:
       return getRoidsString();
     case DOWNLOAD_QUERY:
       return "query";
   }
   return "unknown";
 }
 @Override
 public List<ModelMergerPluginConfiguration> execute()
     throws UserException, BimserverLockConflictException, BimserverDatabaseException {
   Condition condition =
       new IsOfTypeCondition(StorePackage.eINSTANCE.getModelMergerPluginConfiguration());
   Map<Long, ModelMergerPluginConfiguration> result =
       getDatabaseSession()
           .query(condition, ModelMergerPluginConfiguration.class, Query.getDefault());
   List<ModelMergerPluginConfiguration> mapToList = CollectionUtils.mapToList(result);
   if (onlyEnabled) {
     Iterator<ModelMergerPluginConfiguration> iterator = mapToList.iterator();
     while (iterator.hasNext()) {
       ModelMergerPluginConfiguration modelMerger = iterator.next();
       if (!bimServer
               .getPluginManager()
               .isEnabled(modelMerger.getPluginDescriptor().getPluginClassName())
           || !modelMerger.getEnabled()) {
         iterator.remove();
       }
     }
   }
   return mapToList;
 }
  @Override
  public IfcModelInterface execute()
      throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    User user = getUserByUoid(getAuthorization().getUoid());
    Set<String> foundNames = new HashSet<String>();
    IfcModelSet ifcModelSet = new IfcModelSet();
    Project project = null;
    long incrSize = 0L;

    SerializerPluginConfiguration serializerPluginConfiguration =
        getDatabaseSession()
            .get(
                StorePackage.eINSTANCE.getSerializerPluginConfiguration(),
                serializerOid,
                Query.getDefault());

    for (Long roid : roids) {
      Revision virtualRevision = getRevisionByRoid(roid);
      project = virtualRevision.getProject();
      if (!getAuthorization().hasRightsOnProjectOrSuperProjectsOrSubProjects(user, project)) {
        throw new UserException(
            "User has insufficient rights to download revisions from this project");
      }
      Map<ConcreteRevision, Set<Long>> map = new HashMap<ConcreteRevision, Set<Long>>();
      for (String name : names) {
        if (!foundNames.contains(name)) {
          for (ConcreteRevision concreteRevision : virtualRevision.getConcreteRevisions()) {
            for (ObjectIdentifier objectIdentifier :
                getDatabaseSession()
                    .getOidsOfName(
                        name, concreteRevision.getProject().getId(), concreteRevision.getId())) {
              foundNames.add(name);
              if (!map.containsKey(concreteRevision)) {
                map.put(concreteRevision, new HashSet<Long>());
                incrSize += concreteRevision.getSize();
              }
              map.get(concreteRevision).add(objectIdentifier.getOid());
            }
          }
        }
      }
      final long totalSize = incrSize;
      final AtomicLong total = new AtomicLong();

      for (ConcreteRevision concreteRevision : map.keySet()) {
        IfcModel subModel = new IfcModel();
        int highestStopId = findHighestStopRid(project, concreteRevision);
        Query query =
            new Query(
                concreteRevision.getProject().getId(),
                concreteRevision.getId(),
                objectIDM,
                deep,
                highestStopId);
        subModel.addChangeListener(
            new IfcModelChangeListener() {
              @Override
              public void objectAdded() {
                total.incrementAndGet();
                progress = (int) Math.round(100.0 * total.get() / totalSize);
              }
            });
        Set<Long> oids = map.get(concreteRevision);
        getDatabaseSession().getMapWithOids(subModel, oids, query);
        subModel.getModelMetaData().setDate(concreteRevision.getDate());

        try {
          checkGeometry(
              serializerPluginConfiguration,
              bimServer.getPluginManager(),
              subModel,
              project,
              concreteRevision,
              virtualRevision);
        } catch (GeometryGeneratingException e) {
          throw new UserException(e);
        }

        ifcModelSet.add(subModel);
      }
    }
    IfcModelInterface ifcModel = new IfcModel();
    try {
      ifcModel =
          bimServer
              .getMergerFactory()
              .createMerger(getDatabaseSession(), getAuthorization().getUoid())
              .merge(project, ifcModelSet, new ModelHelper(ifcModel));
      ifcModel.getModelMetaData().setName("query");
      for (String name : names) {
        if (!foundNames.contains(name)) {
          throw new UserException("Name " + name + " not found");
        }
      }
      ifcModel.getModelMetaData().setRevisionId(1);
      ifcModel
          .getModelMetaData()
          .setAuthorizedUser(getUserByUoid(getAuthorization().getUoid()).getName());
      ifcModel.getModelMetaData().setDate(new Date());
      return ifcModel;
    } catch (MergeException e) {
      throw new UserException(e);
    }
  }
Exemplo n.º 12
0
  private IfcModel realCheckout(
      Project project, Revision revision, DatabaseSession databaseSession, User user)
      throws BimserverLockConflictException, BimserverDatabaseException, UserException {
    SerializerPluginConfiguration serializerPluginConfiguration =
        getDatabaseSession()
            .get(
                StorePackage.eINSTANCE.getSerializerPluginConfiguration(),
                serializerOid,
                Query.getDefault());
    final long totalSize = revision.getSize();
    final AtomicLong total = new AtomicLong();

    IfcModelSet ifcModelSet = new IfcModelSet();
    for (ConcreteRevision subRevision : revision.getConcreteRevisions()) {
      IfcModel subModel = new IfcModel();
      int highestStopId = findHighestStopRid(project, subRevision);
      Query query =
          new Query(
              subRevision.getProject().getId(), subRevision.getId(), null, Deep.YES, highestStopId);
      subModel.addChangeListener(
          new IfcModelChangeListener() {
            @Override
            public void objectAdded() {
              total.incrementAndGet();
              if (totalSize == 0) {
                setProgress("Preparing checkout...", 0);
              } else {
                setProgress(
                    "Preparing checkout...", (int) Math.round(100.0 * total.get() / totalSize));
              }
            }
          });
      getDatabaseSession().getMap(subModel, query);
      try {
        checkGeometry(
            serializerPluginConfiguration,
            getBimServer().getPluginManager(),
            subModel,
            project,
            subRevision,
            revision);
      } catch (GeometryGeneratingException e) {
        throw new UserException(e);
      }
      subModel.getModelMetaData().setDate(subRevision.getDate());
      ifcModelSet.add(subModel);
    }

    IfcModelInterface ifcModel = new IfcModel();
    if (ifcModelSet.size() > 1) {
      try {
        ifcModel =
            getBimServer()
                .getMergerFactory()
                .createMerger(getDatabaseSession(), getAuthorization().getUoid())
                .merge(revision.getProject(), ifcModelSet, new ModelHelper(ifcModel));
      } catch (MergeException e) {
        throw new UserException(e);
      }
    } else {
      ifcModel = ifcModelSet.iterator().next();
    }

    ifcModel.getModelMetaData().setName(project.getName() + "." + revision.getId());
    ifcModel.getModelMetaData().setRevisionId(project.getRevisions().indexOf(revision) + 1);
    ifcModel.getModelMetaData().setAuthorizedUser(user.getName());
    ifcModel.getModelMetaData().setDate(new Date());
    return (IfcModel) ifcModel;
  }
Exemplo n.º 13
0
  private void initDatabaseDependantItems() throws BimserverDatabaseException {
    serverSettingsCache.init();
    notificationsManager.init();

    getSerializerFactory().init(pluginManager, bimDatabase, this);
    getDeserializerFactory().init(pluginManager, bimDatabase);
    try {
      DatabaseSession session = bimDatabase.createSession();
      try {
        updatePlugins(session);
        session.commit();
      } catch (ServiceException e) {
        LOGGER.error("", e);
      } finally {
        session.close();
      }

      session = bimDatabase.createSession();
      createDatabaseObjects(session);

      ServerSettings serverSettings = serverSettingsCache.getServerSettings();

      for (WebModulePlugin webModulePlugin : pluginManager.getAllWebPlugins(true)) {
        WebModulePluginConfiguration webPluginConfiguration =
            find(serverSettings.getWebModules(), webModulePlugin.getClass().getName());
        if (webPluginConfiguration == null) {
          webPluginConfiguration = session.create(WebModulePluginConfiguration.class);
          serverSettings.getWebModules().add(webPluginConfiguration);
          genericPluginConversion(
              session,
              webModulePlugin,
              webPluginConfiguration,
              getPluginDescriptor(session, webModulePlugin.getClass().getName()));
        } else {
          if (webPluginConfiguration == serverSettings.getWebModule()) {
            setDefaultWebModule(webModulePlugin);
          }
        }
      }

      // Set the default
      if (serverSettings.getWebModule() == null) {
        WebModulePluginConfiguration bimviewsWebModule =
            findWebModule(serverSettings, "org.bimserver.bimviews.BimViewsWebModulePlugin");
        if (bimviewsWebModule != null) {
          serverSettings.setWebModule(bimviewsWebModule);
          setDefaultWebModule(
              pluginManager.getWebModulePlugin(
                  bimviewsWebModule.getPluginDescriptor().getPluginClassName(), true));
        } else {
          WebModulePluginConfiguration defaultWebModule =
              findWebModule(
                  serverSettings, "org.bimserver.defaultwebmodule.DefaultWebModulePlugin");
          if (defaultWebModule != null) {
            serverSettings.setWebModule(defaultWebModule);
            setDefaultWebModule(
                pluginManager.getWebModulePlugin(
                    defaultWebModule.getPluginDescriptor().getPluginClassName(), true));
          }
        }
      }
      session.store(serverSettings);

      Condition condition =
          new AttributeCondition(
              StorePackage.eINSTANCE.getUser_Username(), new StringLiteral("system"));
      User systemUser = session.querySingle(condition, User.class, Query.getDefault());

      ServerStarted serverStarted = session.create(ServerStarted.class);
      serverStarted.setDate(new Date());
      serverStarted.setAccessMethod(AccessMethod.INTERNAL);
      serverStarted.setExecutor(systemUser);
      try {
        session.store(serverStarted);
        session.commit();
      } catch (BimserverLockConflictException e) {
        throw new BimserverDatabaseException(e);
      } catch (ServiceException e) {
        throw new BimserverDatabaseException(e);
      } finally {
        session.close();
      }

      webModules = new HashMap<String, WebModulePlugin>();
      DatabaseSession ses = bimDatabase.createSession();
      try {
        List<WebModulePluginConfiguration> webModuleConfigurations =
            serverSettingsCache.getServerSettings().getWebModules();
        for (WebModulePluginConfiguration webModulePluginConfiguration : webModuleConfigurations) {
          String contextPath = "";
          for (Parameter parameter : webModulePluginConfiguration.getSettings().getParameters()) {
            if (parameter.getName().equals("contextPath")) {
              contextPath = ((StringType) parameter.getValue()).getValue();
            }
          }
          webModules.put(
              contextPath,
              (WebModulePlugin)
                  pluginManager.getPlugin(
                      webModulePluginConfiguration.getPluginDescriptor().getPluginClassName(),
                      true));
        }
        //				if (serverSettingsCache.getServerSettings().getWebModule() != null) {
        //					defaultWebModule = (WebModulePlugin)
        // pluginManager.getPlugin(serverSettingsCache.getServerSettings().getWebModule().getPluginDescriptor().getPluginClassName(), true);
        //				}
      } finally {
        ses.close();
      }

      Integer protocolBuffersPort =
          getServerSettingsCache().getServerSettings().getProtocolBuffersPort();
      if (protocolBuffersPort >= 1 && protocolBuffersPort <= 65535) {
        try {
          protocolBuffersServer =
              new ProtocolBuffersServer(
                  protocolBuffersMetaData, serviceFactory, servicesMap, protocolBuffersPort);
          protocolBuffersServer.start();
        } catch (Exception e) {
          LOGGER.error("", e);
        }
      }

      bimServerClientFactory =
          new DirectBimServerClientFactory<ServiceInterface>(
              serverSettingsCache.getServerSettings().getSiteAddress(),
              serviceFactory,
              servicesMap,
              pluginManager,
              metaDataManager);
      pluginManager.setBimServerClientFactory(bimServerClientFactory);
    } catch (BimserverLockConflictException e) {
      throw new BimserverDatabaseException(e);
    } catch (PluginException e) {
      throw new BimserverDatabaseException(e);
    }
  }
Exemplo n.º 14
0
  public void start()
      throws DatabaseInitException, BimserverDatabaseException, PluginException,
          DatabaseRestartRequiredException, ServerException {
    try {
      LOGGER.debug("Starting BIMserver");
      SVersion localVersion = versionChecker.getLocalVersion();
      if (localVersion != null) {
        LOGGER.info(
            "Version: "
                + localVersion.getMajor()
                + "."
                + localVersion.getMinor()
                + "."
                + localVersion.getRevision()
                + " - "
                + localVersion.getDate());
      } else {
        LOGGER.info("Unknown version");
      }

      try {
        pluginManager.addPluginChangeListener(
            new PluginChangeListener() {
              @Override
              public void pluginStateChanged(PluginContext pluginContext, boolean enabled) {
                // Reflect this change also in the database
                Condition pluginCondition =
                    new AttributeCondition(
                        StorePackage.eINSTANCE.getPluginDescriptor_PluginClassName(),
                        new StringLiteral(pluginContext.getPlugin().getClass().getName()));
                DatabaseSession session = bimDatabase.createSession();
                try {
                  Map<Long, PluginDescriptor> pluginsFound =
                      session.query(pluginCondition, PluginDescriptor.class, Query.getDefault());
                  if (pluginsFound.size() == 0) {
                    LOGGER.error(
                        "Error changing plugin-state in database, plugin "
                            + pluginContext.getPlugin().getClass().getName()
                            + " not found");
                  } else if (pluginsFound.size() == 1) {
                    PluginDescriptor pluginConfiguration = pluginsFound.values().iterator().next();
                    pluginConfiguration.setEnabled(pluginContext.isEnabled());
                    session.store(pluginConfiguration);
                  } else {
                    LOGGER.error(
                        "Error, too many plugin-objects found in database for name "
                            + pluginContext.getPlugin().getClass().getName());
                  }
                  session.commit();
                } catch (BimserverDatabaseException e) {
                  LOGGER.error("", e);
                } catch (ServiceException e) {
                  LOGGER.error("", e);
                } finally {
                  session.close();
                }
              }
            });
        pluginManager.loadPlugin(
            ObjectIDMPlugin.class,
            new File(".").toURI(),
            "Internal",
            new SchemaFieldObjectIDMPlugin(),
            getClass().getClassLoader(),
            PluginSourceType.INTERNAL,
            null);
      } catch (Exception e) {
        LOGGER.error("", e);
      }

      try {
        metaDataManager.init();
        pluginManager.initAllLoadedPlugins();
      } catch (PluginException e) {
        LOGGER.error("", e);
      }
      serverStartTime = new GregorianCalendar();

      longActionManager = new LongActionManager();

      Set<EPackage> packages = new LinkedHashSet<>();
      packages.add(Ifc2x3tc1Package.eINSTANCE);
      packages.add(Ifc4Package.eINSTANCE);
      templateEngine = new TemplateEngine();
      templateEngine.init(config.getResourceFetcher().getResource("templates/"));
      Path databaseDir = config.getHomeDir().resolve("database");
      BerkeleyKeyValueStore keyValueStore = new BerkeleyKeyValueStore(databaseDir);

      schemaConverterManager.registerConverter(new Ifc2x3tc1ToIfc4SchemaConverterFactory());
      schemaConverterManager.registerConverter(new Ifc4ToIfc2x3tc1SchemaConverterFactory());

      metricsRegistry = new MetricsRegistry();

      Query.setPackageMetaDataForDefaultQuery(metaDataManager.getPackageMetaData("store"));

      bimDatabase = new Database(this, packages, keyValueStore, metaDataManager);
      try {
        bimDatabase.init();
      } catch (DatabaseRestartRequiredException e) {
        bimDatabase.close();
        keyValueStore = new BerkeleyKeyValueStore(databaseDir);
        bimDatabase = new Database(this, packages, keyValueStore, metaDataManager);
        try {
          bimDatabase.init();
        } catch (InconsistentModelsException e1) {
          LOGGER.error("", e);
          serverInfoManager.setServerState(ServerState.FATAL_ERROR);
          serverInfoManager.setErrorMessage("Inconsistent models");
        }
      } catch (InconsistentModelsException e) {
        LOGGER.error("", e);
        serverInfoManager.setServerState(ServerState.FATAL_ERROR);
        serverInfoManager.setErrorMessage("Inconsistent models");
      }

      DatabaseSession encsession = bimDatabase.createSession();
      try {
        byte[] encryptionkeyBytes = null;
        if (!bimDatabase.getRegistry().has(ENCRYPTIONKEY, encsession)) {
          encryptionkeyBytes = new byte[16];
          new SecureRandom().nextBytes(encryptionkeyBytes);
          bimDatabase.getRegistry().save(ENCRYPTIONKEY, encryptionkeyBytes, encsession);
          encsession.commit();
        } else {
          encryptionkeyBytes = bimDatabase.getRegistry().readByteArray(ENCRYPTIONKEY, encsession);
        }
        encryptionkey = new SecretKeySpec(encryptionkeyBytes, "AES");
      } finally {
        encsession.close();
      }

      protocolBuffersMetaData = new ProtocolBuffersMetaData();
      protocolBuffersMetaData.load(servicesMap, ProtocolBuffersBimServerClientFactory.class);

      serverInfoManager.init(this);

      webModuleManager = new WebModuleManager(this);

      jsonHandler = new JsonHandler(this);

      serializerFactory = new SerializerFactory();
      deserializerFactory = new DeserializerFactory();

      serverSettingsCache = new ServerSettingsCache(bimDatabase);

      serverInfoManager.update();

      if (serverInfoManager.getServerState() == ServerState.MIGRATION_REQUIRED) {
        serverInfoManager.registerStateChangeListener(
            new StateChangeListener() {
              @Override
              public void stateChanged(ServerState oldState, ServerState newState) {
                if (oldState == ServerState.MIGRATION_REQUIRED && newState == ServerState.RUNNING) {
                  try {
                    initDatabaseDependantItems();
                  } catch (BimserverDatabaseException e) {
                    LOGGER.error("", e);
                  }
                }
              }
            });
      } else {
        initDatabaseDependantItems();
      }

      mailSystem = new MailSystem(this);

      diskCacheManager = new DiskCacheManager(this, config.getHomeDir().resolve("cache"));

      mergerFactory = new MergerFactory(this);

      FileBasedReflectorFactoryBuilder factoryBuilder = new FileBasedReflectorFactoryBuilder();
      reflectorFactory = factoryBuilder.newReflectorFactory();
      if (reflectorFactory == null) {
        throw new RuntimeException("No reflector factory!");
      }
      servicesMap.setReflectorFactory(reflectorFactory);

      bimScheduler = new JobScheduler(this);
      bimScheduler.start();

      if (config.isStartEmbeddedWebServer()) {
        embeddedWebServer.start();
      }

      if (config.isStartCommandLine()) {
        commandLine = new CommandLine(this);
        commandLine.start();
      }
    } catch (Throwable e) {
      LOGGER.error("", e);
      serverInfoManager.setErrorMessage(e.getMessage());
    }
  }