Search in sources :

Example 1 with PostCommitAction

use of org.bimserver.database.PostCommitAction in project BIMserver by opensourceBIM.

the class AddExtendedDataToProjectDatabaseAction method execute.

@Override
public Long execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    super.execute();
    User actingUser = getUserByUoid(authorization.getUoid());
    Project project = getProjectByPoid(poid);
    if (project == null) {
        throw new UserException("Project with poid " + poid + " not found");
    }
    project.getExtendedData().add(getIdEObject());
    getDatabaseSession().store(project);
    final ExtendedDataAddedToProject extendedDataAddedToProject = getDatabaseSession().create(ExtendedDataAddedToProject.class);
    extendedDataAddedToProject.setAccessMethod(getAccessMethod());
    extendedDataAddedToProject.setDate(new Date());
    extendedDataAddedToProject.setExecutor(actingUser);
    extendedDataAddedToProject.setExtendedData(getIdEObject());
    extendedDataAddedToProject.setProject(project);
    getDatabaseSession().addPostCommitAction(new PostCommitAction() {

        @Override
        public void execute() throws UserException {
            bimServer.getNotificationsManager().notify(new SConverter().convertToSObject(extendedDataAddedToProject));
        }
    });
    return null;
}
Also used : ExtendedDataAddedToProject(org.bimserver.models.log.ExtendedDataAddedToProject) Project(org.bimserver.models.store.Project) User(org.bimserver.models.store.User) ExtendedDataAddedToProject(org.bimserver.models.log.ExtendedDataAddedToProject) SConverter(org.bimserver.interfaces.SConverter) PostCommitAction(org.bimserver.database.PostCommitAction) UserException(org.bimserver.shared.exceptions.UserException) Date(java.util.Date)

Example 2 with PostCommitAction

use of org.bimserver.database.PostCommitAction in project BIMserver by opensourceBIM.

the class AddUserDatabaseAction method execute.

