Java源码示例:com.icegreen.greenmail.user.UserException

示例1
@Override
public void execute(Pop3Connection conn, Pop3State state,
                    String cmd) {
    try {
        String[] args = cmd.split(" ");
        if (args.length < 2) {
            conn.println("-ERR Required syntax: USER <username>");
            return;
        }

        String username = args[1];
        GreenMailUser user = state.findOrCreateUser(username);
        if (null == user) {
            conn.println("-ERR User '" + username + "' not found");
            return;
        }
        state.setUser(user);
        conn.println("+OK");
    } catch (UserException nsue) {
        conn.println("-ERR " + nsue);
    }
}
 
示例2
@Test
public void authPlain() throws IOException, MessagingException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // No such user
        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */);
        assertThat(reader.readLine(), is(equalTo("-ERR Authentication failed: User <test> doesn't exist")));

        greenMail.getManagers().getUserManager().createUser("[email protected]", "test", "testpass");

        // Invalid pwd
        printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / <invalid> */);
        assertThat(reader.readLine(), is(equalTo("-ERR Authentication failed: Invalid password")));

        // Successful auth
        printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
        assertThat(reader.readLine(), is(equalTo("+OK")));
    }
}
 
示例3
private void addMailUser(final String user) {
    // Parse ...
    int posColon = user.indexOf(':');
    int posAt = user.indexOf('@');
    String login = user.substring(0, posColon);
    String pwd = user.substring(posColon + 1, posAt);
    String domain = user.substring(posAt + 1);
    String email = login + '@' + domain;
    if (log.isDebugEnabled()) {
        // This is a test system, so we do not care about pwd in the log file.
        log.debug("Adding user " + login + ':' + pwd + '@' + domain);
    }


    GreenMailUser greenMailUser = managers.getUserManager().getUser(email);
    if (null == greenMailUser) {
        try {
            greenMailUser = managers.getUserManager().createUser(email, login, pwd);
            greenMailUser.setPassword(pwd);
        } catch (UserException e) {
            throw new RuntimeException(e);
        }
    }
}
 
示例4
/**
 * Sending email to the user account in the server with additional headers.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException      when no such user or user is null
 */
public void sendMail(String subject, Map<String, String> headers) throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        message.addHeader(entry.getKey(), entry.getValue());
    }
    greenMailUser.deliver(message);
}
 
示例5
public GreenMailUser createUser(String email, String login, String password) throws UserException
{
    // TODO: User creation/addition code should be implemented here (in the AlfrescoImapUserManager).
    // Following code is not need and not used in the current implementation.
    GreenMailUser user = new AlfrescoImapUser(email, login, password);
    user.create();
    addUser(user);
    return user;
}
 
示例6
/**
 * Sending email to the user account in the server with additional headers.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException when no such user or user is null
 */
public void sendMail(String subject, Map<String, String> headers)
        throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        message.addHeader(entry.getKey(), entry.getValue());
    }
    greenMailUser.deliver(message);
}
 
