Search in sources :

Example 1 with ServiceException

use of org.bimserver.shared.exceptions.ServiceException in project BIMserver by opensourceBIM.

the class JsonHandler method handleThrowable.

private void handleThrowable(JsonGenerator writer, Throwable throwable) {
    if (!(throwable instanceof ServiceException)) {
        LoggerFactory.getLogger(JsonHandler.class).error("", throwable);
    } else {
        if (LoggerFactory.getLogger(JsonHandler.class).isDebugEnabled()) {
            LoggerFactory.getLogger(JsonHandler.class).debug("", throwable);
        }
    }
    try {
        writer.writeStartObject();
        writer.writeFieldName("exception");
        writer.writeStartObject();
        writer.writeFieldName("__type");
        writer.writeString(throwable.getClass().getSimpleName());
        writer.writeFieldName("message");
        writer.writeString(throwable.getMessage() == null ? throwable.toString() : throwable.getMessage());
        if (throwable instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) throwable;
            if (serviceException.getErrorCode() != null) {
                writer.writeFieldName("errorType");
                writer.writeString(serviceException.getErrorCode().getClass().getSimpleName());
                writer.writeFieldName("errorCode");
                writer.writeNumber(serviceException.getErrorCode().getCode());
            }
        }
        writer.writeEndObject();
        writer.writeEndObject();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}
Also used : ServiceException(org.bimserver.shared.exceptions.ServiceException) IOException(java.io.IOException)

Example 2 with ServiceException

use of org.bimserver.shared.exceptions.ServiceException in project BIMserver by opensourceBIM.

the class BimServerImporter method start.

