yooli88

2006年4月12日 #

java 字符串解析 转至csdn的afgasdg

StringTokenizer tokenizer = new StringTokenizer(number, ",");
       
boolean bool = true;
       
while (tokenizer.hasMoreTokens()) {
           
try {
                Double.valueOf(tokenizer.nextToken());
            }
catch (Exception e) {
                bool
= false;
            }
        }
//将字符串转化为数组的方法
int gv[];
  
int i = 0;
   StringTokenizer tokenizer
= new StringTokenizer(goodsVolume, ",, ");
         gv
= new int[tokenizer.countTokens()];//动态的决定数组的长度
     while (tokenizer.hasMoreTokens()) {
        String d
= tokenizer.nextToken();
        gv[i]
= Integer.valueOf(d);//将字符串转换为整型
        i++;
    }

//字符串解析
    private String[] stringAnalytical(String str, String divisionChar) {
        String string[];
      
int i = 0;
        StringTokenizer tokenizer
= new StringTokenizer(str, divisionChar);
        string
= new String[tokenizer.countTokens()];// 动态的决定数组的长度
         while (tokenizer.hasMoreTokens()) {
            string[i]
= new String();
            string[i]
= tokenizer.nextToken();
            i
++;
        }
       
return string;// 返回字符串数组
    }

int countTokens()
          计算在生成异常之前可以调用此 tokenizer 的 nextToken 方法的次数。
boolean hasMoreElements()
          返回与 hasMoreTokens 方法相同的值。
boolean hasMoreTokens()
          测试此 tokenizer 的字符串中是否还有更多的可用标记。
Object nextElement()
          除了其声明返回值是 Object 而不是 String 之外,它返回与 nextToken 方法相同的值。
String nextToken()
          返回此 string tokenizer 的下一个标记。
String nextToken(String delim)
          返回此 string tokenizer 的字符串中的下一个标记。




public class StringAnalytical {

   
// 字符串解析,将字符串转根据分割符换成字符串数组
    private String[] stringAnalytical(String string, char c) {
       
int i = 0;
       
int count = 0;

       
if (string.indexOf(c) == -1)
           
return new String[] { string };// 如果不含分割符则返回字符本身
        char[] cs = string.toCharArray();
       
int length = cs.length;
       
for (i = 1; i < length - 1; i++) {// 过滤掉第一个和最后一个是分隔符的情况
            if (cs[i] == c) {
                count
++;// 得到分隔符的个数
            }
        }
        String[] strArray
= new String[count + 1];
       
int k = 0, j = 0;
        String str
= string;
       
if ((k = str.indexOf(c)) == 0)// 去掉第一个字符是分隔符的情况
            str = str.substring(k + 1);
       
if (str.indexOf(c) == -1)// 检测是否含分隔符,如果不含则返回字符串
            return new String[] { str };
       
while ((k = str.indexOf(c)) != -1) {// 字符串含分割符的时候
            strArray[j++] = str.substring(0, k);
            str
= str.substring(k + 1);
           
if ((k = str.indexOf(c)) == -1 && str.length() > 0)
                strArray[j
++] = str.substring(0);
        }
       
return strArray;
    }

   
public void printString(String[] s) {
        System.out.println(
"*********************************");
       
for (String str : s)
            System.out.println(str);
    }

   
public static void main(String[] args) {
        String[] str
= null;
        StringAnalytical string
= new StringAnalytical();
        str
= string.stringAnalytical("1aaa", '@');
        string.printString(str);
        str
= string.stringAnalytical("2aaa@", '@');
        string.printString(str);
        str
= string.stringAnalytical("@3aaa", '@');
        string.printString(str);
        str
= string.stringAnalytical("4aaa@bbb", '@');
        string.printString(str);
        str
= string.stringAnalytical("@5aaa@bbb", '@');
        string.printString(str);
        str
= string.stringAnalytical("6aaa@bbb@", '@');
        string.printString(str);
        str
= string.stringAnalytical("@7aaa@", '@');
        string.printString(str);
        str
= string.stringAnalytical("@8aaa@bbb@", '@');
        string.printString(str);
        str
= string.stringAnalytical("@9aaa@bbb@ccc", '@');
        string.printString(str);
        str
= string.stringAnalytical("@10aaa@bbb@ccc@eee", '@');
        string.printString(str);
    }
}

posted @ 2011-04-06 18:54 迷茫在java的世界里 阅读(361) | 评论 (0)编辑 收藏

java日期处理bean 转至csdn的afgasdg

     摘要: import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.regex.Pattern; import o...  阅读全文

posted @ 2011-04-06 18:52 迷茫在java的世界里 阅读(199) | 评论 (0)编辑 收藏

从 csdn看到的一些很有用的代码 灰常感谢afgasdg了 转帖请注明afgasdg

java访问xml文件
Java code

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class xmljava
{

public static void main(String args[])
    {   
          Element element
=null;
          File f
=new File("a.xml");
          DocumentBuilder db
=null;        //documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
          DocumentBuilderFactory dbf=null;
     
try{
        
          dbf
= DocumentBuilderFactory.newInstance(); //返回documentBuilderFactory对象  
          db =dbf.newDocumentBuilder();//返回db对象用documentBuilderFatory对象获得返回documentBuildr对象

          Document dt
= db.parse(f); //得到一个DOM并返回给document对象
          element = dt.getDocumentElement();//得到一个elment根元素
         
          System.out.println(
"根元素:"+element.getNodeName()); //获得根节点

        NodeList childNodes
=element.getChildNodes() ;    // 获得根元素下的子节点
   
     
for (int i = 0; i < childNodes.getLength(); i++)     // 遍历这些子节点

   {      
       Node node1
= childNodes.item(i); // childNodes.item(i); 获得每个对应位置i的结点

    
if ("Account".equals(node1.getNodeName()))
      {
                       
// 如果节点的名称为"Account",则输出Account元素属性type
      System.out.println("\r\n找到一篇账号. 所属区域: "   + node1.getAttributes().getNamedItem        ("type").getNodeValue() + ". ");
      NodeList nodeDetail
= node1.getChildNodes();   // 获得<Accounts>下的节点
      for (int j = 0; j < nodeDetail.getLength(); j++)
       {  
// 遍历<Accounts>下的节点
          Node detail = nodeDetail.item(j);    // 获得<Accounts>元素每一个节点
            if ("code".equals(detail.getNodeName()))   // 输出code
            System.out.println("卡号: " + detail.getTextContent());
            
else if ("pass".equals(detail.getNodeName())) // 输出pass
                System.out.println("密码: " + detail.getTextContent());
            
else if ("name".equals(detail.getNodeName())) // 输出name
                System.out.println("姓名: " + detail.getTextContent());
            
else if ("money".equals(detail.getNodeName())) // 输出money
                 System.out.println("余额: "+ detail.getTextContent());
     
        }
      }

    }
}

catch(Exception e){System.out.println(e);}
   
}
}


XML code
<?xml version="1.0" encoding="gbk"?> <Accounts> <Account type="by0003"> <code>100001</code> <pass>123</pass> <name>李四</name> <money>1000000.00</money> </Account> <Account type="hz0001"> <code>100002</code> <pass>123</pass> <name>张三</name> <money>1000.00</money> </Account> </Accounts>

posted @ 2011-04-06 18:49 迷茫在java的世界里 阅读(186) | 评论 (0)编辑 收藏

[转帖]在数组里随机取不重复的数

方法没有确认
import java.util.*;
public class Lottery {