示例7
@Override
public void contextInitialized(final ServletContextEvent sce) {
    log.info("Initializing GreenMail");

    managers = new Managers();
    ServletContext ctx = sce.getServletContext();
    configuration = ConfigurationFactory.create(extractParameters(ctx));
    services = ServiceFactory.create(configuration, managers);

    for (Configuration.User user : configuration.getUsers()) {
        GreenMailUser greenMailUser = managers.getUserManager().getUser(user.email);
        if (null == greenMailUser) {
            try {
                greenMailUser = managers.getUserManager().createUser(
                        user.email, user.login, user.password);
                greenMailUser.setPassword(user.password);
            } catch (UserException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    for (Service s : services) {
        log.info("Starting GreenMail service: {}", s);
        s.startService();
    }

    ContextHelper.initAttributes(ctx, managers, configuration);
}
 
示例8
public GreenMailUser getUser(String username) throws UserException {
    GreenMailUser user = manager.getUser(username);
    if (null == user) {
        throw new NoSuchUserException("User <" + username + "> doesn't exist");
    }
    return user;
}
 
示例9
public void authenticate(String pass)
        throws UserException, FolderException {
    if (user == null)
        throw new UserException("No user selected");

    if (manager.isAuthRequired()) {
        user.authenticate(pass);
    }
    inbox = imapHostManager.getInbox(user);
}
 
示例10
public GreenMailUser findOrCreateUser(String username) throws UserException {
    if (manager.hasUser(username)) {
        return manager.getUser(username);
    }
    if (!manager.isAuthRequired()) {
        return manager.createUser(username, username, username);
    }
    throw new UserException("Unable to find or create user '" + username +"'");
}
 
示例11
@Override
public GreenMailUser setUser(String email, String login, String password) {
    GreenMailUser user = managers.getUserManager().getUser(login);
    if (null == user) {
        try {
            user = managers.getUserManager().createUser(email, login, password);
        } catch (UserException e) {
            throw new RuntimeException(e);
        }
    } else {
        user.setPassword(password);
    }
    return user;
}
 
示例12
@Test
public void testSendAndReceive() throws UnsupportedEncodingException, MessagingException, UserException {
    Session smtpSession = greenMail.getSmtp().createSession();

    Message msg = new MimeMessage(smtpSession);
    msg.setFrom(new InternetAddress("[email protected]"));
    msg.addRecipient(Message.RecipientType.TO,
            new InternetAddress("[email protected]"));
    msg.setSubject("Email sent to GreenMail via plain JavaMail");
    msg.setText("Fetch me via IMAP");
    Transport.send(msg);

    // Create user, as connect verifies pwd
    greenMail.setUser("[email protected]", "[email protected]", "secret-pwd");

    // Alternative 1: Create session and store or ...
    Session imapSession = greenMail.getImap().createSession();
    Store store = imapSession.getStore("imap");
    store.connect("[email protected]", "secret-pwd");
    Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    Message msgReceived = inbox.getMessage(1);
    assertEquals(msg.getSubject(), msgReceived.getSubject());

    // Alternative 2: ... let GreenMail create and configure a store:
    IMAPStore imapStore = greenMail.getImap().createStore();
    imapStore.connect("[email protected]", "secret-pwd");
    inbox = imapStore.getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    msgReceived = inbox.getMessage(1);
    assertEquals(msg.getSubject(), msgReceived.getSubject());

    // Alternative 3: ... directly fetch sent message using GreenMail API
    assertEquals(1, greenMail.getReceivedMessagesForDomain("[email protected]").length);
    msgReceived = greenMail.getReceivedMessagesForDomain("[email protected]")[0];
    assertEquals(msg.getSubject(), msgReceived.getSubject());

    store.close();
    imapStore.close();
}
 
示例13
@Test
public void authLogin() throws IOException, MessagingException, UserException {
    Session smtpSession = greenMail.getSmtp().createSession();
    SMTPTransport smtpTransport = new SMTPTransport(smtpSession, smtpURL);
    try {
        Socket smtpSocket = new Socket(hostAddress, port); // Closed by transport
        smtpTransport.connect(smtpSocket);
        assertThat(smtpTransport.isConnected(), is(equalTo(true)));

        // Should fail, as user does not exist
        smtpTransport.issueCommand("AUTH LOGIN ", 334);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_CREDENTIALS_INVALID));

        // Try again but create user
        greenMail.getManagers().getUserManager().createUser("[email protected]", "test", "testpass");
        smtpTransport.issueCommand("AUTH LOGIN ", 334);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 VXNlciBOYW1lAA==" /* Username */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace("334 UGFzc3dvcmQA" /* Password */));
        smtpTransport.issueCommand(Base64.getEncoder().encodeToString("testpass".getBytes(StandardCharsets.US_ASCII)), -1);
        assertThat(smtpTransport.getLastServerResponse(), equalToCompressingWhiteSpace(AuthCommand.AUTH_SUCCEDED));
    } finally {
        smtpTransport.close();
    }
}
 
示例14
@Test
public void authPlainWithContinuation() throws IOException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        greenMail.getManagers().getUserManager().createUser("[email protected]", "test", "testpass");

        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */);
        assertThat(reader.readLine(), is(equalTo(AuthCommand.CONTINUATION)));
        printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / <invalid> */);
        assertThat(reader.readLine(), is(equalTo("+OK")));
    }
}
 
