通过dom4j 读取远程连接数据

来源:互联网 发布:织梦cms演示站 编辑:程序博客网 时间:2024/05/16 10:58

第一:类dto

第二:本人用三个方法读http://blog.hiredmyway.com/feed网站得数据

// 有两个sax2读取

package com.hiredmyway.index.sax2test;

import org.apache.commons.lang.StringUtils;

import com.hiredmyway.util.string.ShortTextSubString;
import com.hiredmyway.util.string.TitleSubString;

public class RssItemDTO {    
        private String Title = "";
        private String URL = "";        
        private String description="";
        private String pubDate="";
        private String imageUrl = "";
        private int id;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getDescription() {
            if(StringUtils.isNotBlank(description)){
                description = new ShortTextSubString().trimSubString(description);
            }
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
        public void setTitle(String Title) {
            if(StringUtils.isNotBlank(this.Title)){
                this.Title = new TitleSubString().trimSubString(this.Title);
            }
            this.Title = Title;
        }        
        public void setURL(String URL) {
            this.URL = URL;
        }
        
        public String toString() {            
            return this.Title+":"+this.pubDate+":"+this.URL+":"+this.description+":"+this.getImageUrl();
        }
        public String getTitle() {
            return Title;
        }
        public String getURL() {
            return URL;
        }
        public String getPubDate() {
            return pubDate;
        }
        public void setPubDate(String pubDate) {
            this.pubDate = pubDate;
        }
        
        public String getImageUrl() {
            return imageUrl;
        }
        public void setImageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
        }

}

-------------------------------------------------

package com.hiredmyway.index.TestDom4j;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.hiredmyway.index.sax2test.RssItemDTO;
import com.hiredmyway.util.SysUtil;


public class InfoXML {
    