public User execute() throws UserException, BimserverDatabaseException, BimserverLockConflictException {
    String trimmedUserName = username.trim().toLowerCase();
    String trimmedName = name.trim();
    if (userType == UserType.SYSTEM && !createSystemUser) {
        throw new UserException("Cannot create system users");
    }
    if (selfRegistration && userType == UserType.ADMIN) {
        throw new UserException("Cannot create admin user with self registration");
    }
    if (trimmedUserName.equals("")) {
        throw new UserException("Invalid username");
    }
    if (!MailSystem.isValidEmailAddress(trimmedUserName) && !(trimmedUserName.equals("test") || trimmedUserName.equals("system"))) {
        throw new UserException("Username must be a valid e-mail address");
    }
    if (trimmedName.equals("")) {
        throw new UserException("Invalid name");
    }
    if (getUserByUserName(trimmedUserName) != null) {
        throw new UserException("A user with the username " + trimmedUserName + " already exists");
    }
    User actingUser = null;
    // if (bimServer.getServerSettingsCache() != null && !bimServer.getServerSettingsCache().getServerSettings().isAllowCreateValidatedUser()) {
    // if (authorization != null && !(authorization instanceof SystemAuthorization)) {
    // actingUser = getUserByUoid(authorization.getUoid());
    // if (actingUser == null || actingUser.getUserType() != UserType.SYSTEM) {
    // if (authorization.getUoid() != -1 && actingUser.getUserType() != UserType.ADMIN) {
    // throw new UserException("Only admin users can create other users");
    // }
    // }
    // }
    // }
    final User user = getDatabaseSession().create(User.class);
    if (password != null) {
        byte[] salt = new byte[32];
        secureRandom.nextBytes(salt);
        user.setPasswordHash(new Authenticator().createHash(password, salt));
        user.setPasswordSalt(salt);
    }
    user.setToken(GeneratorUtils.generateToken());
    user.setName(trimmedName);
    user.setUsername(trimmedUserName);
    user.setCreatedOn(new Date());
    user.setCreatedBy(actingUser);
    user.setUserType(userType);
    user.setLastSeen(null);
    final String token = GeneratorUtils.generateToken();
    user.setValidationToken(Hashers.getSha256Hash(token));
    user.setValidationTokenCreated(new Date());
    if (!createSystemUser) {
        final NewUserAdded newUserAdded = getDatabaseSession().create(NewUserAdded.class);
        newUserAdded.setUser(user);
        newUserAdded.setExecutor(actingUser);
        newUserAdded.setDate(new Date());
        newUserAdded.setAccessMethod(getAccessMethod());
        getDatabaseSession().store(newUserAdded);
        getDatabaseSession().addPostCommitAction(new PostCommitAction() {

            @Override
            public void execute() throws UserException {
                bimServer.getNotificationsManager().notify(new NewUserNotification(bimServer, user.getOid()));
            }
        });
        bimServer.updateUserSettings(getDatabaseSession(), user);
    }
    getDatabaseSession().store(user);
    if (bimServer != null && bimServer.getServerSettingsCache() != null) {
        // this is only null on server/database initialization
        final ServerSettings serverSettings = bimServer.getServerSettingsCache().getServerSettings();
        if (serverSettings.isSendConfirmationEmailAfterRegistration()) {
            getDatabaseSession().addPostCommitAction(new PostCommitAction() {

                @Override
                public void execute() throws UserException {
                    String body = null;
                    try {
                        if (MailSystem.isValidEmailAddress(user.getUsername())) {
                            EmailMessage message = bimServer.getMailSystem().createMessage();
                            String emailSenderAddress = serverSettings.getEmailSenderAddress();
                            InternetAddress addressFrom = new InternetAddress(emailSenderAddress);
                            message.setFrom(addressFrom);
                            InternetAddress[] addressTo = new InternetAddress[1];
                            addressTo[0] = new InternetAddress(user.getUsername());
                            message.setRecipients(Message.RecipientType.TO, addressTo);
                            Map<String, Object> context = new HashMap<String, Object>();
                            context.put("name", user.getName());
                            context.put("username", user.getUsername());
                            context.put("siteaddress", serverSettings.getSiteAddress());
                            context.put("validationlink", resetUrl + "&username=" + user.getUsername() + "&uoid=" + user.getOid() + "&validationtoken=" + token + "&address=" + bimServer.getServerSettingsCache().getServerSettings().getSiteAddress());
                            String subject = null;
                            if (selfRegistration) {
                                body = bimServer.getTemplateEngine().process(context, TemplateIdentifier.SELF_REGISTRATION_EMAIL_BODY);
                                subject = bimServer.getTemplateEngine().process(context, TemplateIdentifier.SELF_REGISTRATION_EMAIL_SUBJECT);
                            } else {
                                body = bimServer.getTemplateEngine().process(context, TemplateIdentifier.ADMIN_REGISTRATION_EMAIL_BODY);
                                subject = bimServer.getTemplateEngine().process(context, TemplateIdentifier.ADMIN_REGISTRATION_EMAIL_SUBJECT);
                            }
                            message.setContent(body, "text/html");
                            message.setSubject(subject.trim());
                            LOGGER.info("Sending registration e-mail to " + user.getUsername());
                            message.send();
                        }
                    } catch (Exception e) {
                        LOGGER.error(body);
                        LOGGER.error("", e);
                        throw new UserException(e);
                    }
                }
            });
        }
    }
    return user;
}
Also used : EmailMessage(org.bimserver.mail.EmailMessage) InternetAddress(javax.mail.internet.InternetAddress) User(org.bimserver.models.store.User) PostCommitAction(org.bimserver.database.PostCommitAction) NewUserAdded(org.bimserver.models.log.NewUserAdded) Date(java.util.Date) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) UserException(org.bimserver.shared.exceptions.UserException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ServerSettings(org.bimserver.models.store.ServerSettings) NewUserNotification(org.bimserver.notifications.NewUserNotification) UserException(org.bimserver.shared.exceptions.UserException) HashMap(java.util.HashMap) Map(java.util.Map) Authenticator(org.bimserver.Authenticator)

Example 3 with PostCommitAction

use of org.bimserver.database.PostCommitAction in project BIMserver by opensourceBIM.

the class ChangeUserTypeDatabaseAction method execute.

@Override
public Void execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    User actingUser = getUserByUoid(authorization.getUoid());
    if (actingUser.getUserType() != UserType.ADMIN) {
        throw new UserException("Only admin users can change other user's types");
    }
    User user = getUserByUoid(uoid);
    if (user.getUserType() == UserType.SYSTEM) {
        throw new UserException("Type of system user cannot be changed");
    }
    user.setUserType(UserType.get(userType.getOrdinal()));
    final UserChanged userChanged = getDatabaseSession().create(UserChanged.class);
    userChanged.setAccessMethod(getAccessMethod());
    userChanged.setDate(new Date());
    userChanged.setExecutor(actingUser);
    userChanged.setUser(user);
    getDatabaseSession().addPostCommitAction(new PostCommitAction() {

        @Override
        public void execute() throws UserException {
            bimServer.getNotificationsManager().notify(new SConverter().convertToSObject(userChanged));
        }
    });
    getDatabaseSession().store(user);
    return null;
}
Also used : User(org.bimserver.models.store.User) SConverter(org.bimserver.interfaces.SConverter) PostCommitAction(org.bimserver.database.PostCommitAction) UserException(org.bimserver.shared.exceptions.UserException) Date(java.util.Date) UserChanged(org.bimserver.models.log.UserChanged)

