Search in sources :

Example 1 with ServicePlugin

use of org.bimserver.plugins.services.ServicePlugin in project BIMserver by opensourceBIM.

the class BimServer method start.

public void start() throws DatabaseInitException, BimserverDatabaseException, PluginException, DatabaseRestartRequiredException, ServerException {
    try {
        LOGGER.debug("Starting BIMserver");
        if (versionChecker != null) {
            SVersion localVersion = versionChecker.getLocalVersion();
            if (localVersion != null) {
                LOGGER.info("Version: " + localVersion.getFullString());
            } else {
                LOGGER.info("Unknown version");
            }
        } else {
            LOGGER.info("Unknown version");
        }
        try {
            pluginManager.setPluginChangeListener(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, OldQuery.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();
                    }
                }

                @Override
                public long pluginBundleUpdated(PluginBundle pluginBundle) {
                    SPluginBundleVersion sPluginBundleVersion = pluginBundle.getPluginBundleVersion();
                    try (DatabaseSession session = bimDatabase.createSession()) {
                        PluginBundleVersion current = null;
                        IfcModelInterface allOfType = session.getAllOfType(StorePackage.eINSTANCE.getPluginBundleVersion(), OldQuery.getDefault());
                        for (PluginBundleVersion pbv : allOfType.getAll(PluginBundleVersion.class)) {
                            if (pbv.getGroupId().equals(pluginBundle.getPluginBundleVersion().getGroupId()) && pbv.getArtifactId().equals(pluginBundle.getPluginBundleVersion().getArtifactId())) {
                                // Current pluginBundle found
                                current = pbv;
                            }
                        }
                        if (current != null) {
                            current.setDescription(sPluginBundleVersion.getArtifactId());
                            current.setIcon(sPluginBundleVersion.getIcon());
                            current.setMismatch(sPluginBundleVersion.isMismatch());
                            current.setRepository(sPluginBundleVersion.getRepository());
                            current.setType(getSConverter().convertFromSObject(sPluginBundleVersion.getType()));
                            current.setVersion(sPluginBundleVersion.getVersion());
                            current.setOrganization(sPluginBundleVersion.getOrganization());
                            current.setName(sPluginBundleVersion.getName());
                            current.setDate(sPluginBundleVersion.getDate());
                            session.store(current);
                            session.commit();
                        }
                        return current.getOid();
                    } catch (BimserverDatabaseException e) {
                        LOGGER.error("", e);
                    } catch (ServiceException e) {
                        LOGGER.error("", e);
                    }
                    return -1;
                }

                @Override
                public void pluginUpdated(long pluginBundleVersionId, PluginContext newPluginContext, SPluginInformation sPluginInformation) throws BimserverDatabaseException {
                    try (DatabaseSession session = bimDatabase.createSession()) {
                        Plugin plugin = newPluginContext.getPlugin();
                        Condition pluginCondition = new AttributeCondition(StorePackage.eINSTANCE.getPluginDescriptor_Identifier(), new StringLiteral(newPluginContext.getIdentifier()));
                        Map<Long, PluginDescriptor> pluginsFound = session.query(pluginCondition, PluginDescriptor.class, OldQuery.getDefault());
                        for (PluginDescriptor pluginDescriptor : pluginsFound.values()) {
                            pluginDescriptor.setIdentifier(newPluginContext.getIdentifier());
                            pluginDescriptor.setPluginClassName(plugin.getClass().getName());
                            pluginDescriptor.setDescription(newPluginContext.getDescription());
                            pluginDescriptor.setName(sPluginInformation.getName());
                            pluginDescriptor.setLocation(newPluginContext.getLocation().toString());
                            pluginDescriptor.setPluginInterfaceClassName(getPluginInterface(plugin.getClass()).getName());
                            pluginDescriptor.setEnabled(sPluginInformation.isEnabled());
                            pluginDescriptor.setInstallForNewUsers(sPluginInformation.isInstallForNewUsers());
                            PluginBundleVersion value = session.get(pluginBundleVersionId, OldQuery.getDefault());
                            pluginDescriptor.setPluginBundleVersion(value);
                            session.store(pluginDescriptor);
                            if (sPluginInformation.isInstallForAllUsers()) {
                                IfcModelInterface allOfType = session.getAllOfType(StorePackage.eINSTANCE.getUser(), OldQuery.getDefault());
                                for (User user : allOfType.getAll(User.class)) {
                                    if (user.getState() == ObjectState.ACTIVE) {
                                        updateUserPlugin(session, user, pluginDescriptor, newPluginContext);
                                    }
                                }
                            }
                            if (newPluginContext.getPlugin() instanceof WebModulePlugin) {
                                ServerSettings serverSettings = getServerSettingsCache().getServerSettings();
                                WebModulePluginConfiguration webPluginConfiguration = find(serverSettings.getWebModules(), newPluginContext.getIdentifier());
                                if (webPluginConfiguration == null) {
                                    webPluginConfiguration = session.create(WebModulePluginConfiguration.class);
                                    serverSettings.getWebModules().add(webPluginConfiguration);
                                }
                                genericPluginConversion(newPluginContext, session, webPluginConfiguration, pluginDescriptor);
                                String contextPath = "";
                                for (Parameter parameter : webPluginConfiguration.getSettings().getParameters()) {
                                    if (parameter.getName().equals("contextPath")) {
                                        contextPath = ((StringType) parameter.getValue()).getValue();
                                    }
                                }
                                String identifier = webPluginConfiguration.getPluginDescriptor().getIdentifier();
                                webModules.put(contextPath, (WebModulePlugin) pluginManager.getPlugin(identifier, true));
                            } else if (newPluginContext.getPlugin() instanceof ServicePlugin) {
                                IfcModelInterface allOfType = session.getAllOfType(StorePackage.eINSTANCE.getInternalServicePluginConfiguration(), OldQuery.getDefault());
                                List<InternalServicePluginConfiguration> all = new ArrayList<>(allOfType.getAll(InternalServicePluginConfiguration.class));
                                for (InternalServicePluginConfiguration internalServicePluginConfiguration : all) {
                                    if (internalServicePluginConfiguration.getPluginDescriptor().getIdentifier().equals(newPluginContext.getIdentifier())) {
                                        activateService(internalServicePluginConfiguration.getUserSettings().getOid(), internalServicePluginConfiguration);
                                    }
                                }
                            }
                        }
                        try {
                            session.commit();
                        } catch (ServiceException e) {
                            LOGGER.error("", e);
                        }
                    }
                }

                @Override
                public void pluginInstalled(long pluginBundleVersionId, PluginContext pluginContext, SPluginInformation sPluginInformation) throws BimserverDatabaseException {
                    try (DatabaseSession session = bimDatabase.createSession()) {
                        Plugin plugin = pluginContext.getPlugin();
                        Condition pluginCondition = new AttributeCondition(StorePackage.eINSTANCE.getPluginDescriptor_Identifier(), new StringLiteral(pluginContext.getIdentifier()));
                        Map<Long, PluginDescriptor> pluginsFound = session.query(pluginCondition, PluginDescriptor.class, OldQuery.getDefault());
                        PluginDescriptor pluginDescriptor = null;
                        if (pluginsFound.size() > 0) {
                            pluginDescriptor = pluginsFound.values().iterator().next();
                        } else {
                            pluginDescriptor = session.create(PluginDescriptor.class);
                        }
                        pluginDescriptor.setIdentifier(pluginContext.getIdentifier());
                        pluginDescriptor.setPluginClassName(plugin.getClass().getName());
                        pluginDescriptor.setDescription(pluginContext.getDescription());
                        pluginDescriptor.setName(sPluginInformation.getName());
                        pluginDescriptor.setLocation(pluginContext.getLocation().toString());
                        pluginDescriptor.setPluginInterfaceClassName(getPluginInterface(plugin.getClass()).getName());
                        pluginDescriptor.setEnabled(sPluginInformation.isEnabled());
                        pluginDescriptor.setInstallForNewUsers(sPluginInformation.isInstallForNewUsers());
                        pluginDescriptor.setPluginBundleVersion(session.get(pluginBundleVersionId, OldQuery.getDefault()));
                        if (sPluginInformation.isInstallForAllUsers()) {
                            IfcModelInterface allOfType = session.getAllOfType(StorePackage.eINSTANCE.getUser(), OldQuery.getDefault());
                            for (User user : allOfType.getAll(User.class)) {
                                if (user.getState() == ObjectState.ACTIVE) {
                                    updateUserPlugin(session, user, pluginDescriptor, pluginContext);
                                }
                            }
                        }
                        if (pluginContext.getPlugin() instanceof WebModulePlugin) {
                            ServerSettings serverSettings = getServerSettingsCache().getServerSettings();
                            WebModulePluginConfiguration webPluginConfiguration = find(serverSettings.getWebModules(), pluginContext.getIdentifier());
                            if (webPluginConfiguration == null) {
                                webPluginConfiguration = session.create(WebModulePluginConfiguration.class);
                                serverSettings.getWebModules().add(webPluginConfiguration);
                                genericPluginConversion(pluginContext, session, webPluginConfiguration, pluginDescriptor);
                                session.store(serverSettings);
                            }
                            String contextPath = "";
                            for (Parameter parameter : webPluginConfiguration.getSettings().getParameters()) {
                                if (parameter.getName().equals("contextPath")) {
                                    contextPath = ((StringType) parameter.getValue()).getValue();
                                }
                            }
                            webModules.put(contextPath, (WebModulePlugin) pluginManager.getPlugin(pluginContext.getIdentifier(), true));
                        }
                        try {
                            session.commit();
                        } catch (ServiceException e) {
                            LOGGER.error("", e);
                        }
                    }
                }

                @Override
                public void pluginUninstalled(PluginContext pluginContext) {
                    // Reflect this change also in the database
                    Condition pluginCondition = new AttributeCondition(StorePackage.eINSTANCE.getPluginDescriptor_Identifier(), new StringLiteral(pluginContext.getIdentifier()));
                    DatabaseSession session = bimDatabase.createSession();
                    try {
                        Map<Long, PluginDescriptor> pluginsFound = session.query(pluginCondition, PluginDescriptor.class, OldQuery.getDefault());
                        if (pluginsFound.size() == 0) {
                            LOGGER.error("Error removing plugin-state in database, plugin " + pluginContext.getPlugin().getClass().getName() + " not found");
                        } else if (pluginsFound.size() == 1) {
                            PluginDescriptor pluginDescriptor = pluginsFound.values().iterator().next();
                            for (PluginConfiguration pluginConfiguration : pluginDescriptor.getConfigurations()) {
                                session.delete(pluginConfiguration, -1);
                            }
                            if (pluginContext.getPlugin() instanceof WebModulePlugin) {
                                ServerSettings serverSettings = getServerSettingsCache().getServerSettings();
                                WebModulePluginConfiguration webPluginConfiguration = find(serverSettings.getWebModules(), pluginContext.getIdentifier());
                                serverSettings.getWebModules().remove(webPluginConfiguration);
                                session.store(serverSettings);
                                String contextPath = "";
                                for (Parameter parameter : webPluginConfiguration.getSettings().getParameters()) {
                                    if (parameter.getName().equals("contextPath")) {
                                        contextPath = ((StringType) parameter.getValue()).getValue();
                                    }
                                }
                                webModules.remove(contextPath);
                            }
                            session.delete(pluginDescriptor, -1);
                        } 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();
                    }
                }

                @Override
                public long pluginBundleInstalled(PluginBundle pluginBundle) {
                    try (DatabaseSession session = bimDatabase.createSession()) {
                        PluginBundleVersion current = null;
                        IfcModelInterface allOfType = session.getAllOfType(StorePackage.eINSTANCE.getPluginBundleVersion(), OldQuery.getDefault());
                        for (PluginBundleVersion pbv : allOfType.getAll(PluginBundleVersion.class)) {
                            if (pbv.getGroupId().equals(pluginBundle.getPluginBundleVersion().getGroupId()) && pbv.getArtifactId().equals(pluginBundle.getPluginBundleVersion().getArtifactId())) {
                                // Current pluginBundle found
                                current = pbv;
                            }
                        }
                        PluginBundleVersion pluginBundleVersion = null;
                        if (current != null) {
                            pluginBundleVersion = current;
                            session.store(pluginBundleVersion);
                        } else {
                            pluginBundleVersion = session.create(PluginBundleVersion.class);
                        }
                        SPluginBundleVersion sPluginBundleVersion = pluginBundle.getPluginBundleVersion();
                        // SConverter should be used here, but it does not seem to trigger the database session in the rights way, just copying over field for now
                        pluginBundleVersion.setArtifactId(sPluginBundleVersion.getArtifactId());
                        pluginBundleVersion.setDescription(sPluginBundleVersion.getArtifactId());
                        pluginBundleVersion.setGroupId(sPluginBundleVersion.getGroupId());
                        pluginBundleVersion.setIcon(sPluginBundleVersion.getIcon());
                        pluginBundleVersion.setMismatch(sPluginBundleVersion.isMismatch());
                        pluginBundleVersion.setRepository(sPluginBundleVersion.getRepository());
                        pluginBundleVersion.setType(getSConverter().convertFromSObject(sPluginBundleVersion.getType()));
                        pluginBundleVersion.setVersion(sPluginBundleVersion.getVersion());
                        pluginBundleVersion.setOrganization(sPluginBundleVersion.getOrganization());
                        pluginBundleVersion.setName(sPluginBundleVersion.getName());
                        pluginBundleVersion.setDate(sPluginBundleVersion.getDate());
                        session.commit();
                        return pluginBundleVersion.getOid();
                    } catch (BimserverDatabaseException e) {
                        LOGGER.error("", e);
                    } catch (ServiceException e) {
                        LOGGER.error("", e);
                    }
                    return -1;
                }

                @Override
                public void pluginBundleUninstalled(PluginBundle pluginBundle) {
                }
            });
        } 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();
        URL emailTemplates = config.getResourceFetcher().getResource("emailtemplates/");
        if (emailTemplates != null) {
            templateEngine.init(emailTemplates);
        } else {
            LOGGER.info("No email templates found");
        }
        Path databaseDir = config.getHomeDir().resolve("database");
        BerkeleyKeyValueStore keyValueStore = new BerkeleyKeyValueStore(databaseDir);
        schemaConverterManager.registerConverter(new Ifc2x3tc1ToIfc4SchemaConverterFactory());
        schemaConverterManager.registerConverter(new Ifc4ToIfc2x3tc1SchemaConverterFactory());
        metricsRegistry = new MetricsRegistry();
        Path mavenPath = config.getHomeDir().resolve("maven");
        if (!Files.exists(mavenPath)) {
            Files.createDirectories(mavenPath);
        }
        mavenPluginRepository = new MavenPluginRepository(mavenPath, "http://central.maven.org/maven2", "~/.m2/repository");
        OldQuery.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");
        }
        try (DatabaseSession encsession = bimDatabase.createSession()) {
            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");
        }
        cleanupStaleData();
        protocolBuffersMetaData = new ProtocolBuffersMetaData();
        protocolBuffersMetaData.load(servicesMap, ProtocolBuffersBimServerClientFactory.class);
        serverInfoManager.init(this);
        webModuleManager = new WebModuleManager(this);
        jsonHandler = new JsonHandler(this);
        serializerFactory = new SerializerFactory();
        serverSettingsCache = new ServerSettingsCache(bimDatabase);
        serverInfoManager.update();
        // int renderEngineProcesses = getServerSettingsCache().getServerSettings().getRenderEngineProcesses();
        // RenderEnginePoolFactory renderEnginePoolFactory = new CommonsPoolingRenderEnginePoolFactory(renderEngineProcesses);
        RenderEnginePoolFactory renderEnginePoolFactory = new NoPoolingRenderEnginePoolFactory();
        renderEnginePools = new RenderEnginePools(this, renderEnginePoolFactory);
        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"));
        newDiskCacheManager = new NewDiskCacheManager(this, config.getHomeDir().resolve("cache"));
        mergerFactory = new MergerFactory(this);
        RealtimeReflectorFactoryBuilder factoryBuilder = new RealtimeReflectorFactoryBuilder(servicesMap);
        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();
        }
        if (getServerInfoManager().getServerState() == ServerState.SETUP) {
            getServerInfoManager().setServerState(ServerState.RUNNING);
        }
    } catch (Throwable e) {
        LOGGER.error("", e);
        serverInfoManager.setErrorMessage(e.getMessage());
    }
}
Also used : SPluginBundleVersion(org.bimserver.interfaces.objects.SPluginBundleVersion) LinkedHashSet(java.util.LinkedHashSet) DatabaseSession(org.bimserver.database.DatabaseSession) StringType(org.bimserver.models.store.StringType) IfcModelInterface(org.bimserver.emf.IfcModelInterface) ArrayList(java.util.ArrayList) ProtocolBuffersMetaData(org.bimserver.shared.pb.ProtocolBuffersMetaData) LongActionManager(org.bimserver.longaction.LongActionManager) EPackage(org.eclipse.emf.ecore.EPackage) PluginBundle(org.bimserver.plugins.PluginBundle) TemplateEngine(org.bimserver.templating.TemplateEngine) Ifc4ToIfc2x3tc1SchemaConverterFactory(org.bimserver.schemaconverter.Ifc4ToIfc2x3tc1SchemaConverterFactory) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Database(org.bimserver.database.Database) BimDatabase(org.bimserver.database.BimDatabase) Ifc2x3tc1ToIfc4SchemaConverterFactory(org.bimserver.schemaconverter.Ifc2x3tc1ToIfc4SchemaConverterFactory) PluginChangeListener(org.bimserver.plugins.PluginChangeListener) SPluginInformation(org.bimserver.interfaces.objects.SPluginInformation) WebModulePluginConfiguration(org.bimserver.models.store.WebModulePluginConfiguration) PluginException(org.bimserver.shared.exceptions.PluginException) AttributeCondition(org.bimserver.database.query.conditions.AttributeCondition) GregorianCalendar(java.util.GregorianCalendar) SecureRandom(java.security.SecureRandom) SVersion(org.bimserver.interfaces.objects.SVersion) PluginDescriptor(org.bimserver.models.store.PluginDescriptor) StringLiteral(org.bimserver.database.query.literals.StringLiteral) ServiceException(org.bimserver.shared.exceptions.ServiceException) MavenPluginRepository(org.bimserver.plugins.MavenPluginRepository) DatabaseRestartRequiredException(org.bimserver.database.DatabaseRestartRequiredException) RenderEnginePools(org.bimserver.renderengine.RenderEnginePools) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) SServicesMap(org.bimserver.shared.meta.SServicesMap) InconsistentModelsException(org.bimserver.database.migrations.InconsistentModelsException) ServicePlugin(org.bimserver.plugins.services.ServicePlugin) NoPoolingRenderEnginePoolFactory(org.bimserver.renderengine.NoPoolingRenderEnginePoolFactory) User(org.bimserver.models.store.User) URL(java.net.URL) ServerSettings(org.bimserver.models.store.ServerSettings) PluginConfiguration(org.bimserver.models.store.PluginConfiguration) SerializerPluginConfiguration(org.bimserver.models.store.SerializerPluginConfiguration) WebModulePluginConfiguration(org.bimserver.models.store.WebModulePluginConfiguration) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SInternalServicePluginConfiguration(org.bimserver.interfaces.objects.SInternalServicePluginConfiguration) WebModulePlugin(org.bimserver.plugins.web.WebModulePlugin) PluginBundleVersion(org.bimserver.models.store.PluginBundleVersion) SPluginBundleVersion(org.bimserver.interfaces.objects.SPluginBundleVersion) RealtimeReflectorFactoryBuilder(org.bimserver.shared.reflector.RealtimeReflectorFactoryBuilder) Condition(org.bimserver.database.query.conditions.Condition) AttributeCondition(org.bimserver.database.query.conditions.AttributeCondition) Path(java.nio.file.Path) BerkeleyKeyValueStore(org.bimserver.database.berkeley.BerkeleyKeyValueStore) SerializerFactory(org.bimserver.serializers.SerializerFactory) PluginContext(org.bimserver.plugins.PluginContext) MailSystem(org.bimserver.mail.MailSystem) ServerState(org.bimserver.models.store.ServerState) RenderEnginePoolFactory(org.bimserver.renderengine.RenderEnginePoolFactory) NoPoolingRenderEnginePoolFactory(org.bimserver.renderengine.NoPoolingRenderEnginePoolFactory) NewDiskCacheManager(org.bimserver.cache.NewDiskCacheManager) ServiceException(org.bimserver.shared.exceptions.ServiceException) IOException(java.io.IOException) ServerException(org.bimserver.shared.exceptions.ServerException) PluginException(org.bimserver.shared.exceptions.PluginException) InconsistentModelsException(org.bimserver.database.migrations.InconsistentModelsException) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) DatabaseRestartRequiredException(org.bimserver.database.DatabaseRestartRequiredException) DatabaseInitException(org.bimserver.database.berkeley.DatabaseInitException) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SInternalServicePluginConfiguration(org.bimserver.interfaces.objects.SInternalServicePluginConfiguration) Parameter(org.bimserver.models.store.Parameter) NewDiskCacheManager(org.bimserver.cache.NewDiskCacheManager) DiskCacheManager(org.bimserver.cache.DiskCacheManager) ModelCheckerPlugin(org.bimserver.plugins.modelchecker.ModelCheckerPlugin) ServicePlugin(org.bimserver.plugins.services.ServicePlugin) WebModulePlugin(org.bimserver.plugins.web.WebModulePlugin) Plugin(org.bimserver.plugins.Plugin)