示例15
@Test
public void authDisabled() throws IOException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        greenMail.getManagers().getUserManager().setAuthRequired(false);

        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("USER [email protected]" + CRLF);
        assertThat(reader.readLine(), is(equalTo("+OK")));
    }
}
 
示例16
@Test
public void authEnabled() throws IOException, UserException {
    try (Socket socket = new Socket(hostAddress, port)) {
        assertThat(socket.isConnected(), is(equalTo(true)));
        PrintStream printStream = new PrintStream(socket.getOutputStream());
        final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        greenMail.getManagers().getUserManager().setAuthRequired(true);

        assertThat(reader.readLine(), is(startsWith("+OK POP3 GreenMail Server v")));
        printStream.print("USER [email protected]" + CRLF);
        assertThat(reader.readLine(), is(not(equalTo("+OK"))));
    }
}
 
示例17
@Test
public void testPop3Capabillities() throws MessagingException, UserException {
    final POP3Store store = greenMail.getPop3().createStore();
    greenMail.getManagers().getUserManager().createUser("[email protected]",
            "[email protected]", "pwd");
    store.connect("[email protected]", "pwd");
    try {
        assertTrue(store.capabilities().containsKey("UIDL"));
    } finally {
        store.close();
    }
}
 
示例18
@Test
public void testPop3ConnectNoAuth() throws MessagingException, UserException, FolderException {
    UserManager userManager = greenMail.getManagers().getUserManager();
    Pop3State status = new Pop3State(userManager);
    userManager.setAuthRequired(false);

    UserImpl user = new UserImpl("[email protected]", "user", "pwd", null);
    status.setUser(user);
    status.authenticate("pass");
}
 
示例19
@Test(expected = UserException.class)
public void testPop3ConnectAuth() throws MessagingException, UserException, FolderException {
    UserManager userManager = greenMail.getManagers().getUserManager();
    Pop3State status = new Pop3State(userManager);
    userManager.setAuthRequired(true);

    UserImpl user = new UserImpl("[email protected]", "user", "pwd", null);
    status.setUser(user);
    status.authenticate("pass");
}
 
示例20
public void authenticate(String password) throws UserException
{
    throw new UnsupportedOperationException();
    // This method is used in the POP3 greenmail implementation, so it is disabled for IMAP
    // See AlfrescoImapUserManager.test() method.
}
 
示例21
public void create() throws UserException
{
    throw new UnsupportedOperationException();
}
 
示例22
public void delete() throws UserException
{
    throw new UnsupportedOperationException();
}
 
示例23
public void deliver(MovingMessage msg) throws UserException
{
    throw new UnsupportedOperationException();
}
 
示例24
public void deliver(MimeMessage msg) throws UserException
{
    throw new UnsupportedOperationException();
}
 
示例25
/**
 * Sending email to the user account in the server.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException      when no such user or user is null
 */
public void sendMail(String subject) throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    greenMailUser.deliver(message);
}
 
示例26
/**
 * Sending email to the user account in the server.
 *
 * @param subject Email subject
 * @throws MessagingException if the properties set to the message are not valid
 * @throws UserException when no such user or user is null
 */
public void sendMail(String subject) throws MessagingException, UserException {
    MimeMessage message = createBasicMessage(subject);
    greenMailUser.deliver(message);
}