⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webauctionbean.java

📁 J2EE开发与Weblogic一书中的源代码
💻 JAVA
字号:
package webauction.ejb;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import javax.sql.DataSource;

import weblogic.management.*;
import weblogic.management.configuration.SecurityConfigurationMBean;
import weblogic.management.security.authentication.AuthenticationProviderMBean;
import weblogic.management.utils.AlreadyExistsException;
import weblogic.management.utils.InvalidParameterException;
import weblogic.management.utils.NotFoundException;
import weblogic.security.providers.authentication.DefaultAuthenticatorMBean;

public class WebAuctionBean implements SessionBean {

    private SessionContext ctx;

    private UserHome userHome;
    private BidHome bidHome;
    private ItemHome itemHome;
    private IDGeneratorHome idGeneratorHome;
    private DataSource dataSource;
    private DefaultAuthenticatorMBean defaultAuth;

    private Object narrow(Object o, Class c) {
        return PortableRemoteObject.narrow(o, c);
    }

    public void setSessionContext(SessionContext c) {
        ctx = c;
        try {
            Context ic = new InitialContext();

            userHome =
                (UserHome) narrow(ic.lookup(EjbConstants.LOOKUP_USER_HOME),
                    UserHome.class);
            bidHome =
                (BidHome) narrow(ic.lookup(EjbConstants.LOOKUP_BID_HOME),
                    BidHome.class);
            itemHome =
                (ItemHome) narrow(ic.lookup(EjbConstants.LOOKUP_ITEM_HOME),
                    ItemHome.class);
            idGeneratorHome =
                (IDGeneratorHome) narrow(ic
                    .lookup(EjbConstants.LOOKUP_IDGEN_HOME),
                    IDGeneratorHome.class);

            String poolName = (String) ic.lookup(EjbConstants.LOOKUP_POOL_NAME);
            dataSource = (DataSource) ic.lookup("java:/comp/env/" + poolName);

            MBeanHome mbeanhome =
                (MBeanHome) ic.lookup(MBeanHome.ADMIN_JNDI_NAME);
            java.util.Set secConfSet =
                mbeanhome.getMBeansByType("SecurityConfiguration");
            if (!secConfSet.isEmpty()) {
                SecurityConfigurationMBean secConf =
                    (SecurityConfigurationMBean) secConfSet.iterator().next();
                weblogic.management.security.RealmMBean realmMBean;
                realmMBean = secConf.findDefaultRealm();

                AuthenticationProviderMBean authProviderMBean[] =
                    realmMBean.getAuthenticationProviders();
                GET_MBEAN : for (
                    int i = 0; i < authProviderMBean.length; i++) {
                    if (authProviderMBean[i]
                        instanceof DefaultAuthenticatorMBean) {
                        defaultAuth =
                            (DefaultAuthenticatorMBean) authProviderMBean[i];
                        if (!defaultAuth
                            .groupExists(EjbConstants.AUCTION_GROUP)) {
                            throw new EJBException(
                                "Auction application requires group "
                                    + EjbConstants.AUCTION_GROUP);
                        }
                    }
                }
            }
        } catch (NamingException e) {
            throw new EJBException(e);
        } catch (InvalidParameterException e) {
            throw new EJBException(e);
        }
    }

    public void ejbCreate() {}
    public void ejbRemove() {}
    public void ejbActivate() {}
    public void ejbPassivate() {}

    public BidValueHolder[] getBidsForUser(String userName)
        throws NoSuchUserException {
        try {
            User user = userHome.findByPrimaryKey(userName);
            Collection bids = bidHome.findBidsForUser(user);
            int size = bids.size();
            if (size == 0) {
                // no bids for this user
                return null;
            } else {
                // build an array of java bean value objects
                Iterator it = bids.iterator();
                BidValueHolder[] bidValues = new BidValueHolder[size];
                for (int i = 0; i < size; i++) {
                    Bid b = (Bid) narrow(it.next(), Bid.class);
                    bidValues[i] =
                        new BidValueHolder(
                            b.getId().intValue(),
                            b.getItem().getDescription(),
                            b.getAmount());
                }
                return bidValues;
            }
        } catch (FinderException fe) {
            fe.printStackTrace();
            throw new NoSuchUserException(
                "User with name: "
                    + userName
                    + " does not exist or could not be loaded.");
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(
                "Error looking for bids for user:"
                    + userName
                    + ".  The error was: "
                    + e);
        }
    }