    public static void main(String[] args) {
        int[] data1 = {3, 5, 6, 8, 9, 15, 18, 24, 27, 30, 32};
        Random r = new Random();
        int irdm = 0;
        for(int i = 0; i < 7; i ++) {
            irdm = r.nextInt(11 - i);
            System.out.println(data1[irdm]);
            for(int j = irdm; j < 11 - i - 1; j ++) {
                data1[j] = data1[j + 1];
            }
        }
    }
}
方法没有确认不知道是否可行public class AAAAA {
        public static void main(String[] args) {

                int i = 0;
                int j = 0;
                int[] temp = new int[20];
                for (j = 0; j < temp.length; j++) {
                        temp[j] = Math.random() * 100  + 1;
                        System.out.print(temp[j] + ",";
                }
                
                HashSet hh = new HashSet();
                while (hh.size() < 7) {
                        int aa = (int) (Math.random() * 100 + 1);
                        hh.add(aa);
                }
                System.out.println(hh.size());
                Iterator ii = hh.iterator();
                while (ii.hasNext()) {
                        System.out.print(ii.next() + ",";
                }
        }

}

java从指定数组中取不重复的7个随机数

如何用java从指定数组中取不重复的7个随机数,以下是我写的代码,但是是有重复的,哪位大侠赐教一下如何使用Random类的种子,帮我实现不重复的随机数。。。
import java.util.*;
public class Lottery {

    public static void main(String[] args)
    {
        int[] data1 = {3,5,6,8,9,15,18,24,27,30,32};
        Random   r=new   Random();
        StringBuffer   str1=new   StringBuffer();
        for(int   i=0;i<6;i++)
        {
        str1.append(data1[r.nextInt(11)]);
         }
         System.out.println(str1);
   }
}

posted @ 2011-01-31 16:57 迷茫在java的世界里 阅读(440) | 评论 (0)编辑 收藏

字符排序 很好用的代码

 char []a={'v','f',',','e','f'};
        Arrays.sort(a);
       
for(char b:a)
        {
            System.out.println(b);
        }

posted @ 2008-04-24 12:20 迷茫在java的世界里 阅读(139) | 评论 (0)编辑 收藏

MVNForumGlobal

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumGlobal.java,v 1.17 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.17 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package com.mvnforum;

public class MVNForumGlobal {

    private MVNForumGlobal() {
    }

/*************************************************************************
 * NOTE: below constants can be changed for each build,
 *       these constant MUST NOT break the compatibility
 *************************************************************************/
    public final static String IMAGE_DIR                 = "/mvnplugin/mvnforum/images";

    public final static String EMOTION_DIR               = "/mvnplugin/mvnforum/images/emotion/";

    public final static String CSS_FULLPATH              = "/mvnplugin/mvnforum/css/style.css";

    public final static String LOGO_FULLPATH             = "/mvnplugin/mvnforum/images/logo.gif";

    // Note that we cannot put / at the end because getRealPath will remove it in Tomcat 4.1.7 :((
    public final static String UPLOADED_AVATAR_DIR       = "/mvnplugin/mvnforum/upload/memberavatars";

    public final static String UPLOADED_COMPANY_DIR      = "/mvnplugin/mvnforum/upload/company";

    public final static String COMPANY_DEFAULT_CSS_PATH  = "/mvnplugin/mvnforum/upload/company/style.css";

    public final static String COMPANY_DEFAULT_LOGO_PATH = "/mvnplugin/mvnforum/upload/company/logo.gif";

    public final static String RESOURCE_BUNDLE_NAME      = "mvnForum_i18n";

    /** value to control the flood prevention. Note value from 0 to 999 is belong to mvnCore */
    public final static Integer FLOOD_ID_NEW_POST       = new Integer(1000);
    public final static Integer FLOOD_ID_NEW_MEMBER     = new Integer(1001);
    public final static Integer FLOOD_ID_LOGIN          = new Integer(1002);
    public final static Integer FLOOD_ID_NEW_MESSAGE    = new Integer(1003);

    /** The maximum length of the email in database */
    public final static int MAX_MEMBER_EMAIL_LENGTH = 60;

    /** The maximum length of the member login name in database */
    public final static int MAX_MEMBER_LOGIN_LENGTH = 30;

    public final static String TEMPLATE_SENDACTIVATECODE_PREFIX  = "sendactivemailtemplate";
    public final static String TEMPLATE_SENDACTIVATECODE_SUBJECT = "sendactivemailtemplate-subject.ftl";
    public final static String TEMPLATE_SENDACTIVATECODE_BODY    = "sendactivemailtemplate-body.ftl";

    public final static String TEMPLATE_FORGOTPASSWORD_PREFIX    = "forgotpasswordtemplate";
    public final static String TEMPLATE_FORGOTPASSWORD_SUBJECT   = "forgotpasswordtemplate-subject.ftl";
    public final static String TEMPLATE_FORGOTPASSWORD_BODY      = "forgotpasswordtemplate-body.ftl";

    public final static String TEMPLATE_WATCHMAIL_PREFIX         = "watchmailtemplate";
    public final static String TEMPLATE_WATCHMAIL_SUBJECT        = "watchmailtemplate-subject.ftl";
    public final static String TEMPLATE_WATCHMAIL_BODY           = "watchmailtemplate-body.ftl";

    // Constant for Company module
    public final static String COMPANY_GROUP_FREFIX              = "CompanyGroup: ";
}

posted @ 2007-09-11 11:33 迷茫在java的世界里 阅读(226) | 评论 (0)编辑 收藏

MVNForumFactoryConfig

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumFactoryConfig.java,v 1.12 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.12 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Luis Miguel Hernanz <luish@germinus.com>
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 */
package com.mvnforum;

import java.io.File;

import net.myvietnam.mvncore.configuration.DOM4JConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.myvietnam.mvncore.util.FileUtil;

/**
 * Class that loads and makes accesible the factory configuration.
 *
 * @author <a href="luish@germinus.com">Luis Miguel Hernanz</a>
 * @version $Revision: 1.12 $
 */
public class MVNForumFactoryConfig {

    private static Log log = LogFactory.getLog(MVNForumFactoryConfig.class);

    private static final String OPTION_FILE_NAME     = "mvnforum.xml";

    private static String authenticatorClassName     = null;
    private static String memberManagerClassName     = "com.mvnforum.db.jdbc.MemberDAOImplJDBC";
    private static String onlineUserFactoryClassName = "com.mvnforum.auth.OnlineUserFactoryImpl";
    private static String requestProcessorClassName  = "com.mvnforum.RequestProcessorDefault";
    private static String luceneAnalyzerClassName    = "org.apache.lucene.analysis.standard.StandardAnalyzer";

    public static String getMemberManagerClassName() {
        return memberManagerClassName;
    }

    public static String getOnlineUserFactoryClassName() {
        return onlineUserFactoryClassName;
    }

    public static String getAuthenticatorClassName() {
        return authenticatorClassName;
    }

    public static String getRequestProcessorClassName() {
        return requestProcessorClassName;
    }

    public static String getLuceneAnalyzerClassName() {
        return luceneAnalyzerClassName;
    }

    static {
        try {
            String strPathName      = FileUtil.getServletClassesPath();
            String configFilename   = strPathName + OPTION_FILE_NAME;
            DOM4JConfiguration conf = new DOM4JConfiguration(new File(configFilename));

            memberManagerClassName     = conf.getString("mvnforumfactoryconfig.member_implementation", memberManagerClassName);
            onlineUserFactoryClassName = conf.getString("mvnforumfactoryconfig.onlineuser_implementation", onlineUserFactoryClassName);
            authenticatorClassName     = conf.getString("mvnforumfactoryconfig.authenticator_implementation", authenticatorClassName);
            requestProcessorClassName  = conf.getString("mvnforumfactoryconfig.requestprocessor_implementation", requestProcessorClassName);
            luceneAnalyzerClassName    = conf.getString("mvnforumfactoryconfig.lucene_analyzer_implementation", luceneAnalyzerClassName);
        } catch (Exception e) {
            log.error("Error loading the factory properties", e);
        }
    }
}

posted @ 2007-09-11 11:32 迷茫在java的世界里 阅读(212) | 评论 (0)编辑 收藏

MVNForumContextListener

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumContextListener.java,v 1.6 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.6 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package com.mvnforum;

import java.sql.Timestamp;

import javax.servlet.*;

import net.myvietnam.mvncore.util.DateUtil;
import net.myvietnam.mvncore.util.FileUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MVNForumContextListener implements ServletContextListener {

    private static Log log = LogFactory.getLog(MVNForumContextListener.class);

    private static MVNForumContextListener instance;

    private Timestamp startTimestamp;

    /**
     * The servlet context with which we are associated.
     */
    private ServletContext context = null;

    public MVNForumContextListener() {
        instance = this;
    }


    /**
     * Notification that the web application is ready to process requests.
     *
     * @param event ServletContextEvent
     */
    public void contextInitialized(ServletContextEvent event) {
        log.debug("contextInitialized");

        this.context = event.getServletContext();

        String realPath = context.getRealPath("/WEB-INF/classes");// Add '/' before WEB-INF to fix the Oracle 10G bug
        FileUtil.setServletClassesPath(realPath);
        startTimestamp = DateUtil.getCurrentGMTTimestamp();
    }


    /**
     * Notification that the servlet context is about to be shut down.
     *
     * @param event ServletContextEvent
     */
    public void contextDestroyed(ServletContextEvent event) {
        log.debug("contextDestroyed");

        this.context = null;
        instance = null;
    }

    // below are add on method

    public static MVNForumContextListener getInstance() {
        return instance;
    }

    public Timestamp getStartTimestamp() {
        return startTimestamp;
    }

}

posted @ 2007-09-11 11:32 迷茫在java的世界里 阅读(199) | 评论 (0)编辑 收藏

MVNForumConstant

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumConstant.java,v 1.8 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.8 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 * @author: Igor Manic   imanic@users.sourceforge.net
 */
package com.mvnforum;

public final class MVNForumConstant {

    /** Cannot instantiate. */
    private MVNForumConstant() {
    }

/*************************************************************************
 * NOTE: below constants MUST NOT be changed IN ALL CASES,
 *       or it will break the compatibility
 *************************************************************************/

    /** Guest/anonymous site visitor. */
    public static final int MEMBER_ID_OF_GUEST             = 0;
    /** System administrator. */
    public static final int MEMBER_ID_OF_ADMIN             = 1;
    /**
     * The highest reserved MemberID.
     * All IDs from 0 through this value should not be used for "regular" members.
     */
    public static final int LAST_RESERVED_MEMBER_ID        = 1;
    /* IMPORTANT: When we have a group without group owner, GroupOwnerID is set to 0.
     * Similiar is for other IDs in the database - 0 means there is no reference.
     * Also, the other reason why MemberID=0 should not be used for Guest is
     * that DBMS could refuse to insert a record with 0 in that field, since it's
     * marked as non-null autoincrement primary key.
     */

    /** Unused GroupID. */
    public static final int GROUP_ID_UNUSED0               = 0;
    /**
     * Unused GroupID. In the previous versions of mvnForum it was used for some
     * special purposes, but should not be used anymore.
     */
    public static final int GROUP_ID_OF_GUEST              = 1;
    /** "Registered Members" virtual group. All members are listed in this group. */
    public static final int GROUP_ID_OF_REGISTERED_MEMBERS = 2;
    /**
     * The highest reserved GroupID.
     * All IDs from 0 through this value should not be used for "regular" groups.
     */
    public static final int LAST_RESERVED_GROUP_ID         = 2;

    /** "Inbox" message folder created by default for each member. */
    public static final String MESSAGE_FOLDER_INBOX        = "Inbox";
    /** "Sent" message folder created by default for each member. */
    public static final String MESSAGE_FOLDER_SENT         = "Sent";
    /** "Draft" message folder created by default for each member. */
    public static final String MESSAGE_FOLDER_DRAFT        = "Draft";
    /** "Trash" message folder created by default for each member. */
    public static final String MESSAGE_FOLDER_TRASH        = "Trash";

    public static final String dtdschemaDecl="<!DOCTYPE mvnforum SYSTEM \"http://www.mvnforum.com/dtd/mvnforum_1_0_rc2.dtd\">";

    public static final String VN_TYPER_MODE = "mvnforum.vntypermode";
}

posted @ 2007-09-11 11:31 迷茫在java的世界里 阅读(192) | 评论 (0)编辑 收藏

MVNForumConfig

     摘要: /*  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumConfig.java,v 1.75 2005/01/29 19:29:26 minhnn Exp $  * $Author: minhnn $  * $Revision: 1.75 $  * $Date: 2005/...  阅读全文

posted @ 2007-09-11 11:31 迷茫在java的世界里 阅读(519) | 评论 (0)编辑 收藏

ManagerFactory

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/ManagerFactory.java,v 1.6 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.6 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Luis Miguel Hernanz <luish@germinus.com>
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 */
package com.mvnforum;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mvnforum.auth.Authenticator;
import com.mvnforum.auth.OnlineUserFactory;

/**
 * Instance that returns the right implementation for the different
 * parts of the mvnforum system.
 *
 * @author <a href="luish@germinus.com">Luis Miguel Hernanz</a>
 * @version $Revision: 1.6 $
 */
// @todo : split this class to new class DAOFactory
public class ManagerFactory {

    private static Log log = LogFactory.getLog(ManagerFactory.class);

    /**
     * Creates a new <code>ManagerFactory</code> instance.
     */
    protected ManagerFactory() {}

    private static OnlineUserFactory onlineUserFactory = null;
    private static Authenticator authenticator = null;
    private static RequestProcessor requestProcessor = null;

    public static synchronized OnlineUserFactory getOnlineUserFactory() {
        if (onlineUserFactory == null) {
            try {
                Class c = Class.forName(MVNForumFactoryConfig.getOnlineUserFactoryClassName());
                onlineUserFactory = (OnlineUserFactory) c.newInstance();
                log.info("onlineUserFactory = " + onlineUserFactory);
            } catch (Exception e) {
                log.error("Error returning the online user factory.", e);
                throw new RuntimeException(e.getMessage());
            }
        }
        return onlineUserFactory;
    }

    public static synchronized Authenticator getAuthenticator() {
        try {
            String authenticatorClass = MVNForumFactoryConfig.getAuthenticatorClassName();
            if ((null != authenticatorClass) && !authenticatorClass.trim().equals("")) {
                log.debug("Using the authenticator: " + authenticatorClass);
                if (authenticator == null) {
                    Class c = Class.forName(authenticatorClass);
                    authenticator = (Authenticator) c.newInstance();
                    log.info("authenticator = " + authenticator);
                }
                return authenticator;
            }
        } catch (Exception e){
            log.error("Error getting the authentication object", e);
        }
        return null;
    }

    public static synchronized RequestProcessor getRequestProcessor() {
        if (requestProcessor == null) {
            try {
                Class c = Class.forName(MVNForumFactoryConfig.getRequestProcessorClassName());
                requestProcessor = (RequestProcessor) c.newInstance();
                log.info("requestProcessor = " + requestProcessor);
            } catch (Exception e) {
                // This should never happen
                log.error("Error returning the requestProcessor.", e);
                throw new RuntimeException(e.getMessage());
            }
        }
        return requestProcessor;
    }
}

posted @ 2007-09-11 11:30 迷茫在java的世界里 阅读(155) | 评论 (0)编辑 收藏

URLMap

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/URLMap.java,v 1.3 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.3 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package com.mvnforum;

public class URLMap {
    private String response = null;

    public URLMap() {
    }

    public void setResponse(String newvalue) {
        response = newvalue;
    }

    public String getResponse() {
        return response;
    }
}

posted @ 2007-09-11 11:29 迷茫在java的世界里 阅读(169) | 评论 (0)编辑 收藏

RequestProcessorDefault

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/RequestProcessorDefault.java,v 1.3 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.3 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Luis Miguel Hernanz <luish@germinus.com>
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 */
package com.mvnforum;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Empty implementation of the RequestProcessor interface.
 *
 * @author <a href="luish@germinus.com">Luis Miguel Hernanz</a>
 * @version $Revision: 1.3 $
 */
public class RequestProcessorDefault implements RequestProcessor {

    private static Log log = LogFactory.getLog(RequestProcessorDefault.class);

    /**
     * This is the first method called in the request processing. This
     * method returns always <code>null</code>.
     *
     * @param request a <code>HttpServletRequest</code> value
     * @param response a <code>HttpServletResponse</code> value
     */
    public String preLogin(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e){
            log.warn("Error setting the character encoding from the request", e);
        }
        return null;
    }

    /**
     * The method receives the user request just before the
     * authentication has been checked. This method always returns
     * <code>null</code>.
     *
     * @param request a <code>HttpServletRequest</code> value
     * @param response a <code>HttpServletResponse</code> value
     */
    public String preProcess(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    /**
     * This method is called just before the call to the final request
     * dispatcher forward. This method always returns
     * <code>responseURI</code>.
     *
     * @param request a <code>HttpServletRequest</code> value
     * @param response a <code>HttpServletResponse</code> value
     * @param responseURI the path to which the control will be
     * forwarded after this method has finished.
     */
    public String postProcess(HttpServletRequest request, HttpServletResponse response, String responseURI) {
        return responseURI;
    }
}

posted @ 2007-09-11 11:29 迷茫在java的世界里 阅读(111) | 评论 (0)编辑 收藏

RequestProcessor

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/RequestProcessor.java,v 1.3 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.3 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Luis Miguel Hernanz <luish@germinus.com>
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 */
package com.mvnforum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Interface to hook additional preprocessing to the user request.
 * This interface is meatn as extension points to ease the integration
 * of the forum system with external systems.
 *
 * @author <a href="luish@germinus.com">Luis Miguel Hernanz</a>
 * @version $Revision: 1.3 $
 */
public interface RequestProcessor {

    /**
     * This is the first method called in the request processing.
     *
     * @param request a <code>HttpServletRequest</code> value
     * @param response a <code>HttpServletResponse</code> value
     * @return the new responseURI to redirect to. The control will be
     * forwarded to this page (if responseURI is an jsp). No furher
     * processing will take place.
     */
    public String preLogin(HttpServletRequest request, HttpServletResponse response);

    /**
     * The method receives teh user request just before the
     * authentication has been checked.
     *
     * @param request a <code>HttpServletRequest</code> value
     * @param response a <code>HttpServletResponse</code> value
     * @return the new responseURI to redirect to.
     */
    public String preProcess(HttpServletRequest request, HttpServletResponse response);

    /**
     * This method is called just before the call to the final request
     * dispatcher forward.
     *
     * @param request a <code>HttpServletRequest</code> value
     * @param response a <code>HttpServletResponse</code> value
     * @param responseURI the path to which the control will be
     * forwarded after this method has finished.
     * @return the new responseURI to redirect to.
     */
    public String postProcess(HttpServletRequest request, HttpServletResponse response, String responseURI);

}

posted @ 2007-09-11 11:28 迷茫在java的世界里 阅读(127) | 评论 (0)编辑 收藏

MyUtil

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MyUtil.java,v 1.30 2005/01/29 11:58:09 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.30 $
 * $Date: 2005/01/29 11:58:09 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package com.mvnforum;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

import javax.servlet.ServletContext;
import javax.servlet.http.*;

import com.mvnforum.auth.*;
import com.mvnforum.common.PrivateMessageUtil;
import com.mvnforum.db.*;
import com.mvnforum.search.member.MemberIndexer;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import net.myvietnam.mvncore.MVNCoreInfo;
import net.myvietnam.mvncore.exception.*;
import net.myvietnam.mvncore.filter.*;
import net.myvietnam.mvncore.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyUtil {

    private static Log log = LogFactory.getLog(MyUtil.class);

    private static RankCache rankCache = RankCache.getInstance();

    public static String filter(String input, boolean enableHTML, boolean enableEmotion,
                                boolean enableMVNCode, boolean enableNewLine, boolean enableURL) {
        String output = input;

        if (enableHTML) {
            output = EnableHtmlTagFilter.filter(output);
        } else {
            output = DisableHtmlTagFilter.filter(output);
        }

        if (enableEmotion) {
            output = EnableEmotionFilter.filter(output, ParamUtil.getContextPath() + MVNForumGlobal.EMOTION_DIR);
        }

        if (enableMVNCode) {
            output = EnableMVNCodeFilter.filter(output);
        }

        if (enableNewLine) {
            output = HtmlNewLineFilter.filter(output);
        }

        if (enableURL) {
            output = URLFilter.filter(output);
        }
        return output;
    }

    public static String getMemberTitle(int postCount) {
        String title = "";
        try {
            ArrayList rankBeans = rankCache.getBeans();
            for (int i = 0; i < rankBeans.size(); i++) {
                RankBean rankBean = (RankBean)rankBeans.get(i);
                if (rankBean.getRankMinPosts() <= postCount) {
                    title = EnableMVNCodeFilter.filter(rankBean.getRankTitle());
                } else {
                    break;
                }
            }//for
        } catch (Exception ex) {
            log.error("Exception in getMemberTitile", ex);
        }
        return title;
    }

    public static String getForumIconName(long lastLogon, long lastPost) {
        String forumIcon = null;
        if (lastLogon > lastPost) {// no new post
            forumIcon = "f_norm_no.gif";
        } else {// new post
            forumIcon = "f_norm_new.gif";
        }
        return forumIcon;
    }

    public static String getThreadIconName(long lastLogon, long lastPost, int postCount) {
        String threadIcon = null;
        if (postCount < MVNForumConfig.getHotTopicThreshold()) {//not hot topic
            if (lastLogon > lastPost) {// no new post
                threadIcon = "f_norm_no.gif";
            } else {// new post
                threadIcon = "f_norm_new.gif";
            }
        } else {// hot topic
            if (lastLogon > lastPost) {// no new post
                threadIcon = "f_hot_no.gif";
            } else {// new post
                threadIcon = "f_hot_new.gif";
            }
        }
        return threadIcon;
    }

    public static String getThreadStatusName(Locale locale, int threadStatus) {
        String result = null;
        switch (threadStatus) {
        case ThreadBean.THREAD_STATUS_DEFAULT:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.normal");
            break;
        case ThreadBean.THREAD_STATUS_DISABLED:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.disabled");
            break;
        case ThreadBean.THREAD_STATUS_LOCKED:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.locked");
            break;
        case ThreadBean.THREAD_STATUS_CLOSED:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.closed");
            break;
        default:
            //throw new AssertionException("Cannot find matching thread status.");
        }
        return result;
    }

    public static String getThreadTypeName(Locale locale, int threadType) {
        String result = "Unknown";
        switch (threadType) {
        case ThreadBean.THREAD_TYPE_DEFAULT:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.normal_thread");
            break;
        case ThreadBean.THREAD_TYPE_STICKY:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.sticky_thread");
            break;
        case ThreadBean.THREAD_TYPE_FORUM_ANNOUNCEMENT:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.announcement_thread");
            break;
        case ThreadBean.THREAD_TYPE_GLOBAL_ANNOUNCEMENT:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.global_announcement_thread");
            break;
        default:
            //throw new AssertionException("Cannot find matching thread type.");
        }
        return result;
    }

    public static String getForumStatusName(Locale locale, int forumStatus) {
        String result = null;
        switch (forumStatus) {
        case ForumBean.FORUM_STATUS_DEFAULT:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.normal");
            break;
        case ForumBean.FORUM_STATUS_DISABLED:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.disabled");
            break;
        case ForumBean.FORUM_STATUS_LOCKED:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.locked");
            break;
        case ForumBean.FORUM_STATUS_CLOSED:
            result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.closed");
            break;
        default:
            //throw new AssertionException("Cannot find matching forum status.");
        }
        return result;
    }

    public static boolean canViewAnyForumInCategory(int categoryID, MVNForumPermission permission) {
        try {
            Collection forumBeans = ForumCache.getInstance().getBeans();
            for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
                ForumBean forumBean = (ForumBean)iter.next();
                if (forumBean.getCategoryID() == categoryID) {
                    if (canViewForum(forumBean, permission)) {
                        return true;
                    }
                }
            }
        } catch (DatabaseException ex) {
            log.error("Cannot load the data in table Forum", ex);
        }
        return false;
    }

    public static boolean canViewForum(ForumBean forumBean, MVNForumPermission permission) {
        if (permission.canReadPost(forumBean.getForumID()) &&
            (forumBean.getForumStatus() != ForumBean.FORUM_STATUS_DISABLED) ) {
            return true;
        }
        return false;
    }

    public static int getViewablePosts(Collection forumBeans, MVNForumPermission permission) {
        int count = 0;
        for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
            ForumBean forumBean = (ForumBean)iter.next();
            if (canViewForum(forumBean, permission)) {
                count += forumBean.getForumPostCount();
            }
        }
        return count;
    }

    public static int getViewableThreads(Collection forumBeans, MVNForumPermission permission) {
        int count = 0;
        for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
            ForumBean forumBean = (ForumBean)iter.next();
            if (canViewForum(forumBean, permission)) {
                count += forumBean.getForumThreadCount();
            }
        }
        return count;
    }

    public static int getViewableForums(Collection forumBeans, MVNForumPermission permission) {
        int count = 0;
        for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
            ForumBean forumBean = (ForumBean)iter.next();
            if (canViewForum(forumBean, permission)) {
                count++;
            }
        }
        return count;
    }

    public static int getViewableCategories(Collection categoryBeans, MVNForumPermission permission) {
        int count = 0;
        for (Iterator iter = categoryBeans.iterator(); iter.hasNext(); ) {
            CategoryBean categoryBean = (CategoryBean)iter.next();
            if (canViewAnyForumInCategory(categoryBean.getCategoryID(), permission)) {
                count++;
            }
        }
        return count;
    }

    /**
     * Get the String with a slash character '/' before the locale name
     * @param localeName the user's preferred locale
     * @return the String with a slash character '/' before the locale name if
     *         this locale is configed to support it. Otherwise,
     *         an empty String will be return
     */
    public static String getLocaleNameAndSlash(String localeName) {
        if ( (localeName == null) || (localeName.length() == 0) ) {
            return "";
        }

        String retValue = "";
        String[] supportedLocales = MVNForumConfig.getSupportedLocaleNames();

        if (supportedLocales == null) {
            log.error("Assertion in MyUtil.getLocaleNameAndSlash. Please check your configuration.");
            return "";
        }

        for (int i = 0; i < supportedLocales.length; i++) {
            if (localeName.equals(supportedLocales[i])) {
                retValue = "/" + localeName;
                break;
            }
        }
        return retValue;
    }

    public static String getCompanyCssPath(CompanyBean companyBean, String contextPath) {
        String cssPath = null;
        if (companyBean.getCompanyCss().length() > 0) {
            cssPath = companyBean.getCompanyCss();
        } else {
            // use default company css
            cssPath = MVNForumGlobal.COMPANY_DEFAULT_CSS_PATH;
        }
        return contextPath + cssPath;
    }

    public static String getCompanyLogoPath(CompanyBean companyBean, String contextPath) {
        String logoPath = null;
        if (companyBean.getCompanyLogo().length() > 0) {
            logoPath = companyBean.getCompanyLogo();
        } else {
            // use default company logo
            logoPath = MVNForumGlobal.COMPANY_DEFAULT_LOGO_PATH;
        }
        return contextPath + logoPath;
    }

    /**
     * Get the locale from locale name
     * @param localeName : in this format la_CO_VA, eg. en_US
     * @return the locale instance of the localeName
     */
    public static Locale getLocale(String localeName) {
        // now, find out the 3 elements of a locale: language, country, variant
        String[] localeElement = StringUtil.getStringArray(localeName, "_");
        String language = "";
        String country = "";
        String variant = "";
        if (localeElement.length >= 1) {
            language = localeElement[0];
        }
        if (localeElement.length >= 2) {
            country = localeElement[1];
        }
        if (localeElement.length >= 3) {
            variant = localeElement[2];
        }
        return new Locale(language, country, variant);
    }

    public static void ensureCorrectCurrentPassword(HttpServletRequest request)
        throws BadInputException, AssertionException, DatabaseException, AuthenticationException {

        OnlineUser onlineUser = OnlineUserManager.getInstance().getOnlineUser(request);
        OnlineUserFactory onlineUserFactory = ManagerFactory.getOnlineUserFactory();

        try {
            if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_REALM) {
                onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_REALM, true);
            } else if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_CUSTOMIZATION) {
                if(MVNForumConfig.getEnablePasswordlessAuth()) {
                    // dont need password
                    onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
                } else {
                    // must have password
                    // @todo: implement this case by using Authenticator
                    onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
                }
            } else {
                //This user did not login by REALM or CUSTOMIZATION
                String memberPassword = "";
                String memberPasswordMD5 = ParamUtil.getParameter(request, "md5pw", false);
                if (memberPasswordMD5.length() == 0 || (memberPasswordMD5.endsWith("==") == false)) {
                    // md5 is not valid, try to use unencoded password method
                    memberPassword = ParamUtil.getParameterPassword(request, "MemberCurrentMatkhau", 3, 0);
                }

                if (memberPassword.length() > 0) {
                    // that is we cannot find the md5 password
                    onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), memberPassword, false);
                } else {
                    // have the md5, go ahead
                    onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), memberPasswordMD5, true);
                }
            }
        } catch (AuthenticationException e) {
            Locale locale = I18nUtil.getLocaleInRequest(request);
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_password");
            throw new BadInputException(localizedMessage);
            //throw new BadInputException("You have typed the wrong password. Cannot proceed.");
        }
    }

    public static void writeMvnForumImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

        BufferedImage image = MVNForumInfo.getImage();
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
            encoder.encode(image);

            outputStream.flush();
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) { }
            }
        }
    }

    public static void writeMvnCoreImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

        BufferedImage image = MVNCoreInfo.getImage();
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
            encoder.encode(image);

            outputStream.flush();
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) { }
            }
        }
    }

    public static void checkClassName(Locale locale, String className, boolean required) throws BadInputException {
        if (required == false) {
            if (className.length() == 0) return;
        }

        try {
            Class.forName(className);
        } catch (ClassNotFoundException ex) {
            throw new BadInputException("Cannot load class: " + className);
        }
    }

    public static void saveVNTyperMode(HttpServletRequest request, HttpServletResponse response) {
        String vnTyperMode = ParamUtil.getParameter(request, "vnselector");
        if (vnTyperMode.equals("VNI") || vnTyperMode.equals("TELEX") ||
            vnTyperMode.equals("VIQR") || vnTyperMode.equals("NOVN")) {
            Cookie typerModeCookie = new Cookie(MVNForumConstant.VN_TYPER_MODE, vnTyperMode);
            typerModeCookie.setPath("/");
            response.addCookie(typerModeCookie);
        }
    }

    public static Hashtable checkMembers(String[] memberNames, Locale locale)
        throws AssertionException, DatabaseException, BadInputException {

        Hashtable memberMap = new Hashtable();
        boolean isFailed = false;
        StringBuffer missingNames = new StringBuffer(512);

        for (int i = 0; i < memberNames.length; i++) {
            int receivedMemberID = -1;
            String memberName = memberNames[i];
            StringUtil.checkGoodName(memberName);
            try {
                receivedMemberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
            } catch (ObjectNotFoundException ex) {
                isFailed = true;
                if (missingNames.length() > 0) {
                    missingNames.append(", ");
                }
                missingNames.append(memberName);
                continue;
            }
            memberMap.put(new Integer(receivedMemberID), memberName);
        } // end for

        if (isFailed) { // the receivers does not exist.
            String localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.receivers_are_not_members", new Object[] {missingNames});
            throw new BadInputException(localizedMessage);
        }
        return memberMap;
    }
}

 