public void start() {
    try (BimServerClientFactory factory = new JsonBimServerClientFactory(bimServer.getMetaDataManager(), address)) {
        LOGGER.info("Importing...");
        remoteClient = factory.create(new UsernamePasswordAuthenticationInfo(username, password));
        final BimDatabase database = bimServer.getDatabase();
        DatabaseSession databaseSession = database.createSession(OperationType.POSSIBLY_WRITE);
        try {
            LOGGER.info("Users...");
            for (SUser user : remoteClient.getServiceInterface().getAllUsers()) {
                createUser(databaseSession, user.getOid());
            }
            LOGGER.info("Projects...");
            for (SProject project : remoteClient.getServiceInterface().getAllProjects(false, false)) {
                createProject(databaseSession, project.getOid());
            }
            LOGGER.info("Done");
            databaseSession.commit();
        } catch (BimserverDatabaseException e) {
            LOGGER.error("", e);
        } finally {
            databaseSession.close();
        }
        final BimServerClientInterface client = bimServer.getBimServerClientFactory().create(new UsernamePasswordAuthenticationInfo(username, password));
        // for (SRenderEnginePluginConfiguration renderEnginePluginConfiguration : client.getPluginInterface().getAllRenderEngines(true)) {
        // if (renderEnginePluginConfiguration.getName().equals("IFC Engine DLL")) {
        // client.getPluginInterface().setDefaultRenderEngine(renderEnginePluginConfiguration.getOid());
        // }
        // }
        Path incoming = Paths.get(path);
        final Map<GregorianCalendar, Key> comments = new TreeMap<>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        for (SProject project : remoteClient.getServiceInterface().getAllProjects(false, false)) {
            for (SRevision revision : remoteClient.getServiceInterface().getAllRevisionsOfProject(project.getOid())) {
                GregorianCalendar gregorianCalendar = new GregorianCalendar();
                gregorianCalendar.setTime(revision.getDate());
                if (!revision.getComment().startsWith("generated for")) {
                    User user = users.get(revision.getUserId());
                    Path userFolder = incoming.resolve(user.getUsername());
                    boolean found = false;
                    for (Path file : PathUtils.list(userFolder)) {
                        if (file.getFileName().toString().endsWith(revision.getComment())) {
                            String dateStr = file.getFileName().toString().substring(0, 19);
                            Date parse = dateFormat.parse(dateStr);
                            GregorianCalendar fileDate = new GregorianCalendar();
                            fileDate.setTime(parse);
                            long millisDiff = Math.abs(fileDate.getTimeInMillis() - revision.getDate().getTime());
                            if (millisDiff > 1000 * 60 * 120) {
                                // 120 minutes
                                continue;
                            }
                            if (revision.getOid() == project.getLastRevisionId()) {
                                comments.put(gregorianCalendar, new Key(file, project.getOid(), revision.getComment(), revision.getDate(), revision.getUserId()));
                            }
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        LOGGER.info("Not found: " + revision.getComment());
                    }
                }
            }
        }
        ExecutorService executorService = new ThreadPoolExecutor(1, 1, 1, TimeUnit.DAYS, new ArrayBlockingQueue<Runnable>(1000));
        for (final GregorianCalendar gregorianCalendar : comments.keySet()) {
            executorService.submit(new Runnable() {

                @Override
                public void run() {
                    Key key = comments.get(gregorianCalendar);
                    LOGGER.info("Checking in: " + key.file.getFileName().toString() + " " + Formatters.bytesToString(key.file.toFile().length()));
                    Project sProject = projects.get(key.poid);
                    try {
                        SDeserializerPluginConfiguration desserializer = client.getServiceInterface().getSuggestedDeserializerForExtension("ifc", sProject.getOid());
                        client.checkinSync(sProject.getOid(), key.comment, desserializer.getOid(), false, key.file);
                        SProject updatedProject = client.getServiceInterface().getProjectByPoid(sProject.getOid());
                        DatabaseSession databaseSession = database.createSession(OperationType.POSSIBLY_WRITE);
                        try {
                            LOGGER.info("Done");
                            Project project = databaseSession.get(updatedProject.getOid(), OldQuery.getDefault());
                            Revision revision = project.getLastRevision();
                            User user = (User) databaseSession.get(users.get(key.userId).getOid(), OldQuery.getDefault());
                            for (Revision otherRevision : revision.getConcreteRevisions().get(0).getRevisions()) {
                                otherRevision.load();
                                otherRevision.setDate(key.date);
                                otherRevision.setComment(otherRevision.getComment().replace("Administrator", user.getName()));
                                databaseSession.store(otherRevision);
                            }
                            DateFormat m = new SimpleDateFormat("dd-MM-yyyy");
                            LOGGER.info("Setting date to " + m.format(key.date));
                            revision.setUser(user);
                            revision.setDate(key.date);
                            databaseSession.store(revision);
                            databaseSession.commit();
                        } catch (BimserverDatabaseException | ServiceException e) {
                            LOGGER.error("", e);
                        } finally {
                            databaseSession.close();
                        }
                    } catch (IOException | UserException | ServerException | PublicInterfaceNotFoundException e) {
                        LOGGER.error("", e);
                    }
                }
            });
        }
        executorService.shutdown();
    } catch (ServiceException e) {
        LOGGER.error("", e);
    } catch (ChannelConnectionException e) {
        LOGGER.error("", e);
    } catch (PublicInterfaceNotFoundException e) {
        LOGGER.error("", e);
    } catch (ParseException e) {
        LOGGER.error("", e);
    } catch (IOException e) {
        LOGGER.error("", e);
    } catch (BimServerClientException e1) {
        LOGGER.error("", e1);
    } catch (Exception e2) {
        LOGGER.error("", e2);
    }
}
Also used : User(org.bimserver.models.store.User) SUser(org.bimserver.interfaces.objects.SUser) SDeserializerPluginConfiguration(org.bimserver.interfaces.objects.SDeserializerPluginConfiguration) DatabaseSession(org.bimserver.database.DatabaseSession) UsernamePasswordAuthenticationInfo(org.bimserver.shared.UsernamePasswordAuthenticationInfo) JsonBimServerClientFactory(org.bimserver.client.json.JsonBimServerClientFactory) SUser(org.bimserver.interfaces.objects.SUser) SProject(org.bimserver.interfaces.objects.SProject) JsonBimServerClientFactory(org.bimserver.client.json.JsonBimServerClientFactory) BimServerClientFactory(org.bimserver.shared.BimServerClientFactory) BimServerClientInterface(org.bimserver.plugins.services.BimServerClientInterface) Path(java.nio.file.Path) ChannelConnectionException(org.bimserver.shared.ChannelConnectionException) GregorianCalendar(java.util.GregorianCalendar) IOException(java.io.IOException) TreeMap(java.util.TreeMap) BimServerClientException(org.bimserver.shared.exceptions.BimServerClientException) Date(java.util.Date) ChannelConnectionException(org.bimserver.shared.ChannelConnectionException) ServiceException(org.bimserver.shared.exceptions.ServiceException) ParseException(java.text.ParseException) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) BimServerClientException(org.bimserver.shared.exceptions.BimServerClientException) IOException(java.io.IOException) UserException(org.bimserver.shared.exceptions.UserException) ServerException(org.bimserver.shared.exceptions.ServerException) SRevision(org.bimserver.interfaces.objects.SRevision) Project(org.bimserver.models.store.Project) SProject(org.bimserver.interfaces.objects.SProject) Revision(org.bimserver.models.store.Revision) SRevision(org.bimserver.interfaces.objects.SRevision) ServiceException(org.bimserver.shared.exceptions.ServiceException) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) ExecutorService(java.util.concurrent.ExecutorService) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ParseException(java.text.ParseException) BimDatabase(org.bimserver.database.BimDatabase) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with ServiceException