    public ItemValueHolder getItemWithId(int id) throws NoSuchItemException {
        try {
            Item item = itemHome.findByPrimaryKey(new Integer(id));
            ItemValueHolder ivh = new ItemValueHolder();
            ivh.setItemDescription(item.getDescription());
            ivh.setTopBidAmount(item.getTopBidAmount());
            ivh.setId(id);
            return ivh;

        } catch (FinderException fe) {
            ctx.setRollbackOnly();
            throw new NoSuchItemException(
                "Item with id: "
                    + id
                    + " does not exist or could not be loaded.");
        } catch (RemoteException re) {
            re.printStackTrace();
            throw new EJBException(
                "Error getting item with id:" + id + ".  The error was: " + re);
        }
    }

    public ItemValueHolder[] getItemsInCategory(String category) {
        try {
            Collection items = itemHome.findItemsInCategory(category);

            if (items.isEmpty()) {
                return null;
            } else {
                ItemValueHolder[] itemValues =
                    new ItemValueHolder[items.size()];
                Iterator it = items.iterator();
                for (int i = 0; i < itemValues.length; i++) {
                    Item item = (Item) narrow(it.next(), Item.class);
                    Integer id = (Integer) item.getPrimaryKey();
                    itemValues[i] = new ItemValueHolder();
                    itemValues[i].setItemDescription(item.getDescription());
                    itemValues[i].setTopBidAmount(item.getTopBidAmount());
                    itemValues[i].setUserName(item.getUser().getUserName());
                    itemValues[i].setId(id.intValue());
                }
                return itemValues;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e);
        }
    }

    public ItemValueHolder createItem(
        String userId,
        String desc,
        String cat,
        long date) {
        try {
            User user = userHome.findByPrimaryKey(userId);
            int id = idGeneratorHome.create().getNextValue();
            Item item =
                itemHome.create(
                    new Integer(id),
                    user,
                    desc,
                    cat,
                    new java.sql.Date(date));
            ItemValueHolder ivh = new ItemValueHolder();
            ivh.setItemDescription(item.getDescription());
            ivh.setTopBidAmount(item.getTopBidAmount());
            ivh.setId(id);
            return ivh;
        } catch (Exception e) {
            ctx.setRollbackOnly();
            e.printStackTrace();
            throw new EJBException(e);
        }
    }

    public void createUser(
        String userName,
        String password,
        String firstName,
        String lastName,
        String streetAddress,
        String city,
        String zipcode,
        String email)
        throws RemoteException, CreateException {
        	System.out.println("add user to DB");
        User user =
            userHome.create(
                userName,
                firstName,
                lastName,
                streetAddress,
                city,
                zipcode,
                email);
        try {
        	System.out.println("add user to domain");
            defaultAuth.createUser(
                userName,
                password,
                "Auction user " + firstName + " " + lastName);
                System.out.println("add user to group");
            defaultAuth.addMemberToGroup(EjbConstants.AUCTION_GROUP, userName);
            System.out.println("Out of the woods?");
        } catch (InvalidParameterException e) {
            System.err.println("Invalid Parameter Exception");
            ctx.setRollbackOnly();
        } catch (AlreadyExistsException e) {
            System.err.println(
                "Already Exists Exception -- user already exists");
            ctx.setRollbackOnly();
        } catch (NotFoundException e) {
            System.err.println("Not found Exception -- could not find group");
            ctx.setRollbackOnly();
        } catch (weblogic.management.NoAccessRuntimeException e) {
            System.err.println("Required Credentials not available");
            ctx.setRollbackOnly();
        } catch (Exception e) {
            System.err.println("Other RuntimeException");
            e.printStackTrace();
        }
    }

    public boolean userExists(String userName) throws RemoteException {
        return isUserInAuction(userName) || isUserInDomain(userName);
    }

    private boolean isUserInDomain(String userName) throws RemoteException {
        try {
            boolean userExists = defaultAuth.userExists(userName);
            return userExists;
        } catch (NullPointerException e) {
            throw new RemoteException(
                "Unable to create DefaultAuthenticationMBean",
                e);
        } catch (InvalidParameterException e) {
            throw new RemoteException("caught InvalidParameterException", e);
        }
    }

    private boolean isUserInAuction(String userName) throws RemoteException {
        Connection conn = null;
        boolean userExists;
        try {
            conn = dataSource.getConnection();
            Statement st = conn.createStatement();
            String jdbcStatement =
                "SELECT * FROM USERTABLE WHERE USERNAME='" + userName + "'";
            ResultSet rs = st.executeQuery(jdbcStatement);
            userExists = rs.next();
        } catch (SQLException e) {
            throw new RemoteException("caught SQL exception", e);
        } finally {
            try {
                conn.close();
            } catch (Exception e) {
                //ignore
            }
        }
        return userExists;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -