Search in sources :

Example 1 with EmailMessage

use of org.bimserver.mail.EmailMessage in project BIMserver by opensourceBIM.

the class ServiceImpl method sendCompareEmail.

@Override
public void sendCompareEmail(SCompareType sCompareType, Long mcid, Long poid, Long roid1, Long roid2, String address) throws ServerException, UserException {
    requireRealUserAuthentication();
    DatabaseSession session = getBimServer().getDatabase().createSession();
    try {
        SUser currentUser = getCurrentUser(session);
        Revision revision1 = session.get(StorePackage.eINSTANCE.getRevision(), roid1, OldQuery.getDefault());
        Revision revision2 = session.get(StorePackage.eINSTANCE.getRevision(), roid2, OldQuery.getDefault());
        String senderName = currentUser.getName();
        String senderAddress = currentUser.getUsername();
        if (!senderAddress.contains("@") || !senderAddress.contains(".")) {
            senderAddress = getBimServer().getServerSettingsCache().getServerSettings().getEmailSenderAddress();
        }
        EmailMessage message = getBimServer().getMailSystem().createMessage();
        try {
            InternetAddress addressFrom = new InternetAddress(senderAddress);
            addressFrom.setPersonal(senderName);
            message.setFrom(addressFrom);
            InternetAddress[] addressTo = new InternetAddress[1];
            addressTo[0] = new InternetAddress(address);
            message.setRecipients(Message.RecipientType.TO, addressTo);
            message.setSubject("BIMserver Model Comparator");
            SCompareResult compareResult = compare(roid1, roid2, sCompareType, mcid);
            String html = CompareWriter.writeCompareResult(compareResult, revision1.getId(), revision2.getId(), sCompareType, getServiceMap().getServiceInterface().getProjectByPoid(poid), false);
            message.setContent(html, "text/html");
            message.send();
        } catch (AddressException e) {
            throw new UserException(e);
        } catch (UnsupportedEncodingException e) {
            throw new UserException(e);
        } catch (MessagingException e) {
            throw new UserException(e);
        }
    } catch (Exception e) {
        handleException(e);
    } finally {
        session.close();
    }
}
Also used : EmailMessage(org.bimserver.mail.EmailMessage) InternetAddress(javax.mail.internet.InternetAddress) DatabaseSession(org.bimserver.database.DatabaseSession) MessagingException(javax.mail.MessagingException) SUser(org.bimserver.interfaces.objects.SUser) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) SerializerException(org.bimserver.plugins.serializers.SerializerException) BcfException(org.opensourcebim.bcf.BcfException) UserException(org.bimserver.shared.exceptions.UserException) CannotBeScheduledException(org.bimserver.longaction.CannotBeScheduledException) DeserializeException(org.bimserver.plugins.deserializers.DeserializeException) ServerException(org.bimserver.shared.exceptions.ServerException) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) SRevision(org.bimserver.interfaces.objects.SRevision) Revision(org.bimserver.models.store.Revision) CheckinRevision(org.bimserver.models.store.CheckinRevision) SExtendedDataAddedToRevision(org.bimserver.interfaces.objects.SExtendedDataAddedToRevision) AddressException(javax.mail.internet.AddressException) SCompareResult(org.bimserver.interfaces.objects.SCompareResult) UserException(org.bimserver.shared.exceptions.UserException)

Example 2 with EmailMessage

use of org.bimserver.mail.EmailMessage 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 EmailMessage

use of org.bimserver.mail.EmailMessage in project BIMserver by opensourceBIM.

the class NewRevisionNotification method sendEmail.

private void sendEmail(DatabaseSession session, Project project, Revision revision) throws UserException {
    Set<User> users = getUsers(session, project);
    for (User user : users) {
        String body = null;
        try {
            if (MailSystem.isValidEmailAddress(user.getUsername())) {
                EmailMessage message = getBimServer().getMailSystem().createMessage();
                ServerSettings serverSettings = getBimServer().getServerSettingsCache().getServerSettings();
                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("revisionId", revision.getId());
                Authorization authorization = null;
                if (user.getUserType() == UserType.ADMIN) {
                    authorization = new AdminAuthorization(getBimServer().getServerSettingsCache().getServerSettings().getSessionTimeOutSeconds(), TimeUnit.SECONDS);
                } else {
                    authorization = new UserAuthorization(getBimServer().getServerSettingsCache().getServerSettings().getSessionTimeOutSeconds(), TimeUnit.SECONDS);
                }
                authorization.setUoid(user.getOid());
                String asHexToken = authorization.asHexToken(getBimServer().getEncryptionKey());
                context.put("token", asHexToken);
                context.put("roid", revision.getOid());
                context.put("comment", revision.getComment());
                context.put("projectName", project.getName());
                String subject = null;
                body = getBimServer().getTemplateEngine().process(context, TemplateIdentifier.NEW_REVISION_EMAIL_BODY);
                subject = getBimServer().getTemplateEngine().process(context, TemplateIdentifier.NEW_REVISION_EMAIL_SUBJECT);
                message.setContent(body, "text/html");
                message.setSubject(subject.trim());
                LOGGER.info("Sending new revision e-mail to " + user.getUsername());
                message.send();
            }
        } catch (Exception e) {
            LOGGER.error(body);
            LOGGER.error("", e);
            throw new UserException(e);
        }
    }
}
Also used : EmailMessage(org.bimserver.mail.EmailMessage) InternetAddress(javax.mail.internet.InternetAddress) User(org.bimserver.models.store.User) HashMap(java.util.HashMap) UserAuthorization(org.bimserver.webservices.authorization.UserAuthorization) ModelCheckException(org.bimserver.plugins.modelchecker.ModelCheckException) UserException(org.bimserver.shared.exceptions.UserException) ChannelConnectionException(org.bimserver.shared.ChannelConnectionException) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) ServerException(org.bimserver.shared.exceptions.ServerException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException) ExplicitRightsAuthorization(org.bimserver.webservices.authorization.ExplicitRightsAuthorization) AdminAuthorization(org.bimserver.webservices.authorization.AdminAuthorization) UserAuthorization(org.bimserver.webservices.authorization.UserAuthorization) Authorization(org.bimserver.webservices.authorization.Authorization) ServerSettings(org.bimserver.models.store.ServerSettings) UserException(org.bimserver.shared.exceptions.UserException) AdminAuthorization(org.bimserver.webservices.authorization.AdminAuthorization)