use of org.bimserver.shared.exceptions.ServiceException in project BIMserver by opensourceBIM.

the class DatabaseSession method commit.

public void commit(ProgressHandler progressHandler) throws BimserverDatabaseException, ServiceException {
    checkOpen();
    if (operationType == OperationType.READ_ONLY) {
        throw new BimserverDatabaseException("Cannot commit READ_ONLY DatabaseSession");
    }
    try {
        if (progressHandler != null) {
            progressHandler.progress(0, objectsToCommit == null ? 0 : objectsToCommit.size());
        }
        int current = 0;
        long writes = 0;
        ByteBuffer keyBuffer = ByteBuffer.wrap(new byte[16]);
        if (objectsToDelete != null) {
            for (RecordIdentifierPlusType recordIdentifier : objectsToDelete) {
                fillKeyBuffer(keyBuffer, recordIdentifier);
                database.getKeyValueStore().storeNoOverwrite(recordIdentifier.getPackageName() + "_" + recordIdentifier.getClassName(), keyBuffer.array(), new byte[] { -1 }, this);
                writes++;
            }
        }
        // This buffer is reused for the values, it's position must be reset at the end of the loop, and the convertObjectToByteArray function is responsible for setting the buffer's position to the end of the (used part of the) buffer
        ByteBuffer reusableBuffer = ByteBuffer.allocate(32768);
        if (objectsToCommit != null) {
            for (IdEObject object : objectsToCommit) {
                if (object.getOid() == -1) {
                    throw new BimserverDatabaseException("Cannot store object with oid -1");
                }
                fillKeyBuffer(keyBuffer, object);
                if (DEVELOPER_DEBUG) {
                    LOGGER.info("Write: " + object.eClass().getName() + " " + "pid=" + object.getPid() + " oid=" + object.getOid() + " rid=" + object.getRid());
                }
                ByteBuffer valueBuffer = convertObjectToByteArray(object, reusableBuffer, getMetaDataManager().getPackageMetaData(object.eClass().getEPackage().getName()));
                int valueBufferPosition = valueBuffer.position();
                processPossibleIndices(keyBuffer, object.getPid(), object.getRid(), object.getOid(), object.eClass(), valueBuffer);
                if (object.eClass().getEAnnotation("nolazyload") == null && !overwriteEnabled) {
                    try {
                        database.getKeyValueStore().storeNoOverwrite(object.eClass().getEPackage().getName() + "_" + object.eClass().getName(), keyBuffer.array(), valueBuffer.array(), 0, valueBufferPosition, this);
                    } catch (BimserverConcurrentModificationDatabaseException e) {
                        throw e;
                    }
                } else {
                    database.getKeyValueStore().store(object.eClass().getEPackage().getName() + "_" + object.eClass().getName(), keyBuffer.array(), valueBuffer.array(), 0, valueBuffer.position(), this);
                }
                if (progressHandler != null) {
                    progressHandler.progress(++current, objectsToCommit.size());
                }
                writes++;
                // bimServerClient may have increased the size of the buffer by creating a new one, we keep using it for other objects
                reusableBuffer = valueBuffer;
                reusableBuffer.position(0);
            }
        }
        if (bimTransaction != null) {
            bimTransaction.commit();
            database.getKeyValueStore().sync();
        }
        database.incrementCommittedWrites(writes);
        if (bimTransaction != null) {
            bimTransaction.incUpdates(writes);
        }
        close();
        if (postCommitActions != null) {
            for (PostCommitAction postCommitAction : postCommitActions) {
                postCommitAction.execute();
            }
            postCommitActions = null;
        }
    } catch (BimserverDatabaseException e) {
        throw e;
    } catch (ServiceException e) {
        throw e;
    }
}
Also used : BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ServiceException(org.bimserver.shared.exceptions.ServiceException) IdEObject(org.bimserver.emf.IdEObject) BimserverConcurrentModificationDatabaseException(org.bimserver.database.berkeley.BimserverConcurrentModificationDatabaseException) ByteBuffer(java.nio.ByteBuffer)

