2008年9月6日

          /**
           * Excel WorkBook對(duì)象類
           * @author zhouqian
           *
           */
          public class ExcelWorkBook {
           /** 工作簿 */
           private static HSSFWorkbook workbook = new HSSFWorkbook();
           
           /** 工作表 */
           private HSSFSheet sheet;
           
           /** 表頭數(shù)據(jù) */
           private String[] tableHeader;
           
           /**
            * 構(gòu)造函數(shù)
            * @param workbookName 工作表名
            * @param tableHeader 表頭數(shù)據(jù)
            */
           public ExcelWorkBook(String workbookName, String[] tableHeader) {
            super();
            this.tableHeader = tableHeader;
            sheet = workbook.createSheet(workbookName);
           }
           
           /**
            * 創(chuàng)建表頭
            * @param headerName
            */
           public void createTableHeader(String headerName) {
            HSSFHeader header = sheet.getHeader();
            header.setCenter(headerName);
            HSSFRow headerRow = sheet.createRow(0);
            int cellNumber = tableHeader.length;
            for (int i = 0; i < cellNumber; i++) {
             HSSFCell headerCell = headerRow.createCell((short)i);
             headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
             headerCell.setCellValue(tableHeader[i]);
            }
           }
           
           /**
            * 創(chuàng)建行
            * @param data 要寫入的數(shù)據(jù)
            * @param rowIndex 第rowIndex行
            */
           public void createTableRow(String[] data, int rowIndex) {
            HSSFRow row = sheet.createRow(rowIndex);
            for (int i = 0; i < data.length; i++) {
             HSSFCell cell = row.createCell((short)i);
             cell.setEncoding(HSSFCell.ENCODING_UTF_16);
             cell.setCellValue(data[i]);
            }
            
           }
           
           /**
            * 創(chuàng)建整個(gè)Excel表
            * @param headerName
            */
           public void createExcelSheet(String headerName, String[][] data) {
            this.createTableHeader(headerName);
            
            String[] rowData;
            for (int i = 0; i < data.length; i++) {
             rowData = data[i];
             createTableRow(rowData, i + 1);
            }
            
           }
           
           /**
            * 導(dǎo)出Excel表格
            * @param os
            * @throws IOException
            */
           public void exportExcel(OutputStream os) throws IOException {
            sheet.setGridsPrinted(true);
            HSSFFooter footer = sheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            workbook.write(os);
           }

           public HSSFSheet getSheet() {
            return sheet;
           }

           public void setSheet(HSSFSheet sheet) {
            this.sheet = sheet;
           }

           public String[] getTableHeader() {
            return tableHeader;
           }

           public void setTableHeader(String[] tableHeader) {
            this.tableHeader = tableHeader;
           }
          }

          posted @ 2009-03-10 20:27 chou 閱讀(177) | 評(píng)論 (0)編輯 收藏
           

          /**
           * 郵件客戶端
           *
           * @author zhouqian
           *
           */
          public class MailClient {
           /** 日志實(shí)例 */
           Log logger = LogFactory.getLog(MailClient.class);

           /** 消息對(duì)象 */
           private Message message;

           /** 郵件會(huì)話 */
           private Session session;

           public MailClient() {
            super();
            this.session = createDefaultSession();
           }

           public MailClient(Session session) {
            super();
            this.session = session;
           }

           public MailClient(Message message) {
            this();
            this.message = message;
           }

           public MailClient(Session session, Message message) {
            super();
            this.session = session;
            this.message = message;
           }

           /**
            * 創(chuàng)建郵件會(huì)話
            *
            * @return
            */
           protected Session createDefaultSession() {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.163.com");
            props.put("mail.smtp.auth", "true");
            Session session = Session.getInstance(props);
            session.setDebug(true);
            return session;
           }

           /**
            * 創(chuàng)建純文本郵件
            *
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            * @return
            * @throws MessagingException
            */
           protected Message createMimeMessage(String subject, String content,
             String recipientTO, String recipientCC, String recipientBCC)
             throws MessagingException {
            Message message = createBlankMessage(recipientTO, recipientCC,
              recipientBCC);

            // 設(shè)置郵件標(biāo)題
            message.setSubject(subject);

            // 設(shè)置郵件內(nèi)容
            message.setText(content);

            // 設(shè)置發(fā)送時(shí)間
            message.setSentDate(new Date(System.currentTimeMillis()));

            // 存儲(chǔ)郵件信息
            message.saveChanges();

            return message;
           }

           /**
            * 創(chuàng)建帶HTML內(nèi)容的郵件
            *
            * @param subject
            * @param content
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            * @return
            * @throws MessagingException
            */
           protected Message createHTMLMessage(String subject, String content,
             String recipientTO, String recipientCC, String recipientBCC)
             throws MessagingException {
            Message message = createBlankMessage(recipientTO, recipientCC,
              recipientBCC);

            // 設(shè)置郵件標(biāo)題
            message.setSubject(subject);

            // 設(shè)置發(fā)送時(shí)間
            message.setSentDate(new Date(System.currentTimeMillis()));

            // 創(chuàng)建存放郵件內(nèi)容的BodyPart對(duì)象
            BodyPart bp = new MimeBodyPart();
            bp.setContent(content, "text/html;charset=gb2312");

            // 創(chuàng)建一個(gè)MimeMultipart來存放BodyPart對(duì)象
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(bp);

            message.setContent(mp);
            message.saveChanges();

            return message;
           }

           /**
            * 創(chuàng)建帶附件的郵件
            *
            * @param subject
            * @param content
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            * @return
            * @throws MessagingException
            */
           protected Message createAttachMessage(String subject, String content,
             File attachment, String recipientTO, String recipientCC,
             String recipientBCC) throws MessagingException {
            Message message = createBlankMessage(recipientTO, recipientCC,
              recipientBCC);

            // 設(shè)置郵件標(biāo)題
            message.setSubject(subject);

            // 設(shè)置發(fā)送時(shí)間
            message.setSentDate(new Date(System.currentTimeMillis()));

            // 創(chuàng)建存放郵件內(nèi)容的BodyPart對(duì)象
            BodyPart bp = new MimeBodyPart();
            bp.setContent(content, "text/html;charset=gb2312");

            // 創(chuàng)建一個(gè)MimeMultipart來存放BodyPart對(duì)象
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(bp);

            // 設(shè)置郵件的附件
            bp = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(attachment.getName());
            DataHandler dh = new DataHandler(fds);
            try {
             bp.setFileName(new String(attachment.getName().getBytes("gb2312")));
            } catch (UnsupportedEncodingException e) {
             final String errMess = "Caught exception while encoding file name:"
               + attachment.getName();
             logger.error(errMess);
             throw new MailException(errMess, e);
            }
            bp.setDataHandler(dh);
            mp.addBodyPart(bp);

            message.setContent(mp);
            message.saveChanges();
            return message;
           }

           /**
            * 創(chuàng)建空白郵件
            *
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            * @return
            * @throws MessagingException
            */
           protected Message createBlankMessage(String recipientTO,
             String recipientCC, String recipientBCC) throws MessagingException {
            Message message = new MimeMessage(session);

            // 設(shè)置發(fā)件人
            InternetAddress from = new InternetAddress("mfktfp2004@163.com");
            message.setFrom(from);

            // 設(shè)置收件人
            InternetAddress to = new InternetAddress(recipientTO);
            message.setRecipient(Message.RecipientType.TO, to);
            if (StringUtil.isNotEmpty(recipientCC)) {
             InternetAddress cc = new InternetAddress(recipientCC);
             message.setRecipient(Message.RecipientType.CC, cc);
            }
            if (StringUtil.isNotEmpty(recipientBCC)) {
             InternetAddress bcc = new InternetAddress(recipientBCC);
             message.setRecipient(Message.RecipientType.BCC, bcc);
            }

            return message;
           }

           /**
            * 發(fā)送郵件
            *
            * @param message
            * @throws MessagingException
            */
           public void sendEmail(Message message) throws MessagingException {
            // 以smtp方式登陸郵箱
            Transport transport = session.getTransport("smtp");
            transport.connect("smtp.163.com", "mfktfp2004", "19850921"); // SMTP地址,用戶名,密碼

            // 發(fā)送郵件
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
           }

           /**
            * 發(fā)送純文本郵件
            *
            * @param subject
            * @param content
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            */
           public void sendMimeEmail(String subject, String content,
             String recipientTO, String recipientCC, String recipientBCC) {
            Message message = null;
            try {
             message = createMimeMessage(subject, content, recipientTO,
               recipientCC, recipientBCC);
             sendEmail(message);
            } catch (MessagingException e) {
             logger.error("Send mime email failure", e);
             throw new MailException("Error sending email, failure", e);
            }

           }

           /**
            * 發(fā)送帶HTML內(nèi)容的郵件
            *
            * @param subject
            * @param content
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            */
           public void sendHTMLEmail(String subject, String content,
             String recipientTO, String recipientCC, String recipientBCC) {
            Message message = null;
            try {
             message = createHTMLMessage(subject, content, recipientTO,
               recipientCC, recipientBCC);
             sendEmail(message);
            } catch (MessagingException e) {
             logger.error("Send html email failure", e);
             throw new MailException("Error sending email, failure", e);
            }
           }

           /**
            * 發(fā)送帶附件的郵件
            *
            * @param subject
            * @param content
            * @param recipientTO
            * @param recipientCC
            * @param recipientBCC
            */
           public void sendAttachEmail(String subject, String content,
             File attachment, String recipientTO, String recipientCC,
             String recipientBCC) {
            Message message = null;
            try {
             message = createAttachMessage(subject, content, attachment,
               recipientTO, recipientCC, recipientBCC);
             sendEmail(message);
            } catch (MessagingException e) {
             logger.error("Send html email failure", e);
             throw new MailException("Error sending email, failure", e);
            }
           }

           public Message getMessage() {
            return message;
           }

           public void setMessage(Message message) {
            this.message = message;
           }

           public Session getSession() {
            return session;
           }

           public void setSession(Session session) {
            this.session = session;
           }
           
           public static void main(String[] args) {
            MailClient client = new MailClient();
            client.sendMimeEmail("test", "test", "zhouqian1103@163.com", null, null);
           }
          }


          public class MailException extends RuntimeException {
           private static final long serialVersionUID = 1L;
           
           /** Throwable實(shí)例 */
           protected Throwable throwable;
           
           public MailException() {
            super();
           }
           
           public MailException(String message) {
            super(message);
           }
           
           public MailException(Throwable cause) {
            this.throwable = cause;
           }
           
           public MailException(String message, Throwable cause) {
            super(message);
            this.throwable = cause;
           }
           
           public void printStackTrace(PrintStream ps) {
            super.printStackTrace(ps);
            if (throwable != null) {
             ps.println("with nested Exception:" + throwable);
             throwable.printStackTrace(ps);
            }
           }
           
           public void printStackTrace(PrintWriter pw) {
            super.printStackTrace(pw);
            if (throwable != null) {
             pw.println("with nested Exception:" + throwable);
             throwable.printStackTrace(pw);
            }
           }
           
           public String toString() {
            if (throwable == null) {
             return super.toString();
            } else {
             return super.toString() + "with nested exception:" + throwable;
            }
           }

           public Throwable getThrowable() {
            return throwable;
           }
          }


          posted @ 2009-03-10 20:26 chou 閱讀(257) | 評(píng)論 (0)編輯 收藏
           
          在測(cè)試Hibernate的一對(duì)多雙向關(guān)聯(lián)映射時(shí),碰到很有趣的問題,跟inverse屬性直接相關(guān)。

          1、People.hbm.xml

          <hibernate-mapping default-lazy="false"> 
          <class name="com.persistent.People" table="people"> 
          <id name="id" column="peopleId" unsaved-value="0"> 
          <generator class="increment"> 
          </generator> 
          </id> 
          <property name="name" column="name"></property> 
          <set name="addresses" cascade="save-update">
          <key column="peopleId" not-null="true" />
          <o(jì)ne-to-many class="com.persistent.Address"/>
          </set> 
          </class>
          </hibernate-mapping>

          2、Address.hbm.xml

          <hibernate-mapping>
          <class name="com.persistent.Address" table="address"> 
          <id name="id" column="addressId" unsaved-value="0">
          <generator class="increment">
          </generator>
          </id> 
          <many-to-one name="people" column="peopleId" insert="false" update="false"></many-to-one> 
          <property name="addressName" column="addressName"></property> 
          <property name="codeNumber" column="codeNumber"></property> 
          </class> 
          </hibernate-mapping>
          3、People.java和Address.java

          public class People ...{ 
          private long id; 
          private String name; 
          private Set addresses = new HashSet(); 
          ...
          }

          public class Address ...{ 
          private long id; 
          private People people; 
          private String addressName; 
          private String codeNumber; 
          ...
          } 

          4、數(shù)據(jù)庫(kù)結(jié)構(gòu)

          people表:{peopleId,name}

          address表:{addressId,peopleId,addressName,codeNumber}

          5、測(cè)試代碼

          People people = new People(); 
          people.setName("linda"); 
          Address address = new Address(); 
          address.setAddressName("yunnan"); 
          address.setCodeNumber("564123"); 
          address.setPeople(people); 
          people.getAddresses().add(address); 
          Session session = HibernateSessionFactory.getSession(); 
          session.beginTransaction(); 
          session.save(people); 
          session.getTransaction().commit(); 

          6、運(yùn)行結(jié)果

            上面測(cè)試代碼運(yùn)行起來正確:

          Hibernate: select max(peopleId) from people
          Hibernate: select max(addressId) from address
          Hibernate: insert into people (name, peopleId) values (?, ?)
          Hibernate: insert into address (addressName, codeNumber, peopleId, addressId) values (?, ?, ?, ?)
          Hibernate: update address set peopleId=? where addressId=?

            如果將People.hbm.xml映射改寫一下:

          <set name="addresses" cascade="save-update" inverse="true">
          <key column="peopleId" not-null="true" />
          <o(jì)ne-to-many class="com.persistent.Address"/>
          </set>

            不同之處在于添加了inverse="true",結(jié)果:

          Hibernate: select max(peopleId) from people
          Hibernate: select max(addressId) from address
          Hibernate: insert into people (name, peopleId) values (?, ?)
          Hibernate: insert into address (addressName, codeNumber, addressId) values (?, ?, ?)

            可以看到,peopleId并沒有寫入到關(guān)聯(lián)的address當(dāng)中,數(shù)據(jù)庫(kù)address表中相應(yīng)記錄的peopleId字段為空。

          7、分析

            在Hibernate中,術(shù)語inverse是反轉(zhuǎn)的意思,在關(guān)聯(lián)關(guān)系中,inverse="false"為主控方,由主控方負(fù)責(zé)維護(hù)對(duì)象的關(guān)聯(lián)關(guān)系。所以上面的映射文件改動(dòng)之后,address為主控方,people為被控方,但是測(cè)試代碼只進(jìn)行了一個(gè)保存操作session.save(people),這是針對(duì)people的,因此無法正確級(jí)聯(lián)保存address。而原來的映射文件中(雖然沒有明確指明,Hibernate默認(rèn)inverse="false"),people為主控方,因此保存people時(shí)它會(huì)保證關(guān)聯(lián)的address的正確保存。

            也就是說,Hibernate僅僅按照主控方對(duì)象的狀態(tài)的變化來同步更新數(shù)據(jù)庫(kù)。按照原來的映射文件,people.getAddresses().add(address),即主控方對(duì)象的狀態(tài)發(fā)生了改變,因此數(shù)據(jù)庫(kù)會(huì)跟著對(duì)象狀態(tài)的變化來同步更新數(shù)據(jù)庫(kù);而address.setPeople(people),即被控方對(duì)象的狀態(tài)發(fā)生了改變,它是不能觸發(fā)對(duì)象和數(shù)據(jù)庫(kù)的同步更新的。
          posted @ 2008-09-06 14:41 chou 閱讀(156) | 評(píng)論 (0)編輯 收藏
           
          主站蜘蛛池模板: 桑植县| 淮阳县| 兴仁县| 光山县| 班玛县| 辽宁省| 长垣县| 浪卡子县| 大丰市| 岱山县| 肥乡县| 通江县| 阳信县| 隆化县| 临高县| 开封市| 广平县| 茶陵县| 左云县| 六枝特区| 论坛| 通化县| 临朐县| 紫金县| 咸阳市| 七台河市| 武陟县| 姚安县| 卢龙县| 彩票| 辽源市| 双鸭山市| 信丰县| 朝阳市| 虹口区| 贵南县| 保山市| 莱西市| 苏尼特右旗| 许昌县| 杨浦区|