Example 4 with PostCommitAction

use of org.bimserver.database.PostCommitAction in project BIMserver by opensourceBIM.

the class CheckinDatabaseAction method execute.

@Override
public ConcreteRevision execute() throws UserException, BimserverDatabaseException {
    try {
        bimServer.getCheckinsInProgress().put(poid, getActingUid());
        if (fileSize == -1) {
            setProgress("Deserializing IFC file...", -1);
        } else {
            setProgress("Deserializing IFC file...", 0);
        }
        if (getModel().size() == 0) {
            throw new DeserializeException("Cannot checkin empty model");
        }
        authorization.canCheckin(poid);
        project = getProjectByPoid(poid);
        int nrConcreteRevisionsBefore = project.getConcreteRevisions().size();
        User user = getUserByUoid(authorization.getUoid());
        if (project == null) {
            throw new UserException("Project with poid " + poid + " not found");
        }
        if (!authorization.hasRightsOnProjectOrSuperProjects(user, project)) {
            throw new UserException("User has no rights to checkin models to this project");
        }
        if (!MailSystem.isValidEmailAddress(user.getUsername())) {
            throw new UserException("Users must have a valid e-mail address to checkin");
        }
        if (getModel() != null) {
            checkCheckSum(project, getModel());
        }
        long size = 0;
        if (getModel() != null) {
            for (IdEObject idEObject : getModel().getValues()) {
                if (idEObject.eClass().getEAnnotation("hidden") == null) {
                    size++;
                }
            }
            getModel().fixInverseMismatches();
        }
        for (ModelCheckerInstance modelCheckerInstance : project.getModelCheckers()) {
            if (modelCheckerInstance.isValid()) {
                ModelCheckerPlugin modelCheckerPlugin = bimServer.getPluginManager().getModelCheckerPlugin(modelCheckerInstance.getModelCheckerPluginClassName(), true);
                if (modelCheckerPlugin != null) {
                    ModelChecker modelChecker = modelCheckerPlugin.createModelChecker(null);
                    ModelCheckerResult result = modelChecker.check(getModel(), modelCheckerInstance.getCompiled());
                    if (!result.isValid()) {
                        throw new UserException("Model is not valid according to " + modelCheckerInstance.getName());
                    }
                }
            }
        }
        CreateRevisionResult result = createNewConcreteRevision(getDatabaseSession(), size, project, user, comment.trim());
        concreteRevision = result.getConcreteRevision();
        IfcHeader ifcHeader = getModel().getModelMetaData().getIfcHeader();
        if (ifcHeader != null) {
            getDatabaseSession().store(ifcHeader);
            concreteRevision.setIfcHeader(ifcHeader);
        }
        project.getConcreteRevisions().add(concreteRevision);
        if (getModel() != null) {
            concreteRevision.setChecksum(getModel().getModelMetaData().getChecksum());
        }
        final NewRevisionAdded newRevisionAdded = getDatabaseSession().create(NewRevisionAdded.class);
        newRevisionAdded.setDate(new Date());
        newRevisionAdded.setExecutor(user);
        final Revision revision = concreteRevision.getRevisions().get(0);
        if (newServiceId != -1) {
            NewService newService = getDatabaseSession().get(newServiceId, OldQuery.getDefault());
            revision.getServicesLinked().add(newService);
        }
        concreteRevision.setSummary(new SummaryMap(getModel()).toRevisionSummary(getDatabaseSession()));
        // If this revision is being created by an external service, store a link to the service in the revision
        if (authorization instanceof ExplicitRightsAuthorization) {
            ExplicitRightsAuthorization explicitRightsAuthorization = (ExplicitRightsAuthorization) authorization;
            if (explicitRightsAuthorization.getSoid() != -1) {
                Service service = getDatabaseSession().get(explicitRightsAuthorization.getSoid(), OldQuery.getDefault());
                revision.setService(service);
            }
        }
        newRevisionAdded.setRevision(revision);
        newRevisionAdded.setProject(project);
        newRevisionAdded.setAccessMethod(getAccessMethod());
        Revision lastRevision = project.getLastRevision();
        IfcModelInterface ifcModel = null;
        if (merge && lastRevision != null) {
            ifcModel = checkinMerge(lastRevision);
        } else {
            ifcModel = getModel();
        }
        ifcModel.fixOidsFlat(getDatabaseSession());
        if (bimServer.getServerSettingsCache().getServerSettings().isGenerateGeometryOnCheckin()) {
            setProgress("Generating Geometry...", -1);
            UserSettings userSettings = user.getUserSettings();
            RenderEnginePluginConfiguration defaultRenderEngine = userSettings.getDefaultRenderEngine();
            if (defaultRenderEngine == null) {
                throw new UserException("No default render engine has been selected for this user");
            }
            RenderEnginePool pool = bimServer.getRenderEnginePools().getRenderEnginePool(model.getPackageMetaData().getSchema(), defaultRenderEngine.getPluginDescriptor().getPluginClassName(), new PluginConfiguration(defaultRenderEngine.getSettings()));
            GenerateGeometryResult generateGeometry = new GeometryGenerator(bimServer).generateGeometry(pool, bimServer.getPluginManager(), getDatabaseSession(), ifcModel, project.getId(), concreteRevision.getId(), true, geometryCache);
            concreteRevision.setMinBounds(generateGeometry.getMinBoundsAsVector3f());
            concreteRevision.setMaxBounds(generateGeometry.getMaxBoundsAsVector3f());
            for (Revision other : concreteRevision.getRevisions()) {
                other.setHasGeometry(true);
            }
        }
        if (nrConcreteRevisionsBefore != 0 && !merge) {
            // There already was a revision, lets delete it (only when not merging)
            concreteRevision.setClear(true);
        }
        Set<EClass> eClasses = ifcModel.getUsedClasses();
        Map<EClass, Long> startOids = getDatabaseSession().getStartOids();
        if (startOids == null) {
            throw new BimserverDatabaseException("No objects changed");
        }
        int s = 0;
        for (EClass eClass : eClasses) {
            if (!DatabaseSession.perRecordVersioning(eClass)) {
                s++;
            }
        }
        ByteBuffer buffer = ByteBuffer.allocate(8 * s);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        for (EClass eClass : eClasses) {
            long oid = startOids.get(eClass);
            if (!DatabaseSession.perRecordVersioning(eClass)) {
                buffer.putLong(oid);
            }
        }
        concreteRevision.setOidCounters(buffer.array());
        if (ifcModel != null) {
            getDatabaseSession().store(ifcModel.getValues(), project.getId(), concreteRevision.getId());
        }
        getDatabaseSession().addPostCommitAction(new PostCommitAction() {

            @Override
            public void execute() throws UserException {
                bimServer.getCheckinsInProgress().remove(poid);
                bimServer.getNotificationsManager().notify(new NewRevisionNotification(bimServer, project.getOid(), revision.getOid(), authorization));
            }
        });
        getDatabaseSession().store(concreteRevision);
        getDatabaseSession().store(project);
    } catch (Throwable e) {
        if (e instanceof BimserverDatabaseException) {
            throw (BimserverDatabaseException) e;
        }
        if (e instanceof UserException) {
            throw (UserException) e;
        }
        LOGGER.error("", e);
        throw new UserException(e);
    }
    return concreteRevision;
}
Also used : User(org.bimserver.models.store.User) RenderEnginePool(org.bimserver.renderengine.RenderEnginePool) IfcModelInterface(org.bimserver.emf.IfcModelInterface) ModelCheckerResult(org.bimserver.models.store.ModelCheckerResult) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ModelChecker(org.bimserver.plugins.modelchecker.ModelChecker) EClass(org.eclipse.emf.ecore.EClass) ExplicitRightsAuthorization(org.bimserver.webservices.authorization.ExplicitRightsAuthorization) RenderEnginePluginConfiguration(org.bimserver.models.store.RenderEnginePluginConfiguration) PluginConfiguration(org.bimserver.plugins.PluginConfiguration) UserException(org.bimserver.shared.exceptions.UserException) NewRevisionAdded(org.bimserver.models.log.NewRevisionAdded) NewService(org.bimserver.models.store.NewService) ModelCheckerInstance(org.bimserver.models.store.ModelCheckerInstance) ModelCheckerPlugin(org.bimserver.plugins.modelchecker.ModelCheckerPlugin) IdEObject(org.bimserver.emf.IdEObject) UserSettings(org.bimserver.models.store.UserSettings) PostCommitAction(org.bimserver.database.PostCommitAction) GeometryGenerator(org.bimserver.GeometryGenerator) Service(org.bimserver.models.store.Service) NewService(org.bimserver.models.store.NewService) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) IfcHeader(org.bimserver.models.store.IfcHeader) ByteBuffer(java.nio.ByteBuffer) Date(java.util.Date) RenderEnginePluginConfiguration(org.bimserver.models.store.RenderEnginePluginConfiguration) NewRevisionNotification(org.bimserver.notifications.NewRevisionNotification) Revision(org.bimserver.models.store.Revision) ConcreteRevision(org.bimserver.models.store.ConcreteRevision) SummaryMap(org.bimserver.SummaryMap) GenerateGeometryResult(org.bimserver.GenerateGeometryResult)