Example 2 with ServicePlugin

use of org.bimserver.plugins.services.ServicePlugin in project BIMserver by opensourceBIM.

the class SerializerFactory method getAllServicePluginDescriptors.

public List<SPluginDescriptor> getAllServicePluginDescriptors() {
    List<SPluginDescriptor> descriptors = new ArrayList<SPluginDescriptor>();
    for (ServicePlugin servicePlugin : pluginManager.getAllServicePlugins(true).values()) {
        SPluginDescriptor descriptor = new SPluginDescriptor();
        descriptor.setPluginClassName(servicePlugin.getClass().getName());
        descriptors.add(descriptor);
    }
    return descriptors;
}
Also used : ServicePlugin(org.bimserver.plugins.services.ServicePlugin) SPluginDescriptor(org.bimserver.interfaces.objects.SPluginDescriptor) ArrayList(java.util.ArrayList)

Example 3 with ServicePlugin

use of org.bimserver.plugins.services.ServicePlugin in project BIMserver by opensourceBIM.

the class PluginServiceImpl method setPluginSettings.

@Override
public void setPluginSettings(Long poid, SObjectType settings) throws ServerException, UserException {
    DatabaseSession session = getBimServer().getDatabase().createSession();
    try {
        ObjectType convertedSettings = getBimServer().getSConverter().convertFromSObject(settings, session);
        SetPluginSettingsDatabaseAction action = new SetPluginSettingsDatabaseAction(session, getInternalAccessMethod(), poid, convertedSettings);
        session.executeAndCommitAction(action);
    } catch (Exception e) {
        handleException(e);
    } finally {
        session.close();
    }
    session = getBimServer().getDatabase().createSession();
    try {
        PluginConfiguration pluginConfiguration = session.get(StorePackage.eINSTANCE.getPluginConfiguration(), poid, OldQuery.getDefault());
        if (pluginConfiguration instanceof InternalServicePluginConfiguration) {
            ServicePlugin servicePlugin = getBimServer().getPluginManager().getServicePlugin(pluginConfiguration.getPluginDescriptor().getPluginClassName(), true);
            SInternalServicePluginConfiguration sInternalService = (SInternalServicePluginConfiguration) getBimServer().getSConverter().convertToSObject(pluginConfiguration);
            servicePlugin.unregister(sInternalService);
            servicePlugin.register(getAuthorization().getUoid(), sInternalService, new org.bimserver.plugins.PluginConfiguration(settings));
        }
    } catch (BimserverDatabaseException e) {
        handleException(e);
    } finally {
        session.close();
    }
}
Also used : SObjectType(org.bimserver.interfaces.objects.SObjectType) ObjectType(org.bimserver.models.store.ObjectType) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ServicePlugin(org.bimserver.plugins.services.ServicePlugin) SetPluginSettingsDatabaseAction(org.bimserver.database.actions.SetPluginSettingsDatabaseAction) DatabaseSession(org.bimserver.database.DatabaseSession) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SInternalServicePluginConfiguration(org.bimserver.interfaces.objects.SInternalServicePluginConfiguration) SRenderEnginePluginConfiguration(org.bimserver.interfaces.objects.SRenderEnginePluginConfiguration) SObjectIDMPluginConfiguration(org.bimserver.interfaces.objects.SObjectIDMPluginConfiguration) PluginConfiguration(org.bimserver.models.store.PluginConfiguration) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) SQueryEnginePluginConfiguration(org.bimserver.interfaces.objects.SQueryEnginePluginConfiguration) SerializerPluginConfiguration(org.bimserver.models.store.SerializerPluginConfiguration) ModelComparePluginConfiguration(org.bimserver.models.store.ModelComparePluginConfiguration) QueryEnginePluginConfiguration(org.bimserver.models.store.QueryEnginePluginConfiguration) WebModulePluginConfiguration(org.bimserver.models.store.WebModulePluginConfiguration) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SInternalServicePluginConfiguration(org.bimserver.interfaces.objects.SInternalServicePluginConfiguration) DeserializerPluginConfiguration(org.bimserver.models.store.DeserializerPluginConfiguration) ModelMergerPluginConfiguration(org.bimserver.models.store.ModelMergerPluginConfiguration) SModelComparePluginConfiguration(org.bimserver.interfaces.objects.SModelComparePluginConfiguration) SWebModulePluginConfiguration(org.bimserver.interfaces.objects.SWebModulePluginConfiguration) SSerializerPluginConfiguration(org.bimserver.interfaces.objects.SSerializerPluginConfiguration) RenderEnginePluginConfiguration(org.bimserver.models.store.RenderEnginePluginConfiguration) SModelMergerPluginConfiguration(org.bimserver.interfaces.objects.SModelMergerPluginConfiguration) SInternalServicePluginConfiguration(org.bimserver.interfaces.objects.SInternalServicePluginConfiguration) IOException(java.io.IOException) ServerException(org.bimserver.shared.exceptions.ServerException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) UserException(org.bimserver.shared.exceptions.UserException)