Example 4 with ServiceException

use of org.bimserver.shared.exceptions.ServiceException in project BIMserver by opensourceBIM.

the class BimServer method start.

public void start() throws DatabaseInitException, BimserverDatabaseException, PluginException, DatabaseRestartRequiredException, ServerException {
    try {
        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");
        }
        if (config.getHomeDir() != null) {
            LOGGER.info("Using \"" + config.getHomeDir().toString() + "\" as homedir");
        } else {
            LOGGER.info("Not using a homedir");
        }
        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(OperationType.POSSIBLY_WRITE);
                    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(OperationType.POSSIBLY_WRITE)) {
                        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(OperationType.POSSIBLY_WRITE)) {
                        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(OperationType.POSSIBLY_WRITE)) {
                        ServerSettings serverSettings = getServerSettingsCache().getServerSettings();
                        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;
                        ObjectType settings = null;
                        if (pluginsFound.size() > 0) {
                            pluginDescriptor = pluginsFound.values().iterator().next();
                            settings = pluginDescriptor.getSettings();
                        } else {
                            pluginDescriptor = session.create(PluginDescriptor.class);
                            settings = convertSettings(session, pluginContext.getPlugin().getSystemSettingsDefinition());
                            pluginDescriptor.setSettings(settings);
                        }
                        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()));
                        try {
                            pluginContext.initialize(new org.bimserver.plugins.PluginConfiguration(settings));
                        } catch (PluginException e) {
                            LOGGER.error("", e);
                        }
                        if (pluginDescriptor.getPluginClassName().contentEquals("org.ifcopenshell.IfcOpenShellEnginePlugin")) {
                            if (serverSettings.getDefaultRenderEnginePlugin() == null) {
                                serverSettings.setDefaultRenderEnginePlugin(pluginDescriptor);
                                session.store(serverSettings);
                            }
                        }
                        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) {
                            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(OperationType.POSSIBLY_WRITE);
                    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(OperationType.POSSIBLY_WRITE)) {
                        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(true);
            pluginManager.initAllLoadedPlugins();
        } catch (PluginException e) {
            LOGGER.error("", e);
        }
        serverStartTime = new GregorianCalendar();
        longActionManager = new LongActionManager(this);
        Set<EPackage> packages = new LinkedHashSet<>();
        packages.add(Ifc2x3tc1Package.eINSTANCE);
        packages.add(Ifc4Package.eINSTANCE);
        templateEngine = new TemplateEngine();
        ResourceFetcher resourceFetcher = config.getResourceFetcher();
        if (resourceFetcher.isDirectory("emailtemplates")) {
            templateEngine.init(resourceFetcher.getURL("emailtemplates"));
        } else {
            LOGGER.info("No email templates found");
        }
        Path databaseDir = config.getHomeDir().resolve("database");
        BerkeleyKeyValueStore keyValueStore = new BerkeleyKeyValueStore(databaseDir, config.getBdbEnvironmentProperties());
        geometryAccellerator = new GeometryAccellerator(this);
        schemaConverterManager.registerConverter(new Ifc2x3tc1ToIfc4SchemaConverterFactory());
        schemaConverterManager.registerConverter(new Ifc4ToIfc2x3tc1SchemaConverterFactory());
        authCache = new AuthCache(this);
        pluginSettingsCache = new PluginSettingsCache(this);
        metricsRegistry = new MetricsRegistry();
        Path mavenPath = config.getHomeDir().resolve("maven");
        if (!Files.exists(mavenPath)) {
            Files.createDirectories(mavenPath);
        }
        OldQuery.setPackageMetaDataForDefaultQuery(metaDataManager.getPackageMetaData("store"));
        bimDatabase = new Database(this, packages, keyValueStore, metaDataManager);
        try {
            bimDatabase.init();
        } catch (DatabaseRestartRequiredException e) {
            bimDatabase.close();
            keyValueStore = new BerkeleyKeyValueStore(databaseDir, config.getBdbEnvironmentProperties());
            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(OperationType.POSSIBLY_WRITE)) {
            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();
        serverInfoManager.init(this);
        webModuleManager = new WebModuleManager(this);
        jsonHandler = new JsonHandler(this);
        serializerFactory = new SerializerFactory();
        serverSettingsCache = new ServerSettingsCache(bimDatabase);
        for (String schema : new String[] { "ifc2x3tc1", "ifc4" }) {
            for (String type : new String[] { "geometry", "stdlib" }) {
                try {
                    PackageMetaData packageMetaData = getMetaDataManager().getPackageMetaData(schema);
                    JsonQueryObjectModelConverter jsonQueryObjectModelConverter = new JsonQueryObjectModelConverter(packageMetaData);
                    String queryNameSpace = schema + "-" + type;
                    if (type.contentEquals("stdlib")) {
                        Include objectPlacement = jsonQueryObjectModelConverter.getDefineFromFile(queryNameSpace + ":ObjectPlacement", true);
                        // The sole reason is to make sure this is done once, and then cached
                        objectPlacement.makeDirectRecursive(new HashSet<>());
                    }
                } catch (QueryException e) {
                    LOGGER.error(schema + " " + type, e);
                }
            }
        }
        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"));
        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) GeometryAccellerator(org.bimserver.geometry.accellerator.GeometryAccellerator) DatabaseSession(org.bimserver.database.DatabaseSession) StringType(org.bimserver.models.store.StringType) IfcModelInterface(org.bimserver.emf.IfcModelInterface) ArrayList(java.util.ArrayList) Include(org.bimserver.database.queries.om.Include) 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) PackageMetaData(org.bimserver.emf.PackageMetaData) 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) DatabaseRestartRequiredException(org.bimserver.database.DatabaseRestartRequiredException) Map(java.util.Map) HashMap(java.util.HashMap) SServicesMap(org.bimserver.shared.meta.SServicesMap) InconsistentModelsException(org.bimserver.database.migrations.InconsistentModelsException) ServicePlugin(org.bimserver.plugins.services.ServicePlugin) User(org.bimserver.models.store.User) JsonQueryObjectModelConverter(org.bimserver.database.queries.om.JsonQueryObjectModelConverter) ResourceFetcher(org.bimserver.plugins.ResourceFetcher) ObjectType(org.bimserver.models.store.ObjectType) 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) 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) QueryException(org.bimserver.database.queries.om.QueryException) InconsistentModelsException(org.bimserver.database.migrations.InconsistentModelsException) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) DatabaseRestartRequiredException(org.bimserver.database.DatabaseRestartRequiredException) DatabaseInitException(org.bimserver.database.berkeley.DatabaseInitException) RenderEngineException(org.bimserver.plugins.renderengine.RenderEngineException) QueryException(org.bimserver.database.queries.om.QueryException) InternalServicePluginConfiguration(org.bimserver.models.store.InternalServicePluginConfiguration) SInternalServicePluginConfiguration(org.bimserver.interfaces.objects.SInternalServicePluginConfiguration) Parameter(org.bimserver.models.store.Parameter) PluginSettingsCache(org.bimserver.pluginsettings.PluginSettingsCache) 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 5 with ServiceException