    public static Document parse2Document(String xmlFilePath) throws IOException {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            URL u = new URL(xmlFilePath);
            URLConnection UC = u.openConnection();
            UC.setRequestProperty("User-agent", "www.hiredmyway.com");
//            InputStream in = InfoXML.class.getResourceAsStream(xmlFilePath);
            InputStream in = UC.getInputStream();
//            document = reader.read(in);
            document = reader.read(u);
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
            System.out.println("");
            e.printStackTrace();
        }
        return document;
    }
    public void doInfoXML(String infoXML) throws IOException
    {

      SAXReader reader = new SAXReader();

      Document document = parse2Document(infoXML);
    
      try
      {
//       Element root = (Element) document.getRootElement();
       List<Element> list = document.selectNodes("/rss/channel/item");
//       if (!list.isEmpty()) {
//           for (Element element : list){
//               System.out.println(element.elementText("title"));
//              
//               System.out.println(SysUtil.convertDateStringToString(element.elementText("pubDate")));
//               System.out.println(element.elementText("description"));
//               System.out.println(element.elementText("/rss/channel/item/content:encoded"));
//               System.out.println( element.attributeValue(".content:encoded"));
//               System.out.println(element.element("content:encoded").getText());
//               System.out.println("---------");
//           }
//           
//       }
       
       
       Iterator it = list.iterator();
       RssItemDTO dto = null;
       int i =0;
       while(it.hasNext())
       {
           dto = new RssItemDTO();
           Node nodex=(Node)it.next();
           String title = getXmlValue("title", nodex);
           dto.setTitle(title);
           String pubDate = getXmlValue("pubDate", nodex);

         //Fri, 28 Oct 2011 13:45:36 +0000
           System.out.println(pubDate);
           dto.setPubDate(SysUtil.convertDateStringToString(pubDate));
           String content_encoded = getXmlValue("content:encoded", nodex);
           List img = getImageUrl(content_encoded);
           dto.setImageUrl((String)img.get(0));

          if (null != dto) {
              System.out.println("title="+dto.getTitle());

        //10/28/11
              System.out.println("Date="+dto.getPubDate());
              System.out.println("content:encoded="+dto.getImageUrl());
          }

        System.out.println(" --------------------- "+i++);  
       }
      } catch (Exception e1)
      {
       e1.printStackTrace();
      }
    }
    public static void main(String[] args) throws IOException
    {
      InfoXML xml=new InfoXML();
 
      String Url = "http://blog.hiredmyway.com/feed";
      xml.doInfoXML(Url);
      
    }

    private List<String> getImageUrl(String content) {
        String img = "";
        Pattern p_image;
        Matcher m_image;
        List<String> pics = new ArrayList<String>();
        String regex_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile(regex_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(content);
        while (m_image.find()) {
            img = img + "," + m_image.group();
             Matcher m  = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;

    }
    
    private String getXmlValue(String attribute, Node nodex){
        List list = nodex.selectNodes(attribute);
        Iterator it = list.iterator();
        String resources="";
        while (it.hasNext()){
            Node node = (Node)it.next();
             resources = node.getStringValue();
           break;
         
        }
        return resources;
        
    }
}

===============================================================


package com.hiredmyway.util;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

import com.hiredmyway.action.employer.EmployerDashBoardAction;
import com.hiredmyway.dto.PaymentInfoDTO;
import com.hiredmyway.dto.ZipCodeDTO;
import com.hiredmyway.enums.KindEnum;
import com.hiredmyway.enums.ResumeOrgJobStatusEnum;
import com.hiredmyway.pojo.Address;
import com.hiredmyway.pojo.BasePojo;
import com.hiredmyway.pojo.Enums;
import com.hiredmyway.pojo.OrganizationProfile;
import com.hiredmyway.pojo.Users;
import com.hiredmyway.service.payment.util.AuthNet.CustomerPaymentProfile;
import com.hiredmyway.service.payment.util.AuthNet.CustomerProfile;
import com.opensymphony.xwork2.validator.validators.EmailValidator;

public class SysUtil {
    private static final String BROWSE_UNIQUE = "p/";
    private static final String VIEW_ACTIVE = "viewActiveResume.action";
    private static Logger logger = Logger.getLogger(SysUtil.class);
    
    @SuppressWarnings("unchecked")
    public static List convertToList(Set<BasePojo> set) {
        Iterator it = set.iterator();
        List list = new ArrayList();
        if (set != null && set.size() != 0) {
            while (it.hasNext()) {
                Object pojo = it.next();
                list.add(pojo);
            }
        }
        sort(list);
        return list;
    }

    
    public static Set<BasePojo> removeObj(Set<BasePojo>list){
        Set<BasePojo> basePojoList = new HashSet<BasePojo>();
        for(BasePojo pojo:list){
            if(!pojo.getDeleted()){
                basePojoList.add(pojo);
            }
        }
        return basePojoList;
    }
    
    
    public static List<BasePojo> removeObj(List<BasePojo>list){
        List<BasePojo> basePojoList = new ArrayList<BasePojo>();
        for(BasePojo pojo:list){
            if(!pojo.getDeleted()){
                basePojoList.add(pojo);
            }
        }
        sort(basePojoList);
        return basePojoList;
    }
    
    
    public static void sort(List<BasePojo> list){
        Collections.sort(list, new Comparator<BasePojo>(){
            public int compare(BasePojo o1, BasePojo o2){
                if(o1.getId() > o2.getId())
                    return 1;
                else
                    return -1;
            }
        });
    }
    
    
    public static String getUniqueUserUrl(Integer id,String shotName){
        String url =BROWSE_UNIQUE + shotName +"_"+id;
        return url;
    }
    
    public static String viewActiveUrl(String uniqueFlag,Integer id,String trimFullName){
        String url =VIEW_ACTIVE+"?uniqueflag="+uniqueFlag+"&id="+id+"&fullname="+trimFullName;
        return url;
    }
    

    public static String getTrimFullName(String fullName){
        if(fullName !=null){
            return fullName.replace(" ", "");
        }else{
            return "";
        }
    }

    public static String getFullName(Boolean isPrivate,String firstName,String lastName){
        String fullName="";
        if(firstName ==null ||lastName == null){
            return "";
        }else if(isPrivate !=null && isPrivate){
            //private user
            fullName = firstName+" "+lastName.substring(0,1);
        }else{
            fullName = firstName+" "+lastName;
        }
        return fullName;
    }
    
   public static void formatDate(Date data){
       
   }
   
   public static String trimAll(String s){
       String ret = s;
       if(StringUtils.isNotEmpty(s)){
           if(s.contains(" ")){
               ret = s.replaceAll(" ","");
           }
       }
       return ret;
   }
   
   public static List<OptionList> getYesNOList(){
      OptionList op1 = new OptionList("Yes",true);
      OptionList op2 = new OptionList("No",false);
      List<OptionList> list = new ArrayList<OptionList>();
      list.add(op1);
      list.add(op2);
      return list;
  }
 
  public static List<OptionList> getPubliclyOrPrivatelyList(){
      OptionList op1 = new OptionList("Privately held",true);
      OptionList op2 = new OptionList("Publicly held",false);
      List<OptionList> list = new ArrayList<OptionList>();
      list.add(op1);
      list.add(op2);
      return list;
  }
 
  public static List<OptionList> getCustomList(String labelTrue,String labelFalse){
      OptionList op1 = new OptionList(labelTrue,true);
      OptionList op2 = new OptionList(labelFalse,false);
      List<OptionList> list = new ArrayList<OptionList>();
      list.add(op1);
      list.add(op2);
      return list;
  }
 
  /**
     * compare enums by target priority
     * @param cache
     * @param target
     * @param biggerThan
     * @param includeEqual
     * @param kind(optional)
     * @return
     */
    public static String getEnumIds(SysCache cache,Enums target,boolean biggerThan,boolean includeEqual){
        if(target != null && target.getPriority() == null){
            target = SysCache.getInstance().getOneEnum(target.getId());
        }
        if(target == null || target.getPriority() == null){
             logger.error("error target in getEnumsIds,target id:"+target.getId());
             return "";
        }
        
        List<Enums> enums = cache.getEnum(target.getKind());
        List<Integer> resultList = new ArrayList<Integer>();
        Iterator it = enums.iterator();
        while(it.hasNext()){
            Enums e = (Enums)it.next();
            if(e.getPriority() == null){
                logger.error("priority is null can't compare for this enum,"+target.getKind());
            }
            if(biggerThan && e.getPriority() != null){
                if(e.getPriority() > target.getPriority()){
                    resultList.add(e.getId());
                }else if(includeEqual){
                    if(e.getPriority() == target.getPriority()){
                        resultList.add(e.getId());
                    }
                }

            }else{
                if(e.getPriority() != null && e.getPriority()< target.getPriority()){
                    resultList.add(e.getId());
                }else if(includeEqual){
                    if(e.getPriority() != null && e.getPriority() == target.getPriority()){
                        resultList.add(e.getId());
                    }
                }
            }
        }
        String retString = "";
        for (int i = 0; i < resultList.size(); i++) {
            retString += resultList.get(i);
            if(i < resultList.size() -1){
                retString +=",";
            }
        }
        return retString;
    }
    
    
    public static String converListToSqlString(List list){
        String result = "";
        if(list != null && list.size() >0){
            for (int i = 0; i < list.size(); i++) {
                Object obj = list.get(i);
                result += obj.toString();
                if(i < list.size() -1){
                    result +=", ";
                }
            }
        }
        if("".equals(result)){
            result = null;
        }
        return result;
    }
   
   public static String getGoogelMapParameters(Address address){
       if(address==null){
           address = new Address();
       }
        StringBuffer sb = new StringBuffer("");
        sb.append("location=").append("");
        String append ="";
        if(StringUtils.isNotEmpty(address.getAddress1()) ){
            append = address.getAddress1();
        }
        if(StringUtils.isNotEmpty(address.getAddress2())){
            if(StringUtils.isNotEmpty(address.getAddress1()) ){
                append += " , ";
            }
            append += address.getAddress2();
        }
        sb.append("&address=").append(append);
        sb.append("&city=").append(address.getCity()==null?"":address.getCity());
        sb.append("&state=").append(address.getEnums()==null?"":address.getEnums().getCodeDesc());
        sb.append("&zipcode=").append(address.getZipCode()==null?"":address.getZipCode());
        sb.append("&country=").append(address.getEnumsByCountry()==null?"":address.getEnumsByCountry().getCodeDesc());
        
        return sb.toString();
    }
 
  /**
   * @param email
   * @return
   */
   public static boolean isEmail(String email){      
       String regex = EmailValidator.emailAddressPattern;       
       Pattern p =  Pattern.compile(regex);
       Matcher m = null;
       String strEmail[]=email.split(",");
       for(int i=0;i<strEmail.length;i++){
           if(!p.matcher(strEmail[i].trim()).find())
               return false;
       }       
       return true;
   }
   /**
    * Judge the input data
    * @param date
    * @return
    */
   public static boolean isDate(String date){
       String inputDate=date;
       Pattern p = Pattern.compile("\\d{1,2}[/]\\d{1,2}[/]\\d{4}");
        Matcher m = p.matcher(date);
        if(!m.matches()){
            return false;
        }
       
       SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
       SimpleDateFormat sdf1 = new SimpleDateFormat("M/d/yyyy");
       try {
        if (inputDate.equals(sdf.format(sdf.parse(inputDate))) ||inputDate.equals(sdf1.format(sdf1.parse(inputDate))) ) {  
                return true;
            } else {  
               return false;  
            }
        } catch (ParseException e) {        
            e.printStackTrace();
            return false;
        }
   }
   
   public static Date converToDate(String date){
       Date result = null;
       if(SysUtil.isDate(date)){
           try {
               result = DateUtils.parseDate(date, new String[]{"MM/dd/yyyy","M/d/yyyy"});
           } catch (ParseException e) {
               e.printStackTrace();
           }
       }
       return result;
   }
   //trim  remove last comma
   public static String formatEmail(String email){    
       if(email == null){
           return null;
       }
       StringBuilder buffer = new StringBuilder();
       String strEmail[]=email.split(",");
       for(int i=0;i<strEmail.length;i++){
           String str = strEmail[i].trim();
           if(!"".equals(str)){
               buffer.append(str);
               buffer.append(",");
           }
       }
       String formatStr = buffer.toString();
       if(formatStr.endsWith(",")){
           formatStr = formatStr.substring(0, formatStr.length() -1);
       }
       return formatStr;
   }
   
   public static CustomerProfile getCustomerProfile(Users user){
        CustomerProfile customerProfile = new CustomerProfile();
        customerProfile.setMerchantCustomerId(user.getId().toString());
        customerProfile.setEmail(user.getLoginName());
        customerProfile.setDescription(String.valueOf(Calendar.getInstance().getTime().getTime()));
        return customerProfile;
    }
   
   public static CustomerProfile getCustomerProfile(OrganizationProfile organizationProfile){
        CustomerProfile customerProfile = new CustomerProfile();
        customerProfile.setMerchantCustomerId(organizationProfile.getId().toString());
        customerProfile.setEmail(organizationProfile.getUser().getLoginName());
        customerProfile.setDescription(String.valueOf(Calendar.getInstance().getTime().getTime()));
        return customerProfile;
    }   
    
   public static CustomerPaymentProfile getCustomerPaymentProfile(PaymentInfoDTO paymentInfoDTO){
        CustomerPaymentProfile customerPaymentProfile = new CustomerPaymentProfile();
        customerPaymentProfile.setFirstName(paymentInfoDTO.getNameOfCard());
        
        customerPaymentProfile.setLastName("");
        customerPaymentProfile.setAddress(paymentInfoDTO.getAddress1());
        customerPaymentProfile.setCity(paymentInfoDTO.getCity());
        customerPaymentProfile.setState(paymentInfoDTO.getState());
        customerPaymentProfile.setZip(paymentInfoDTO.getZip());
        customerPaymentProfile.setCountry("United States");
        customerPaymentProfile.setPhone(paymentInfoDTO.getPhone());
        customerPaymentProfile.setCardNumber(paymentInfoDTO.getCardNumber());
        customerPaymentProfile.setExpirationDate(paymentInfoDTO.getExpirationYear() + "-" + paymentInfoDTO.getExpirationMonth());
        customerPaymentProfile.setCardCode(paymentInfoDTO.getCcv());    
                
        return customerPaymentProfile;
    }
   
   
   
   
   /**
    * @author Michael  Oct 22, 2010
    * convert an object to json String
    * @param object
    * @return
    */
   public static String objectToJson(Object object) {     
       JSONObject jsonObject = JSONObject.fromObject(object);     
       return jsonObject.toString();     
   }

   /**
    * @author Michael  Oct 22, 2010
    * convert json String to object
    * @param json
    * @param beanClz
    * @return
    */
   public static Object jsonToObject(String json, Class beanClz) {     
       return JSONObject.toBean(JSONObject.fromObject(json), beanClz);     
   }    

   public static boolean isDevMode(){
       boolean result = false;
       String env = SysCache.getInstance().getSysConfig("enviroment");
       if(env != null){
           if(env.equalsIgnoreCase("tomcat") || env.equalsIgnoreCase("dev")){
               result = true;
           }
       }else{
           Logger.getLogger(SysUtil.class).error("error get env config");
       }
       return result;
   }
   
   public static boolean isLiveMode(){
       boolean result = false;
       String env = SysCache.getInstance().getSysConfig("enviroment");
       if(env != null){
           if(env.equalsIgnoreCase("live")){
               result = true;
           }
       }else{
           Logger.getLogger(SysUtil.class).error("error get env config");
       }
       return result;
   }
   
   @Deprecated
   /**
    * @author Michael  Nov 24, 2010
    * to calculate Percent, return percent number in 10,20 ...
    * @param number
    * @param total
    * @return
    */
   public static Integer calculatePercent(int number,int total){
      int ret = 0;
      if(number <=0 || total <= 0){
          ret =  0;
      }else if(number > total){
          ret = 100;
      }else{
         float percent = ((Integer)number).floatValue()/((Integer)total).floatValue();  
         percent = percent * 10; // 0.583 * 10 = 5.83 => 6 => 60
         ret = Math.round(percent)*10;
      }
      return ret;
   }
   
   public static boolean isEqual(Integer integer1, Integer integer2){
       if((integer1 == null && integer2 != null) || (integer1 != null && integer2 == null)){
           return false;
       }else if(integer1 - integer2 != 0){
           return false;
       }else{
           return true;
       }  
   }
   
   public static String filterDeletedStatus(String alias, Integer deletedStatus){
       Integer inprocessingStatus = ((Enums)SysCache.getInstance().getOneEnum(KindEnum.RESUMEORGJOBSTATUSENUM.getKindName(),ResumeOrgJobStatusEnum.INPROCESSING.getCode())).getId();
       Integer draftStatus = ((Enums)SysCache.getInstance().getOneEnum(KindEnum.RESUMEORGJOBSTATUSENUM.getKindName(),ResumeOrgJobStatusEnum.DRAFT.getCode())).getId();
       return " and (" + alias + ".status is null or " + alias + ".status not in (" +  deletedStatus + ", " + inprocessingStatus + ", " + draftStatus + " )) ";
   }
    
   public static String filterContacted(String alias, Integer contactedRelationType, Integer deletedStatus, boolean forJob){
        String filter = "";
        if(forJob){
            filter = " and not exists (select contacted.id from resume_org_job contacted where contacted.deleted = 0  and contacted.job_id = " + alias + ".job_id and contacted.res_id = " + alias + ".res_id and contacted.relation_type = " + contactedRelationType  + SysUtil.filterDeletedStatus("contacted", deletedStatus) + ")";
        }else{
            filter = " and not exists (select contacted.id from resume_org_job contacted where contacted.deleted = 0  and contacted.org_id = " + alias + ".org_id and contacted.job_id is null and contacted.res_id = " + alias + ".res_id and contacted.relation_type = "+ contactedRelationType + SysUtil.filterDeletedStatus("contacted", deletedStatus) + ") ";
        }
        
        filter += filterDeletedForRojStatus(alias);
        
        return filter;        
    }
   
   public static String filterDeletedForRojStatus(String alias){
       String filter = "";
       
       SessionManager sm = SessionManager.get();
       if(sm != null){
          Integer userId = sm.getUserId();
          if(userId != null){
              filter = " and not exists (select rs.id from roj_status rs where rs.deleted = 1  and rs.roj_id = " + alias + ".id and rs.owner = " + userId + ") ";    
          }
       }
       return filter;
    }
   
   
   public static String addFreeOrPremiumApplyConditions(String alias, String freeOrPremium){
       String con = "";
       if(freeOrPremium != null && freeOrPremium.equals(EmployerDashBoardAction.FREE_APPLICATIONS)){
           con = " and " + alias + ".free_apply = 1 ";
       }else if(freeOrPremium != null && freeOrPremium.equals(EmployerDashBoardAction.PREMIUM_APPLICATIONS)){
           con = " and (" + alias + ".free_apply is null or " + alias + ".free_apply = 0)";
       }
       return con;
   }
   
   public static String converToString(List<ZipCodeDTO> list){
        String result = null;
        if(list != null && list.size()>0){
            result ="";
            for (int i = 0; i < list.size(); i++) {
                ZipCodeDTO dto =(ZipCodeDTO)list.get(i);
                result += "'"+dto.getZipcode()+"'";
                if(i < (list.size()-1)){
                    result +=", ";
                }
            }
        }
        return result;
    }
   
   public static String checkNull(Object obj){
       if(obj == null){
           return " ";
       }else{
           return obj.toString();
       }
   }
   
    public static int getDaysBetween(Date beginDate, Date endDate){
        Calendar d1 = new GregorianCalendar();
        d1.setTime(beginDate);

        Calendar d2 = new GregorianCalendar();
        d2.setTime(endDate);

        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);

        if (d1.get(Calendar.YEAR) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                if(beginDate.getTime() <= endDate.getTime()){
                    days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                    d1.add(Calendar.YEAR, 1);
                }else{
                    days -= d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                    d1.add(Calendar.YEAR, -1);
                }
            } while (d1.get(Calendar.YEAR) != y2);
        }
        
        return days;
    }
    
    
    public static String[] convertToStringArray(String target){
        String[] ret = null;
        if(StringUtils.isNotBlank(target)){
            target = target.trim();
            ret = target.split(" ");
            if(ret.length < 1){
                ret = null;
            }
        }
        return ret;
    }
    
    
    public static String convertToSQLString(Object[] array){
        String ret ="";
        if(array != null && array.length >0){
            for (int i = 0; i < array.length; i++) {
                ret += array[i]+"";
                if(i<array.length -1){
                    ret +=",";
                }
            }
        }
        return ret;
    }
    
    public static Timestamp converStringToTimestamp(String date, String simpleDateFormat){
        if(StringUtils.isBlank(date)){
            return null;
        }
        
        String defaultSimpleDateFormat = "MM/dd/yyyy HH:mm";
        if(StringUtils.isBlank((simpleDateFormat))){
            simpleDateFormat = defaultSimpleDateFormat;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(simpleDateFormat);
        
        Timestamp ts = null;
        try {
            ts = new Timestamp(sdf.parse(date).getTime());
        } catch (ParseException e) {
            return null;
        }
        return ts;
    }
    
    public static String converDateToString(Date date, String simpleDateFormat){
        if(date == null){
            return null;
        }
        
        String defaultSimpleDateFormat = "MM/dd/yyyy HH:mm";
        if(StringUtils.isBlank((simpleDateFormat))){
            simpleDateFormat = defaultSimpleDateFormat;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(simpleDateFormat);
        
        String ts = null;
        try {
            ts = sdf.format(date);
        } catch (Exception e) {
            return null;
        }
        return ts;
    }
    
    /**
     * convert String with Date form to String MM/dd/yy
     * like convert String:Thu, 20 Oct 2011 06:00:00 EST to Stirng:10/20/11
     */
    public static String convertDateStringToString(String dateString){
        Date date = null;
        try {
            date = DateFormat.getDateInstance(DateFormat.FULL,Locale.UK).parse(dateString.trim());
        } catch (ParseException e) {            
            e.printStackTrace();
        }        
          SimpleDateFormat sp=new SimpleDateFormat("MM/dd/yy");
          return sp.format(date);
    }
    /*
     *@param target format like 1-10, 11-50, 10+
     */
    public static Integer getRangeStart(String target){
        Integer start = null;
        if(StringUtils.isBlank(target)){
            start = null;
        }else{
            String[] ret = target.split("\\-");
            if(ret.length > 1){
                start =  Integer.valueOf(ret[0]);
            }else{
                ret = target.split("\\+");
                start = Integer.valueOf(ret[0]) + 1;
            }
        }
        return start;
    }
    
    /*
     *@param target format like 1-10, 11-50, 10+
     */
    public static Integer getRangeEnd(String target){
        Integer end = null;
        if(StringUtils.isBlank(target)){
            end = null;
        }else{
            String[] ret = target.split("\\-");
            if(ret.length > 1){
                end =  Integer.valueOf(ret[1]);
            }else{
                end = null;
            }
        }
        return end;
    }    
    
    public static String formatMoney(Object money){
        return SysUtil.formatMoney(money, 0);
    }
    
    public static String formatMoney(Object money, Integer digits){
        if(money == null){
            money = 0f;
        }
        if(digits == null){
            digits = 2;
        }else if(digits < 0){
            digits = 0;
        }
        NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
        format.setMaximumFractionDigits(digits);
        return format.format(money);
    }
    
    public static boolean checkCommonObjNotNull(BasePojo... obj){
        boolean result = false;
        List list = Arrays.asList(obj);
        if(list != null){
            Iterator it = list.iterator();
            while(it.hasNext()){
                Object objsub = it.next();
                if(objsub != null){
                    Class classSub = objsub.getClass();
                    try{
                        Method m = classSub.getMethod("getId",null);
                        m.setAccessible(true);
                        Object subObjId = m.invoke(objsub, null);
                        if(subObjId == null){
                            result = false;
                            break;
                        }else{
                            result = true;
                        }
                    }catch(Exception e){
                        result = false;
                        logger.warn("checkCommonObjNotNull "+e.getStackTrace());
                    }
                }else{
                    result = false;
                    break;
                }
            }
        }
        return result;
    }
    
    public static String formatNumber(Float amonut, String format){
        if(amonut == null) amonut = 0.00f;
        if(format == null) format = "$##,###,###.00";
        DecimalFormat formatDF = new DecimalFormat(format);
        return formatDF.format(amonut);
    }
    
    public static String maskString(String input, Integer count){
        if(StringUtils.isEmpty(input)){
            return null;
        }
        if(count == null || count <= 0){
            count = 3;
        }
        if(count > input.length()){
            count = input.length();
        }
        if(input.length() <= count){
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < input.length(); i++) {
                buffer.append("*");
            }
            input = buffer.toString();            
        }else{
            input = input.substring(0,input.length()-count);
            StringBuffer buffer = new StringBuffer();
            for(int i = 0; i< count ;i ++){
                buffer.append("*");
            }
            input += buffer.toString();
        }
        return input;
    }
    
    public static String getUploadedFileLoaction(String fileName){
        if(StringUtils.isNotBlank(fileName)){
            String photoUrl = SysCache.getInstance().getSysConfig("floder_for_uploaded");
            if(!photoUrl.endsWith("/")){
                photoUrl = photoUrl + "/";
            }
            photoUrl = photoUrl + fileName;
            return photoUrl;
        }
        return null;
    }
    public static String subString(String subString,int start,int length){
        if(subString.length()>length){
            subString=subString.substring(start,start+length-3)+"...";
        }        
        return subString;
    }
    
    
    
    public static String getMySQLLimit(Integer start, Integer limit){
        if(start == null){
            start = 0;
        }
        if(start != null && limit != null){
            return " limit "+start+","+limit+" ";
        }else{
            return "";
        }
    }
    
    public static String findMatch(String pattern,String input){
        String result = null;
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(input);
        if(m.find()){
            result = m.group();
        }
        return result;
    }
    
    public static void main(String[] args) {
        System.out.println(isEmail(""));
        System.out.println(isEmail("sad@qq.com"));
        System.out.println(isEmail("sad@qq.com,"));
        System.out.println(isEmail("sad@qq.com,asda@ss.com"));
        System.out.println(isEmail("sad@qq.com,dsfsfd@ccc.com"));
       System.out.println(isEmail("sad@qq.com,  dsfsfd@ccc.com, asd@c.om"));
       
       System.out.println(formatEmail("sad@qq.com,  dsfsfd@ccc.com, asd@c.om,   ")+"======");
       System.out.println(formatEmail("sad@qq.com ,  dsfsfd@ccc.com , asd@c.om  ")+"======");
       System.out.println(formatEmail("sad@qq.com    ")+"======");
       System.out.println(formatEmail("sad@qq.com")+"======");
       System.out.println(formatEmail("sad@qq.com,    ")+"======");
       System.out.println(formatEmail("sad@qq.com    ,    ")+"======");
       System.out.println(formatEmail("")+"======");
    }
}




原创粉丝点击