posted @ 2007-09-11 11:27 迷茫在java的世界里 阅读(265) | 评论 (0)编辑 收藏

MVNForumResourceBundle

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumResourceBundle.java,v 1.6 2005/01/18 11:52:08 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.6 $
 * $Date: 2005/01/18 11:52:08 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Pavel Av
 */
package com.mvnforum;

import java.util.Locale;
import java.util.ResourceBundle;

import net.myvietnam.mvncore.i18n.CacheResourceBundle;

public class MVNForumResourceBundle {

    private static CacheResourceBundle cacheResourceBundle = new CacheResourceBundle(MVNForumGlobal.RESOURCE_BUNDLE_NAME);

    private MVNForumResourceBundle() {
    }

    public static ResourceBundle getResourceBundle(Locale locale) {
        return cacheResourceBundle.getResourceBundle(locale);
    }

    public static String getString(Locale locale, String key) {
        return cacheResourceBundle.getString(locale, key);
    }

    public static String getString(Locale locale, String key, Object[] args) {
        return cacheResourceBundle.getString(locale, key, args);
    }
}

posted @ 2007-09-11 11:26 迷茫在java的世界里 阅读(138) | 评论 (0)编辑 收藏

MVNForumInfo

 

/*
 * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MVNForumInfo.java,v 1.36.2.2 2005/06/17 17:53:37 minhnn Exp $
 * $Author: minhnn $
 * $Revision: 1.36.2.2 $
 * $Date: 2005/06/17 17:53:37 $
 *
 * ====================================================================
 *
 * Copyright (C) 2002-2005 by MyVietnam.net
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * All copyright notices regarding mvnForum MUST remain intact
 * in the scripts and in the outputted HTML.
 * The "powered by" text/logo with a link back to
 * http://www.mvnForum.com and http://www.MyVietnam.net in the
 * footer of the pages MUST remain visible when the pages
 * are viewed on the internet or intranet.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * Support can be obtained from support forums at:
 * http://www.mvnForum.com/mvnforum/index
 *
 * Correspondence and Marketing Questions can be sent to:
 * info@MyVietnam.net
 *
 * @author: Minh Nguyen  minhnn@MyVietnam.net
 * @author: Mai  Nguyen  mai.nh@MyVietnam.net
 */