Example 4 with ServicePlugin

use of org.bimserver.plugins.services.ServicePlugin in project BIMserver by opensourceBIM.

the class ServiceRunnerServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (request.getRequestURI().endsWith("/servicelist")) {
        processServiceList(request, response);
        return;
    }
    String token = null;
    if (request.getHeader("Authorization") != null) {
        String a = request.getHeader("Authorization");
        if (a.startsWith("Bearer")) {
            token = a.substring(7);
        }
    }
    if (token == null) {
        token = request.getHeader("Token");
    }
    LOGGER.info("Token: " + token);
    String serviceName = request.getHeader("ServiceName");
    if (serviceName == null) {
        serviceName = request.getRequestURI();
        if (serviceName.startsWith("/services/")) {
            serviceName = serviceName.substring(10);
        }
    }
    LOGGER.info("ServiceName: " + serviceName);
    long serviceOid = Long.parseLong(serviceName);
    String inputType = request.getHeader("Input-Type");
    LOGGER.info("Input-Type: " + inputType);
    try (DatabaseSession session = getBimServer().getDatabase().createSession()) {
        Authorization authorization = Authorization.fromToken(getBimServer().getEncryptionKey(), token);
        User user = session.get(authorization.getUoid(), OldQuery.getDefault());
        if (user == null) {
            LOGGER.error("Service \"" + serviceName + "\" not found for this user");
            throw new UserException("No user found with uoid " + authorization.getUoid());
        }
        if (user.getState() == ObjectState.DELETED) {
            LOGGER.error("User has been deleted");
            throw new UserException("User has been deleted");
        }
        InternalServicePluginConfiguration foundService = null;
        UserSettings userSettings = user.getUserSettings();
        for (InternalServicePluginConfiguration internalServicePluginConfiguration : userSettings.getServices()) {
            if (internalServicePluginConfiguration.getOid() == serviceOid) {
                foundService = internalServicePluginConfiguration;
                break;
            }
        }
        if (foundService == null) {
            LOGGER.info("Service \"" + serviceName + "\" not found for this user");
            throw new ServletException("Service \"" + serviceName + "\" not found for this user");
        }
        PluginDescriptor pluginDescriptor = foundService.getPluginDescriptor();
        ServicePlugin servicePlugin = getBimServer().getPluginManager().getServicePlugin(pluginDescriptor.getPluginClassName(), true);
        if (servicePlugin instanceof BimBotsServiceInterface) {
            LOGGER.info("Found service " + servicePlugin);
            BimBotsServiceInterface bimBotsServiceInterface = (BimBotsServiceInterface) servicePlugin;
            try {
                if (getBimServer().getServerSettingsCache().getServerSettings().isStoreServiceRuns()) {
                    LOGGER.info("Storing intermediate results");
                    // When we store service runs, we can just use the streaming deserializer to stream directly to the database, after that we'll trigger the actual service
                    // Create or find project and link user and service to project
                    // Checkin stream into project
                    // Trigger service
                    ServiceInterface serviceInterface = getBimServer().getServiceFactory().get(authorization, AccessMethod.INTERNAL).get(ServiceInterface.class);
                    SProject project = serviceInterface.addProject("tmp-" + new Random().nextInt(), "ifc2x3tc1");
                    SDeserializerPluginConfiguration deserializer = serviceInterface.getSuggestedDeserializerForExtension("ifc", project.getOid());
                    if (deserializer == null) {
                        throw new BimBotsException("No deserializer found");
                    }
                    serviceInterface.checkin(project.getOid(), "Auto checkin", deserializer.getOid(), -1L, "s", new DataHandler(new InputStreamDataSource(request.getInputStream())), false, true);
                    project = serviceInterface.getProjectByPoid(project.getOid());
                    PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData(project.getSchema());
                    IfcModelInterface model = new BasicIfcModel(packageMetaData, null);
                    try {
                        Revision revision = session.get(project.getLastRevisionId(), OldQuery.getDefault());
                        session.getMap(model, new OldQuery(packageMetaData, project.getId(), revision.getId(), revision.getOid(), null, Deep.NO));
                    } catch (BimserverDatabaseException e) {
                        e.printStackTrace();
                    }
                    BimServerBimBotsInput input = new BimServerBimBotsInput(getBimServer(), authorization.getUoid(), null, null, model);
                    BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, getBimServer().getSConverter().convertToSObject(foundService.getSettings()));
                    SExtendedData extendedData = new SExtendedData();
                    SFile file = new SFile();
                    file.setData(output.getData());
                    file.setFilename(output.getContentDisposition());
                    file.setMime(output.getContentType());
                    file.setSize(output.getData().length);
                    Long fileId = serviceInterface.uploadFile(file);
                    extendedData.setFileId(fileId);
                    extendedData.setTitle(output.getTitle());
                    SExtendedDataSchema extendedDataSchema = null;
                    try {
                        extendedDataSchema = serviceInterface.getExtendedDataSchemaByName(output.getSchemaName());
                    } catch (UserException e) {
                        extendedDataSchema = new SExtendedDataSchema();
                        extendedDataSchema.setContentType(output.getContentType());
                        extendedDataSchema.setName(output.getSchemaName());
                        serviceInterface.addExtendedDataSchema(extendedDataSchema);
                    }
                    extendedData.setSchemaId(extendedDataSchema.getOid());
                    serviceInterface.addExtendedDataToRevision(project.getLastRevisionId(), extendedData);
                    response.setHeader("Output-Type", output.getSchemaName());
                    response.setHeader("Data-Title", output.getTitle());
                    response.setHeader("Data-Identifier", "" + project.getOid());
                    response.setHeader("Content-Type", output.getContentType());
                    response.setHeader("Content-Disposition", output.getContentDisposition());
                    response.getOutputStream().write(output.getData());
                } else {
                    // When we don't store the service runs, there is no other way than to just use the old deserializer and run the service from the EMF model
                    LOGGER.info("NOT Storing intermediate results");
                    DeserializerPlugin deserializerPlugin = getBimServer().getPluginManager().getFirstDeserializer("ifc", Schema.IFC2X3TC1, true);
                    if (deserializerPlugin == null) {
                        throw new BimBotsException("No deserializer plugin found");
                    }
                    byte[] data = IOUtils.toByteArray(request.getInputStream());
                    SchemaName schema = SchemaName.valueOf(inputType);
                    Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration());
                    PackageMetaData packageMetaData = getBimServer().getMetaDataManager().getPackageMetaData("ifc2x3tc1");
                    deserializer.init(packageMetaData);
                    IfcModelInterface model = deserializer.read(new ByteArrayInputStream(data), schema.name(), data.length, null);
                    BimServerBimBotsInput input = new BimServerBimBotsInput(getBimServer(), authorization.getUoid(), schema, data, model);
                    BimBotsOutput output = bimBotsServiceInterface.runBimBot(input, getBimServer().getSConverter().convertToSObject(foundService.getSettings()));
                    response.setHeader("Output-Type", output.getSchemaName());
                    response.setHeader("Data-Title", output.getTitle());
                    response.setHeader("Content-Type", output.getContentType());
                    response.setHeader("Content-Disposition", output.getContentDisposition());
                    response.getOutputStream().write(output.getData());
                }
            } catch (BimBotsException e) {
                LOGGER.error("", e);
            } catch (DeserializeException e) {
                LOGGER.error("", e);
            } catch (PluginException e) {
                LOGGER.error("", e);
            } catch (ServerException e) {
                LOGGER.error("", e);
            }
        } else {
            throw new ServletException("Service \"" + serviceName + "\" does not implement the BimBotsServiceInterface");
        }
    } catch (AuthenticationException e) {
        LOGGER.error("", e);
    } catch (BimserverDatabaseException e) {
        LOGGER.error("", e);
    } catch (UserException e) {
        LOGGER.error("", e);
    }
}
Also used : ServicePlugin(org.bimserver.plugins.services.ServicePlugin) User(org.bimserver.models.store.User) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) DatabaseSession(org.bimserver.database.DatabaseSession) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) IfcModelInterface(org.bimserver.emf.IfcModelInterface) DataHandler(javax.activation.DataHandler) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) SProject(org.bimserver.interfaces.objects.SProject) SExtendedDataSchema(org.bimserver.interfaces.objects.SExtendedDataSchema) Authorization(org.bimserver.webservices.authorization.Authorization) ServletException(javax.servlet.ServletException) InputStreamDataSource(org.bimserver.utils.InputStreamDataSource) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) Random(java.util.Random) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) ServiceInterface(org.bimserver.shared.interfaces.ServiceInterface) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) PluginConfiguration(org.bimserver.plugins.PluginConfiguration) UserException(org.bimserver.shared.exceptions.UserException) SFile(org.bimserver.interfaces.objects.SFile) ServerException(org.bimserver.shared.exceptions.ServerException) UserSettings(org.bimserver.models.store.UserSettings) PackageMetaData(org.bimserver.emf.PackageMetaData) PluginException(org.bimserver.shared.exceptions.PluginException) DeserializerPlugin(org.bimserver.plugins.deserializers.DeserializerPlugin) BimBotsException(org.bimserver.bimbots.BimBotsException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) BasicIfcModel(org.bimserver.ifc.BasicIfcModel) BimServerBimBotsInput(org.bimserver.bimbots.BimServerBimBotsInput) OldQuery(org.bimserver.database.OldQuery) PluginDescriptor(org.bimserver.models.store.PluginDescriptor) Revision(org.bimserver.models.store.Revision) SExtendedData(org.bimserver.interfaces.objects.SExtendedData) ByteArrayInputStream(java.io.ByteArrayInputStream) Deserializer(org.bimserver.plugins.deserializers.Deserializer) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) BimBotsOutput(org.bimserver.bimbots.BimBotsOutput) SchemaName(org.bimserver.plugins.SchemaName)