Example 4 with EmailMessage

use of org.bimserver.mail.EmailMessage in project BIMserver by opensourceBIM.

the class RequestPasswordChangeDatabaseAction method execute.

@Override
public Void execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
    final User user = getUserByUserName(username);
    if (user == null) {
        throw new UserException("User with username \"" + username + "\" not found");
    }
    final String token = GeneratorUtils.generateToken();
    user.setValidationToken(Hashers.getSha256Hash(token));
    user.setValidationTokenCreated(new Date());
    getDatabaseSession().store(user);
    getDatabaseSession().addPostCommitAction(new PostCommitAction() {

        @Override
        public void execute() throws UserException {
            if (MailSystem.isValidEmailAddress(user.getUsername())) {
                EmailMessage message = bimServer.getMailSystem().createMessage();
                String body = null;
                String subject = null;
                try {
                    InternetAddress addressFrom = new InternetAddress(bimServer.getServerSettingsCache().getServerSettings().getEmailSenderAddress());
                    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());
                    if (includeSiteAddress) {
                        context.put("siteaddress", bimServer.getServerSettingsCache().getServerSettings().getSiteAddress());
                    }
                    context.put("validationlink", resetUrl + "&username=" + user.getUsername() + "&uoid=" + user.getOid() + "&validationtoken=" + token + (includeSiteAddress ? ("&address=" + bimServer.getServerSettingsCache().getServerSettings().getSiteAddress()) : ""));
                    body = bimServer.getTemplateEngine().process(context, TemplateIdentifier.PASSWORD_RESET_EMAIL_BODY);
                    subject = bimServer.getTemplateEngine().process(context, TemplateIdentifier.PASSWORD_RESET_EMAIL_SUBJECT);
                    message.setContent(body, "text/html");
                    message.setSubject(subject.trim());
                    message.send();
                } catch (Exception e) {
                    LOGGER.error(body);
                    throw new UserException(e.getMessage());
                }
            }
        }
    });
    return null;
}
Also used : EmailMessage(org.bimserver.mail.EmailMessage) InternetAddress(javax.mail.internet.InternetAddress) User(org.bimserver.models.store.User) PostCommitAction(org.bimserver.database.PostCommitAction) UserException(org.bimserver.shared.exceptions.UserException) HashMap(java.util.HashMap) Map(java.util.Map) Date(java.util.Date) BimserverLockConflictException(org.bimserver.database.BimserverLockConflictException) UserException(org.bimserver.shared.exceptions.UserException) BimserverDatabaseException(org.bimserver.BimserverDatabaseException)

Aggregations

InternetAddress (javax.mail.internet.InternetAddress)4 BimserverDatabaseException (org.bimserver.BimserverDatabaseException)4 EmailMessage (org.bimserver.mail.EmailMessage)4 UserException (org.bimserver.shared.exceptions.UserException)4 HashMap (java.util.HashMap)3 User (org.bimserver.models.store.User)3 Date (java.util.Date)2 Map (java.util.Map)2 BimserverLockConflictException (org.bimserver.database.BimserverLockConflictException)2 PostCommitAction (org.bimserver.database.PostCommitAction)2 ServerSettings (org.bimserver.models.store.ServerSettings)2 ServerException (org.bimserver.shared.exceptions.ServerException)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 MessagingException (javax.mail.MessagingException)1 AddressException (javax.mail.internet.AddressException)1 Authenticator (org.bimserver.Authenticator)1 DatabaseSession (org.bimserver.database.DatabaseSession)1 SCompareResult (org.bimserver.interfaces.objects.SCompareResult)1