package com.mvnforum;

import java.awt.*;
import java.awt.image.BufferedImage;

public class MVNForumInfo {

    private MVNForumInfo() {
    }

    private static String PRODUCT_NAME         = "mvnForum";

    private static String PRODUCT_DESC         = "mvnForum 1.0.0 RC4 Update 4";

    private static String PRODUCT_VERSION      = "1.0.0-RC4_04";

    private static String PRODUCT_RELEASE_DATE = "18 June 2005";

    private static String PRODUCT_HOMEPAGE     = "http://www.mvnForum.com";

    public static String getProductName() {
        return PRODUCT_NAME;
    }

    public static String getProductDesc() {
        return PRODUCT_DESC;
    }

    public static String getProductVersion() {
        return PRODUCT_VERSION;
    }

    public static String getProductReleaseDate() {
        return PRODUCT_RELEASE_DATE;
    }

    public static String getProductHomepage() {
        return PRODUCT_HOMEPAGE;
    }

    public static BufferedImage getImage() {

        String str = PRODUCT_VERSION + " on " + PRODUCT_RELEASE_DATE;
        int IMAGE_WIDTH  = 250;
        int IMAGE_HEIGHT = 30;

        BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.setBackground(Color.blue);
        g.setColor(Color.white);
        g.draw3DRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, false);
        FontMetrics fontMetrics = g.getFontMetrics();
        int strWidth  = fontMetrics.stringWidth(str);
        int strHeight = fontMetrics.getAscent() + fontMetrics.getDescent();
        g.drawString(str, (IMAGE_WIDTH - strWidth) / 2, IMAGE_HEIGHT - ((IMAGE_HEIGHT - strHeight) / 2) - fontMetrics.getDescent());
        g.dispose(); // free resource
        return bufferedImage;
    }

}