Example 5 with ServicePlugin

use of org.bimserver.plugins.services.ServicePlugin in project BIMserver by opensourceBIM.

the class ServiceRunnerServlet method processServiceList.

private void processServiceList(HttpServletRequest request, HttpServletResponse response) {
    BimDatabase database = getBimServer().getDatabase();
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode result = mapper.createObjectNode();
    ArrayNode array = mapper.createArrayNode();
    result.set("services", array);
    try (DatabaseSession session = database.createSession()) {
        for (PluginDescriptor pluginDescriptor : session.getAllOfType(StorePackage.eINSTANCE.getPluginDescriptor(), PluginDescriptor.class, OldQuery.getDefault())) {
            if (pluginDescriptor.getPluginInterfaceClassName().equals(ServicePlugin.class.getName())) {
                ServicePlugin servicePlugin = getBimServer().getPluginManager().getServicePlugin(pluginDescriptor.getPluginClassName(), true);
                if (servicePlugin instanceof BimBotsServiceInterface) {
                    try {
                        BimBotsServiceInterface bimBotsServiceInterface = (BimBotsServiceInterface) servicePlugin;
                        ObjectNode descriptorJson = mapper.createObjectNode();
                        descriptorJson.put("id", pluginDescriptor.getOid());
                        descriptorJson.put("name", pluginDescriptor.getName());
                        descriptorJson.put("description", pluginDescriptor.getDescription());
                        descriptorJson.put("provider", getBimServer().getServerSettingsCache().getServerSettings().getName());
                        descriptorJson.put("providerIcon", getBimServer().getServerSettingsCache().getServerSettings().getIcon());
                        ArrayNode inputs = mapper.createArrayNode();
                        ArrayNode outputs = mapper.createArrayNode();
                        for (String schemaName : bimBotsServiceInterface.getAvailableInputs()) {
                            inputs.add(schemaName);
                        }
                        for (String schemaName : bimBotsServiceInterface.getAvailableOutputs()) {
                            outputs.add(schemaName);
                        }
                        descriptorJson.set("inputs", inputs);
                        descriptorJson.set("outputs", outputs);
                        ObjectNode oauth = mapper.createObjectNode();
                        oauth.put("authorizationUrl", getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/oauth/authorize");
                        oauth.put("registerUrl", getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/oauth/register");
                        oauth.put("tokenUrl", getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/oauth/access");
                        descriptorJson.set("oauth", oauth);
                        descriptorJson.put("resourceUrl", getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/services");
                        array.add(descriptorJson);
                    } catch (Exception e) {
                        LOGGER.error("", e);
                    }
                }
            }
        }
        response.setContentType("application/json");
        response.getOutputStream().write(mapper.writeValueAsBytes(result));
    } catch (BimserverDatabaseException e) {
        LOGGER.error("", e);
    } catch (JsonProcessingException e) {
        LOGGER.error("", e);
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}
Also used : ServicePlugin(org.bimserver.plugins.services.ServicePlugin) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DatabaseSession(org.bimserver.database.DatabaseSession) IOException(java.io.IOException) BimBotsServiceInterface(org.bimserver.bimbots.BimBotsServiceInterface) PluginException(org.bimserver.shared.exceptions.PluginException) ServletException(javax.servlet.ServletException) UserException(org.bimserver.shared.exceptions.UserException) BimBotsException(org.bimserver.bimbots.BimBotsException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) AuthenticationException(org.bimserver.webservices.authorization.AuthenticationException) ServerException(org.bimserver.shared.exceptions.ServerException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) PluginDescriptor(org.bimserver.models.store.PluginDescriptor) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) BimDatabase(org.bimserver.database.BimDatabase) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

ServicePlugin (org.bimserver.plugins.services.ServicePlugin)6 DatabaseSession (org.bimserver.database.DatabaseSession)4 IOException (java.io.IOException)3 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)3 SInternalServicePluginConfiguration (org.bimserver.interfaces.objects.SInternalServicePluginConfiguration)3 InternalServicePluginConfiguration (org.bimserver.models.store.InternalServicePluginConfiguration)3 PluginDescriptor (org.bimserver.models.store.PluginDescriptor)3 ServerException (org.bimserver.shared.exceptions.ServerException)3 UserException (org.bimserver.shared.exceptions.UserException)3 ArrayList (java.util.ArrayList)2 ServletException (javax.servlet.ServletException)2 BimBotsException (org.bimserver.bimbots.BimBotsException)2 BimBotsServiceInterface (org.bimserver.bimbots.BimBotsServiceInterface)2 BimDatabase (org.bimserver.database.BimDatabase)2 IfcModelInterface (org.bimserver.emf.IfcModelInterface)2 SDeserializerPluginConfiguration (org.bimserver.interfaces.objects.SDeserializerPluginConfiguration)2 DeserializeException (org.bimserver.plugins.deserializers.DeserializeException)2 PluginException (org.bimserver.shared.exceptions.PluginException)2 AuthenticationException (org.bimserver.webservices.authorization.AuthenticationException)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1