use of org.bimserver.shared.exceptions.ServiceException in project BIMserver by opensourceBIM.

the class OAuthRegistrationServlet method service.

@Override
public void service(HttpServletRequest request, HttpServletResponse httpResponse) throws ServletException, IOException {
    OAuthServerRegistrationRequest oauthRequest = null;
    try {
        oauthRequest = new OAuthServerRegistrationRequest(new JSONHttpServletRequestWrapper(request));
        oauthRequest.discover();
        oauthRequest.getClientUrl();
        oauthRequest.getClientDescription();
        oauthRequest.getRedirectURI();
        try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.POSSIBLY_WRITE)) {
            OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_RedirectUrl(), oauthRequest.getRedirectURI());
            GregorianCalendar now = new GregorianCalendar();
            if (oAuthServer == null) {
                oAuthServer = session.create(OAuthServer.class);
                oAuthServer.setClientName(oauthRequest.getClientName());
                oAuthServer.setClientUrl(oauthRequest.getClientUrl());
                oAuthServer.setClientDescription(oauthRequest.getClientDescription());
                if (oauthRequest.getClientIcon() != null) {
                    try {
                        byte[] icon = NetUtils.getContentAsBytes(new URL(oauthRequest.getClientIcon()), 5000);
                        oAuthServer.setClientIcon(icon);
                    } catch (Exception e) {
                    // 
                    }
                }
                oAuthServer.setRedirectUrl(oauthRequest.getRedirectURI());
                // DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
                GregorianCalendar expires = new GregorianCalendar();
                expires.add(Calendar.YEAR, 1);
                String secret = new MD5Generator().generateValue();
                oAuthServer.setIssuedAt(now.getTime());
                oAuthServer.setExpiresAt(expires.getTime());
                oAuthServer.setClientSecret(secret);
                oAuthServer.setClientId(oauthRequest.getClientName().replace(" ", "").toLowerCase());
                oAuthServer.setIncoming(true);
                session.commit();
            }
            OAuthResponse response = OAuthServerRegistrationResponse.status(HttpServletResponse.SC_OK).setClientId(oAuthServer.getClientId()).setClientSecret(oAuthServer.getClientSecret()).setIssuedAt("" + oAuthServer.getIssuedAt().getTime()).setExpiresIn(oAuthServer.getExpiresAt().getTime() - now.getTimeInMillis()).setParam("message", "OK").buildJSONMessage();
            httpResponse.setStatus(response.getResponseStatus());
            httpResponse.setContentType(response.getHeaders().get("Content-Type"));
            httpResponse.getWriter().write(response.getBody());
        } catch (BimserverDatabaseException e) {
            e.printStackTrace();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    } catch (OAuthProblemException e) {
        OAuthResponse response;
        try {
            response = OAuthServerRegistrationResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
            httpResponse.setStatus(response.getResponseStatus());
            httpResponse.getWriter().write(response.getBody());
        } catch (OAuthSystemException e1) {
            e1.printStackTrace();
        }
    } catch (OAuthSystemException e) {
        e.printStackTrace();
    }
}
Also used : DatabaseSession(org.bimserver.database.DatabaseSession) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) GregorianCalendar(java.util.GregorianCalendar) OAuthServer(org.bimserver.models.store.OAuthServer) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) URL(java.net.URL) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) ServletException(javax.servlet.ServletException) ServiceException(org.bimserver.shared.exceptions.ServiceException) IOException(java.io.IOException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) JSONHttpServletRequestWrapper(org.apache.oltu.oauth2.ext.dynamicreg.server.request.JSONHttpServletRequestWrapper) ServiceException(org.bimserver.shared.exceptions.ServiceException) OAuthServerRegistrationRequest(org.apache.oltu.oauth2.ext.dynamicreg.server.request.OAuthServerRegistrationRequest) MD5Generator(org.apache.oltu.oauth2.as.issuer.MD5Generator)