posted @ 2007-09-11 11:22 迷茫在java的世界里| 编辑 收藏

六章 复用类

      代码的复用有两种方法————1就是直接在新类中生成旧有的类的对象 (合成)2是创建一个新的类 这个类会全盘接受旧有的类 并且在不对旧有类修改的前提下 添加新的代码(继承)
      合成所使用的方法
      只要把对象的引用reference放到新的类里面就可以了。当primitive数据作为类的成员时候会自动初始化为零,对象的reference也会为null,这时候调用这个reference会抛出nullpoint异常。
   reference的初始化有以下三种方式:
   1 在定义对象的时候。这就意味着在调用构造函数之前,他们已经初始化完毕了。
   2在这个类的构造函数里。
   3在即将使用那个对象之前。如果碰到创建对象的代价很高,或者不是每次都需要创建对象的时候,这种做法就能降低程序的开销。
      继承所使用的方法
      继承的时候 必须使用extends关键词和基类的名字。之后新类就会自动获得基类的全部成员和方法。继承不会限定只能使用基类的方法。也可以往派生类里加入新的方法。
      基类的初始化
      当创建一个派生类的对象的时候,这个对象立门还有一个基类的对象。这个对象同基类自己创建的对象没有任何的差别。只是从外面看来这个对象是被包裹在派生类的对象里面。
      基类的初始化只有一个方法能保证:调用基类的构造函数来进行初始化,只有这样才能掌握怎样才能正确地进行初始化的信息和权限。java会让派生类的构造函数自动地调用基类的构造函数。
      带参数的构造函数
      调用带参数的构造函数必须使用super关键词以及合适的参数明确调用基类的构造函数。
      确保进行妥善地清理
      一般情况下java会将需要清理的对象留给垃圾回收器去处理,它不会主动的进行清理。由于不知道垃圾回收器甚么时候启动,也不知道会不会启动,所有需要进行清理,就必须明确地写一个专门干这件事情的方法,为了应付异常,还要将这个方法放入finally子句里面去。不要去调用finalize方法。
      用合成还是继承
      一般来说,合成用于新类要使用旧类的功能,而不是其接口的场合,也就是说把对象嵌进去,用它来实现新类的功能,但用户看到的是新类的接口,而不是嵌进去的对象的接口,因此在新类里嵌入private的旧类对象,有时为了让用户直接访问新类的各个组成部分也可以嵌入public的旧类对象。通常都应该将基类的成员数据定义为privite类型。继承表达的是一种“是(is-a)”关系,合成表达的是“有(has-a)”关系,对于一些需要对外部世界隐藏,但要对它的继承类开放的基类 可以使用protected来定义那些开放的部分。最好的做法是,将数据成员设成private 的;你应该永远保留修改底层实现的权利。然后用protected 权限的方法来控制继承类的访问权限。
      渐进式的开发
      继承的优点之一就是,它支持渐进式的开发(incremental develop)。添加新的代码的时候,不会给老代码带来bug;实际上新的bug 全都被圈在新代码里。通过继承已有的,已经能正常工作的类,然后再添加一些数据成员和方法(以及重新定义一些原有的方法),你可以不去修改那些可能还有人在用的老代码,因而也就不会造成bug 了。一旦发现了bug,你就知道它肯定是在新代码里。相比要去修改老代码,新代码会短很多,读起来也更简单。继承实质上是在表达这样一种关系:“新的类是一种旧的类”。
      上传
       继承最重要的特征不在于它为新类提供了方法,而是它表达了新类同基类之间的关系。这种关系可以被归纳为一句话“新类就是一种原有的类。” (upcasting)”。上传总是安全的,因为你是把一个较具体的类型转换成较为一般的类型。也就是说派生类是基类的超集(superset)。它可能会有一些基类所没有的方法,但是它最少要有基类的方法。在上传过程中,类的接口只会减小,不会增大。这就是为什么编译器会允许你不作任何明确的类型转换或特殊表示就进行上传的原因了。
      合成还是继承,再探讨
      在判断该使用合成还是继承的时候,有一个最简单的办法,就是问一下你是不是会把新类上传给基类。如果你必须上传,那么继承就是必须的,如果不需要上传,那么就该再看看是不是应该用继承了。
      final 关键词
      final 的三种用途:数据(data),方法(method)和类(class)。
