yooli88

          2007年9月11日 #

          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的世界里 閱讀(368) | 評論 (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的世界里 閱讀(210) | 評論 (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的世界里 閱讀(192) | 評論 (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的世界里 閱讀(451) | 評論 (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的世界里 閱讀(145) | 評論 (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的世界里 閱讀(240) | 評論 (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的世界里 閱讀(223) | 評論 (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的世界里 閱讀(208) | 評論 (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的世界里 閱讀(202) | 評論 (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的世界里 閱讀(533) | 評論 (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的世界里 閱讀(163) | 評論 (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的世界里 閱讀(180) | 評論 (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的世界里 閱讀(113) | 評論 (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的世界里 閱讀(131) | 評論 (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的世界里 閱讀(276) | 評論 (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的世界里 閱讀(146) | 評論 (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的世界里| 編輯 收藏

          主站蜘蛛池模板: 镇安县| 称多县| 凤城市| 新疆| 北川| 凤台县| 上虞市| 鄂温| 南宫市| 安多县| 墨脱县| 大姚县| 陇南市| 绥阳县| 塔城市| 西畴县| 工布江达县| 凤冈县| 宾阳县| 莲花县| 顺义区| 堆龙德庆县| 凤山县| 新野县| 潜江市| 卓资县| 陇西县| 平阳县| 岐山县| 洪泽县| 高要市| 保德县| 溆浦县| 武安市| 洞头县| 石台县| 菏泽市| 偃师市| 西平县| 青州市| 海安县|