Example 5 with PostCommitAction

use of org.bimserver.database.PostCommitAction in project BIMserver by opensourceBIM.

the class DeleteProjectDatabaseAction method execute.

@Override
public Boolean execute() throws UserException, BimserverDatabaseException, BimserverLockConflictException {
    User actingUser = getUserByUoid(authorization.getUoid());
    final Project project = getProjectByPoid(poid);
    if (actingUser.getUserType() == UserType.ADMIN || (actingUser.getHasRightsOn().contains(project) && bimServer.getServerSettingsCache().getServerSettings().isAllowUsersToCreateTopLevelProjects())) {
        delete(project);
        final ProjectDeleted projectDeleted = getDatabaseSession().create(ProjectDeleted.class);
        projectDeleted.setAccessMethod(getAccessMethod());
        projectDeleted.setDate(new Date());
        projectDeleted.setExecutor(actingUser);
        projectDeleted.setProject(project);
        getDatabaseSession().addPostCommitAction(new PostCommitAction() {

            @Override
            public void execute() throws UserException {
                bimServer.getNotificationsManager().notify(new SConverter().convertToSObject(projectDeleted));
            }
        });
        getDatabaseSession().store(project);
        return true;
    } else {
        throw new UserException("No rights to delete this project");
    }
}
Also used : Project(org.bimserver.models.store.Project) User(org.bimserver.models.store.User) SConverter(org.bimserver.interfaces.SConverter) PostCommitAction(org.bimserver.database.PostCommitAction) UserException(org.bimserver.shared.exceptions.UserException) ProjectDeleted(org.bimserver.models.log.ProjectDeleted) Date(java.util.Date)

Aggregations

PostCommitAction (org.bimserver.database.PostCommitAction)19 UserException (org.bimserver.shared.exceptions.UserException)19 Date (java.util.Date)18 User (org.bimserver.models.store.User)18 SConverter (org.bimserver.interfaces.SConverter)13 Project (org.bimserver.models.store.Project)10 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)5 Revision (org.bimserver.models.store.Revision)5 HashMap (java.util.HashMap)4 GenerateGeometryResult (org.bimserver.GenerateGeometryResult)3 SummaryMap (org.bimserver.SummaryMap)3 NewRevisionAdded (org.bimserver.models.log.NewRevisionAdded)3 ConcreteRevision (org.bimserver.models.store.ConcreteRevision)3 ByteBuffer (java.nio.ByteBuffer)2 Map (java.util.Map)2 InternetAddress (javax.mail.internet.InternetAddress)2 Authenticator (org.bimserver.Authenticator)2 BimserverLockConflictException (org.bimserver.database.BimserverLockConflictException)2 GeometryGenerationReport (org.bimserver.geometry.GeometryGenerationReport)2 StreamingGeometryGenerator (org.bimserver.geometry.StreamingGeometryGenerator)2