Final 的数据
      很多编程语言都有通知编译器“这是段『常量(constant)』 数据”的手段。常量能用于下列两种情况:
1. 可以是“编译时的常量(compile-time constant)”,这样就再也不能改了。
2. 也可以是运行时初始化的值,这个值你以后就不想再改了。
如果是编译时的常量,编译器会把常量放到算式里面;这样编译的时候就能进行计算,因此也就降低了运行时的开销。在Java 中这种常量必须是primitive 型的,而且要用final 关键词表示。这种常量的赋值必须在定义的时候进行。
       一个既是static 又是final 的数据成员会只占据一段内存,并且不可修改。
      当final 不是指primitive,而是用于对象的reference 的时候,意思就有点搞了。对primitive 来说,final 会将这个值定义成常量,但是对于对象的reference 而言,final 的意思则是这个reference 是常量。初始化的时候,一旦将reference 连到了某个对象,那么它就再也不能指别的对象了。但是这个对象本身是可以修改的;Java 没有提供将某个对象作成常量的方法。(但是你可以自己写一个类,这样就能把类当做常量了。)这种局限性也体现在数组上,因为它也是一个对象。
      空白的final 数据 (Blank finals)
      Java 能让你创建“空白的final 数据(blank finals)”,也就是说把数据成员声明成final 的,但却没给初始化的值。碰到这种情况,你必须先进行初始化,再使用空白的final 数据成员,而且编译器会强制你这么做。不过,空白的final 数据也提供了一种更为灵活的运用final 关键词方法,比方说,现在对象里的final 数据就能在保持不变性的同时又有所不同了。
      你一定得为final 数据赋值,要么是在定义数据的时候用一个表达式赋值,要么是在构造函数里面进行赋值。为了确保final 数据在使用之前已经进行了初始化,这一要求是强制性的。
      Final 的参数
      Java 允许你在参数表中声明参数是final 的,这样参数也编程final了。也就是说,你不能在方法里让参数reference 指向另一个对象了。
      Final 方法
使用final 方法的目的有二。第一,为方法上“锁”,禁止派生类进行修改。这是出于设计考虑。当你希望某个方法的功能,能在继承过程中被保留下来,并且不被覆写,就可以使用这个方法。
第二个原因就是效率。如果方法是final 的,那么编译器就会把调用转换成“内联的(inline)”。当编译器看到要调用final 方法的时候,它就会(根据判断)舍弃普通的,“插入方法调用代码的”编译机制(将参数压入栈,然后跳去执行要调用的方法的代码,再跳回来清空栈,再处理返回值),相反它会用方法本身的拷贝来代替方法的调用。当然如果方法很大,那么程序就会膨胀得很快,于是内联也不会带来什么性能的改善,因为这种改善相比程序处理所耗用的时间是微不足道的。Java 的设计者们暗示过,Java 的编译器有这个功能,可以智能地判断是不是应该将final 方法做成内联的。不过,最好还是把效率问题留给编译器和JVM去处理,而只把final 用于要明确地禁止覆写的场合。
final 和private
private 方法都隐含有final 的意思。由于你不能访问private 的方法,因此你也不能覆写它。你可以给private 方法加一个final 修饰符,但是这样做什么意义也没有。这个问题有可能会造成混乱,因为即使你覆写了一个private 方法(它隐含有final 的意思),看上去它还是可以运行的,而且编译器也不会报错。
      只有是基类接口里的东西才能被“覆写”。也就是说,对象应该可以被上传到基类,然后再调用同一个方法(这一点要到下一章才能讲得更清楚。)如果方法是private 的,那它就不属于基类的接口。它只能算是被类隐藏起来的,正好有着相同的名字的代码。如果你在派生类里创建了同名的public 或protected,或package 权限的方法,那么它们同基类中可能同名的方法,没有任何联系。你并没有覆写那个方法,你只是创建了一个新的方法。由于private 方法是无法访问的,实际上是看不见的,因此这么作除了会影响类的代码结构,其它什么意义都没有。
      Final 类
      把整个类都定义成final 的(把final 关键词放到类的定义部分的前面)就等于在宣布,你不会去继承这个类,你也不允许别人去继承这个类。换言之,出于类的设计考虑,它再也不需要作修改了,或者从安全角度出发,你不希望它再生出子类。
      注意,final 类的数据可以是final 的,也可以不是final 的,这要由你来决定。无论类是不是final 的,这一条都适用于“将final 用于数据的”场合。但是,由于final 类禁止了继承,覆写方法已经不可能了,因此所有的方法都隐含地变成final 了。你可以为final 类的方法加一个final 修饰符,但是这一样没什么意义。
      小心使用final
      看来,设计类的时候将方法定义成final 的,会是一个很明智的决定。可能你会觉得没人会要覆写你的方法。有时确实是这样。

posted @ 2007-06-28 19:20 迷茫在java的世界里 阅读(182) | 评论 (0)编辑 收藏

第五章 隐藏实现

      本章主要是介绍如何对代码进行封装,并解释为什么类库中有些部分会被公之于众,有些部分被隐藏的起来:类库创建时保证在不影响类库使用者代码的前提下对类库进行修改和改进,在对类库进行修改的时候不能删减现有方法,对于那些只有类内部实现有关的,不应该会使用的部分进行封装,限制用户使用这部分代码,便于类库创建者对类库进行修改,这就是java提供的访问控制符 access specifier ,public protected package private 
      使用import导入一个完整的类或类库。package的名称是独一无二的 ,不要import两个同名的类否则会引起冲突
      java的访问控制符:类只能被定义public 或 package(默认的没有定义访问控制符的),而类内部数据成员和方法 被定义public的可以被任何类都能访问,被定义protected的数据成员或方法只能被该类的子类访问,定义package的数据成员或方法只能被同一目录下的类访问,private的成员或方法只能被类的内部数据成员或方法访问。
      类的访问权限:每个编译单元只能有一个public类,只是为了保证每个编译单元只能有一个公共接口,可以根据需要往这个编译单元里添加package权限的类,public的类必须和这个编译单元一样的文件名      

posted @ 2007-06-25 18:43 迷茫在java的世界里| 编辑 收藏

Eclipse与插件(tomcatPlugin Lomboz easyStruts)安装

一、安装准备 

在进行安装以前,你应该准备以下软件: 

 软件:J2se 
 版本:1.4.2_04 
 官方下载:http://java.sun.com/j2se/1.4.2/download.html 
 备注: 
  
 软件:Tomcat 
 版本:5.0.19 
 官方下载:http://www.apache.org/dist/jakarta/ 
 备注: 
  
 软件:Struts 
 版本:1.1 
 官方下载:http://www.apache.org/dist/jakarta/struts/ 
 备注: 
  
 软件:Eclipse 
 版本:2.1.3 
 官方下载:http://www.eclipse.org/downloads/index.php 
 备注:目前eclipse最新版为eclipse3.0R1 

 软件:EclipseLanguagePack 
 版本:2.1.2.1 
 官方下载:http://www.eclipse.org/downloads/index.php 
 备注:该版本只能汉化eclipse2.1.3及以下版本 

 软件:TomcatPlugin 
 版本:2.2.1 
 官方下载:http://www.sysdeo.com/eclipse/tomcatPlugin.html 
 备注:该版本只能汉化eclipse2.1.3及以下版本 
  
 软件:Lomboz 
 版本:2.1.3 
 官方下载:http://www.objectlearn.com/index.jsp 
 备注:该版本只能汉化eclipse2.1.3及以下版本 

 软件:EasyStruts 
 版本:0.6.4 
 官方下载:http://sourceforge.net/projects/easystruts 
 备注:该版本只能汉化eclipse2.1.3及以下版本 
  