Aggregations

ServiceException (org.bimserver.shared.exceptions.ServiceException)53 IOException (java.io.IOException)21 PublicInterfaceNotFoundException (org.bimserver.shared.exceptions.PublicInterfaceNotFoundException)21 SProject (org.bimserver.interfaces.objects.SProject)19 DatabaseSession (org.bimserver.database.DatabaseSession)18 BimServerClientInterface (org.bimserver.plugins.services.BimServerClientInterface)17 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)16 User (org.bimserver.models.store.User)13 Project (org.bimserver.models.store.Project)11 BimServerClientException (org.bimserver.shared.exceptions.BimServerClientException)11 UserException (org.bimserver.shared.exceptions.UserException)11 Date (java.util.Date)10 JsonBimServerClientFactory (org.bimserver.client.json.JsonBimServerClientFactory)9 SDeserializerPluginConfiguration (org.bimserver.interfaces.objects.SDeserializerPluginConfiguration)9 ChannelConnectionException (org.bimserver.shared.ChannelConnectionException)9 Path (java.nio.file.Path)8 UsernamePasswordAuthenticationInfo (org.bimserver.shared.UsernamePasswordAuthenticationInfo)8 ServerException (org.bimserver.shared.exceptions.ServerException)8 ArrayList (java.util.ArrayList)6 BimServerClientFactory (org.bimserver.shared.BimServerClientFactory)6