以上软件版本为安装成功的版本,为了使您的安装不至于出错请遵照以上版本准本软件。 

hodesoft公司内部员工可以访问\\192.168.0.23获取 

如果要找其他eclipse插件可以去下面这个站点 
http://www.eclipse-plugins.info 
  

二、JDK安装 

1.安装J2SE-SDK到E:\j2sdk1.4.2 

       部分目录结构如下: 

              E:\j2sdk1.4.2\in 

              E:\j2sdk1.4.2\lib 

              E:\j2sdk1.4.2\jre 

                     ... 

2.配置环境变量如下: 

JAVA_HOME = E:\j2sdk1.4.2 

              PATH = %JAVA_HOME%\in;.;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib; 

              CLASSPATH = .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib; 

  

三、Tomcat安装 

1.解压jakarta-tomcat-5.0.19.zip到E:\tomcat 

       部分目录结构如下: 

              E:\tomcat\in 

              E:\tomcat\conf 

              E:\tomcat\webapps 

                     ... 

2.配置环境变量如下: 

TOMCAT_HOME = E:\tomcat 

  

四、Struts安装 

1.解压jakarta-struts-1.1.zip到E:\jakarta-struts-1.1 

       部分目录结构如下: 

              E:\jakarta-struts-1.1\lib 

              E:\jakarta-struts-1.1\webapps 

                     ... 

五、Eclipse安装 

1.解压eclipse-SDK-2.1.3-win32.zip到E:\eclipse213 

       部分目录结构如下: 

              E:\eclipse213\features 

              E:\eclipse213\plugins 

                     ... 

2.启动Eclipse,看看安装是否成功 

       如果启动不成功,请查看JRE是否安装 

3.启动Eclipse,点击菜单 windows->preferences 在左边树中点击展开java,选择Installed JREs, 

如果Installed JREs如下则正确: 

 JRE Type:Standard VM 
 Name:j2sdk1.4.2 
 Location:E:\j2sdk1.4.2 


六、Eclipse汉化 

1.解压eclipse2.1.2.1-SDK-win32-LanguagePackFeature.zip到E:\eclipse213下 

       将目录名eclipse2.1.2.1-SDK-win32-LanguagePackFeature改为eclipse2.1.2.1Language 

部分目录结构如下: 

              E:\eclipse213\eclipse2.1.2.1Language\eclipse\features 

              E:\eclipse213\eclipse2.1.2.1Language\eclipse\plugins 

                     ... 

2.在E:\eclipse213下新建文件夹links,使得文件夹links和文件夹eclipse2.1.2.1Language同级 

3.在E:\eclipse213\links下新建文件,文件名任取,这里我们命名为language.link,打开此文件, 

加入 path = E:\\eclipse213\\eclipse2.1.2.1Language 

4.启动Eclipse,看看汉化是否成功,如不成功请检查language.link文件中配置信息path = 

E:\\eclipse213\\eclipse2.1.2.1Language和汉化文件夹eclipse2.1.2.1Language的安装路径是否一 

致 

  

七、TomcatPlugin安装 

1.解压tomcatPluginV221.zip 

2.将解压目录tomcatPluginV221下文件夹com.sysdeo.eclipse.tomcat_2.2.1复制到eclipse安装目 

录中的plugins目录中,即E:\eclipse213\plugins 

3.启动Eclipse 

4.启动后你将看到你的菜单上多了一个下拉项Tomcat,快捷栏里多了三个Tomcat的猫图表,如 

果没有看到,请点击 窗口->定制透视图,展开树结构中的“其它”,选择“Tomcat” 

5.点击 窗口->首选项 

       在左边树中点击tomcat,设置tomcat version为version 5.x 

                                          设置tomcat version为version 5.x 

                                          设置tomcat-home为E:\tomcat 

                                          设置perspective to switch when tomcat is started为java 

在左边树中点击tomcat->JVM setting,设置JRE为j2sdk1.4.2 

点击应用确定 

6.点击快捷按钮“Start Tomcat”来启动Tomcat吧 

  

八、Lomboz安装 

1.解压lomboz.213.zip 

2.将解压目录lomboz.213\plugins下文件夹com.objectlearn.jdt.j2ee和com.objectlearn.jdt.j2ee.editors 

复制到eclipse安装目录中的plugins目录中,即E:\eclipse213\plugins 

3.启动Eclipse 

4.点击 窗口->首选项 

       在左边树中点击lomboz,设置JDK tools.jar位置为E:\ j2sdk1.4.2\lib\tools.jar 

在左边树中点击lomboz->server definitions,设置Server Type为Apache Tomcat v5.0.x 

                            设置Application Server Directory为E:\tomcat 

                            设置classpath Variable Name为TOMCAT_HOME 

                            设置classpath Variable为E:\tomcat 

点击应用确定 

  

九、easyStruts安装 

1.解压org.easystruts.eclipse_0.6.4.zip 

2.将解压目录org.easystruts.eclipse_0.6.4下文件夹com.cross.easystruts.eclipse_0.6.4复制到eclipse 

安装目录中的plugins目录中,即E:\eclipse213\plugins 

3.启动Eclipse 

4.点击 窗口->首选项 

       在左边树中点击Easy Struts,选择struts1.1 

ADD JREs如下: 

struts.jar-E:\jakarta-struts-1.1\lib\struts.jar 

ADD TLDs如下: 

                     struts-tiles.tld-E:\jakarta-struts-1.1\lib\struts-tiles.tld 

                     struts-template.tld-E:\jakarta-struts-1.1\lib\struts-template.tld 

                     struts-nested.tld-E:\jakarta-struts-1.1\lib\struts-nested.tld 

                     struts-logic.tld-E:\jakarta-struts-1.1\lib\struts-logic.tld 

                     struts-html.tld-E:\jakarta-struts-1.1\lib\struts-html.tld 

                     struts-bean.tld-E:\jakarta-struts-1.1\lib\struts-bean.tld 

点击应用确定 

posted @ 2006-04-12 20:31 迷茫在java的世界里 阅读(612) | 评论 (0)编辑 收藏

技巧

http://www.blogjava.net/nickey/

posted @ 2006-04-12 19:57 迷茫在java的世界里 阅读(161) | 评论 (0)编辑 收藏

Java 开发者中外学习网站归类

Hibernate中文网站:http://www.hibernate.org.cn
开源网站:http://www.open-open.com
Java视线:http://www.javaeye.com
csdn:http://www.csdn.net

http://www.javaalmanac.com - Java开发者年鉴一书的在线版本. 要想快速查到某种Java技巧的用法及示例代码, 这是一个不错的去处.
http://www.onjava.com - O'Reilly的Java网站. 每周都有新文章.
http://java.sun.com - 官方的Java开发者网站 - 每周都有新文章发表.
http://www.developer.com/java - 由Gamelan.com 维护的Java技术文章网站.
http://www.java.net - Sun公司维护的一个Java社区网站.
http://www.builder.com - Cnet的Builder.com网站 - 所有的技术文章, 以Java为主.
http://www.ibm.com/developerworks/java - IBM的Developerworks技术网站; 这是其中的Java技术主页.
http://www.javaworld.com - 最早的一个Java站点. 每周更新Java技术文章.
http://www.devx.com/java - DevX维护的一个Java技术文章网站.
http://www.fawcette.com/javapro - JavaPro在线杂志网站.
http://www.sys-con.com/java - Java Developers Journal的在线杂志网站.
http://www.javadesktop.org - 位于Java.net的一个Java桌面技术社区网站.
http://www.theserverside.com - 这是一个讨论所有Java服务器端技术的网站.
http://www.jars.com - 提供Java评论服务. 包括各种framework和应用程序.
http://www.jguru.com - 一个非常棒的采用Q&A形式的Java技术资源社区.
http://www.javaranch.com - 一个论坛,得到Java问题答案的地方,初学者的好去处。
http://www.ibiblio.org/javafaq/javafaq.html - comp.lang.java的FAQ站点 - 收集了来自comp.lang.java新闻组的问题和答案的分类目录.
http://java.sun.com/docs/books/tutorial/ - 来自SUN公司的官方Java指南 - 对于了解几乎所有的java技术特性非常有帮助.
http://www.javablogs.com - 互联网上最活跃的一个Java Blog网站.
http://java.about.com/ - 来自About.com的Java新闻和技术文章网站.
http://www.objectlearn.com/index.jsp

http://www.open-open.com开源网

中文网站
http://www-900.ibm.com/developerWorks/cn/java/index.shtml
http://diy.ccidnet.com/pub/article/c317_a71330_p1.html  赛迪网J2EE专题
http://www.javaresearch.org/    Java研究组织
http://www.jdon.com/   J道-Java和J2EE解决之道
http://community.csdn.net/expert/forum.asp   CSDN技术社区

http://www.javaeye.com   Java视线

1、spring in action Live中文文档

http://searchwebservices.techtarget.com.cn/wpsum/29/2217529.shtml?504

2、Spring实战

http://searchwebservices.techtarget.com.cn/wpsum/75/2215575.shtml?2994

3、Spring - Java/J2EE Application Framework

spring in action Framework 开发参考手册(中文版)

http://www.jactiongroup.net/reference/html/index.html

4、Introducing to spring in action Framework(中文修订版)

http://spring.jactiongroup.net/viewtopic.php?t=453

5、spring in action Framework 介绍 (ppt培训文档)

http://www.jactiongroup.net/doc/Introduction2open-sourceSpringframework4J2EE.ppt

http://www.jactiongroup.net/doc/IntroductionToSpring.ppt

6、Spring 中文社区

http://spring.jactiongroup.net

7、中国IT实验室 spring in action 框架完全进阶专题

http://www.chinaitlab.com/www/techspecial/spring/


本人再加一个啦:)~~
http://www.springframework.org




Eclipse及其插件介绍和下载
0.Eclipse下载
EMF,GEF - Graphical Editor Framework,UML2,VE - Visual Editor都在这里下载
http://www.eclipse.org/downloads/index.php
 
0.5.lomboz J2EE插件,开发JSP,EJB
http://forge.objectweb.org/projects/lomboz
1.MyEclipse J2EE开发插件,支持SERVLET/JSP/EJB/数据库操纵等
http://www.myeclipseide.com/
 
2.Properties Editor  编辑java的属性文件,并可以自动存盘为Unicode格式
http://propedit.sourceforge.jp/index_en.html
 
3.Colorer Take  为上百种类型的文件按语法着色
http://colorer.sourceforge.net/
 
4.XMLBuddy 编辑xml文件
http://www.xmlbuddy.com/
 
5.Code Folding  加入多种代码折叠功能(比eclipse自带的更多)
http://www.coffee-bytes.com/servlet/PlatformSupport
 
6.Easy Explorer  从eclipse中访问选定文件、目录所在的文件夹
http://easystruts.sourceforge.net/
 
7.Fat Jar 打包插件,可以方便的完成各种打包任务,可以包含外部的包等
http://fjep.sourceforge.net/
 
8.RegEx Test 测试正则表达式
http://brosinski.com/stephan/archives/000028.php
 
9.JasperAssistant 报表插件(强,要钱的)
http://www.jasperassistant.com/
 
10.Jigloo GUI Builder JAVA的GUI编辑插件
http://cloudgarden.com/jigloo/
 
11.Profiler 性能跟踪、测量工具,能跟踪、测量BS程序
http://sourceforge.net/projects/eclipsecolorer/
 
12.AdvanQas 提供对if/else等条件语句的提示和快捷帮助(自动更改结构等)
http://eclipsecolorer.sourceforge.net/advanqas/index.html
 
13.Log4E Log4j插件,提供各种和Log4j相关的任务,如为方法、类添加一个logger等
http://log4e.jayefem.de/index.php/Main_Page
 
14.VSSPlugin VSS插件
http://sourceforge.net/projects/vssplugin
 
15.Implementors 提供跳转到一个方法的实现类,而不是接中的功能(实用!)
http://eclipse-tools.sourceforge.net/implementors/
 
16.Call Hierarchy 显示一个方法的调用层次(被哪些方法调,调了哪些方法)
http://eclipse-tools.sourceforge.net/call-hierarchy/index.html
 
17.EclipseTidy 检查和格式化HTML/XML文件
http://eclipsetidy.sourceforge.net/
 
18.Checkclipse 检查代码的风格、写法是否符合规范
http://www.mvmsoft.de/content/plugins/checkclipse/checkclipse.htm
 
19.Hibernate Synchronizer Hibernate插件,自动映射等
http://www.binamics.com/hibernatesync/
 
20.VeloEclipse  Velocity插件
http://propsorter.sourceforge.net/
 
21.EditorList 方便的列出所有打开的Editor
http://editorlist.sourceforge.net/
 
22.MemoryManager 内存占用率的监视
http://cloudgarden.com/memorymanager/
 
23.swt-designer java的GUI插件
http://www.swt-designer.com/
 
24.TomcatPlugin 支持Tomcat插件
http://www.sysdeo.com/eclipse/tomcatPlugin.html
 
25.XML Viewer
http://tabaquismo.freehosting.net/ignacio/eclipse/xmlview/index.html
 
26.quantum 数据库插件
http://quantum.sourceforge.net/
 
27.Dbedit 数据库插件
http://sourceforge.net/projects/dbedit
 
28.clay.core 可视化的数据库插件
http://www.azzurri.jp/en/software/index.jsp
http://www.azzurri.jp/eclipse/plugins
 
29.hiberclipse hibernate插件
http://hiberclipse.sourceforge.net/
http://www.binamics.com/hibernatesync
 
30.struts-console Struts插件
http://www.jamesholmes.com/struts/console/
 
31.easystruts Struts插件
http://easystruts.sourceforge.net/
 
32.veloedit Velocity插件
http://veloedit.sourceforge.net/
 
33.jalopy 代码整理插件
http://jalopy.sourceforge.net/
 
34.JDepend 包关系分析
http://andrei.gmxhome.de/jdepend4eclipse/links.html
 
35.Spring IDE Spring插件
http://springide-eclip.sourceforge.net/updatesite/
 
36.doclipse 可以产生xdoclet 的代码提示
http://beust.com/doclipse/
0.Eclipse下载
EMF,GEF - Graphical Editor Framework,UML2,VE - Visual Editor都在这里下载
http://www.eclipse.org/downloads/index.php

posted @ 2006-04-12 19:29 迷茫在java的世界里 阅读(246) | 评论 (0)编辑 收藏

用Tomcat插件在Eclipse上搭建可跟踪调试的J2EE WEB开发环境

目标:
1.管理J2EE工程:发布WEB程序,启动/关闭服务器等
2.编辑JSP/HTML/XML:有代码提示,语法着色,错误提示等功能
3.跟踪调试JSP/SERVLET:可设置断点,单步执行,变量/栈/线程跟踪等
 
(1).下载安装Sysdeo Tomcat插件,用来管理tomcat服务器,提供断点调试功能
http://www.sysdeo.com/eclipse/tomcatPlugin.html
SysdeoTomcat插件的安装方法:
使用 Eclipse 作为 Jakarta Tomcat 的开发环境 ----一种快速集成 Eclipse 和 Tomcat 的方法  Geoffrey R. Duck
http://www-900.ibm.com/developerworks/cn/opensource/os-ectom/
 
(2).下载安装Lomboz插件,用来编辑JSP/HTML/XML等
http://www.objectlearn.com
Lomboz的安装方法:
*使用Eclipse开发Jsp 左锦
http://www-900.ibm.com/developerWorks/cn/java/l-jsp-eclipse/index.shtml
*使用Eclipse开发J2EE应用 ----集成Eclipse, Lomboz和JBoss 姜巍巍
http://www-900.ibm.com/developerWorks/cn/java/l-eclipse-j2ee/index.shtml
 
(3).快速指南
1.New Project -> Tomcat Project

2.输入Project Name 下一步(不能建在已有的目录里)

3.输入Context Name 就是web应用程序的名称,决定访问时的地址; 输入Subdirectory to set as web application root(设置为web应用程序根目录的目录名),就是web目录,可以输入webapp(JBuilder默认的名称),或其他的,如果不输入的话,就直接建在Project目录下.

4.此时建立的目录有:
webapp/WEB-INF/src  默认的源文件是放在WEB-INF目录下(Tomcat Plugin的)
work  执行JSP时,编译成的servlet源文件会放在此处(Tomcat Plugin的)
bin   eclipse默认的放置编译后生成的classes文件
src   eclipse默认的源文件目录
webapp web应用程序的目录

5.以上的目录都可以在project属性里改,我一般喜欢把源文件放在src目录下,而不是WEB-INF/src下,输出到WEB-INF/classes目录,而不是bin目录.

6.以上建好的web应用程序没有web.xml,如果要自动建这个文件,那么可以执行一次lomboz的J2EE Module向导.

7.运行tomcat(点击tomcat插件在界面上新增的小猫图标即可启动/关闭tomcat,具体的安装看上面的链接)
 
8.编辑JSP/HTML等文件,按右键->Open with->JSP editor(红色图标那个).文件关联可以在Window菜单->Preferences->Workbench->File Association里面设置.

9.调试Servlet或struts的Action时,只要在程序的相应位置的行号上双击就可以设置一个断点,刷新相应的页面(即发出请求),程序就会在断点的位置中断.
      如果要调试JSP,稍微麻烦一点,因为它不能直接支持JSP的断点调试.要先把那个页面请求一次,再刷新eclipse里的左侧目录(右键->刷新),会发现work目录下出现相应JSP文件的java源文件.打开这个源文件,在里面设置断点即可.

(转移自2004年9月的一篇随笔)

posted @ 2006-04-12 04:01 迷茫在java的世界里 阅读(630) | 评论 (0)编辑 收藏