1,加密的Util类
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2004, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------- * AbstractElementDefinitionHandler.java * ------------------------------------- * (C)opyright 2003, by Thomas Morgner and Contributors. * * Original Author: Kevin Kelley <kelley@ruralnet.net> - * 30718 Rd. 28, La Junta, CO, 81050 USA. // * * $Id: Base64.java,v 1.5 2004/01/01 23:59:29 mungady Exp $ * * Changes * ------------------------- * 23.09.2003 : Initial version * */ package com.zte.aspportal.comm.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.CharArrayWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; /** * Provides encoding of raw bytes to base64-encoded characters, and * decoding of base64 characters to raw bytes. * date: 06 August 1998 * modified: 14 February 2000 * modified: 22 September 2000 * * @author Kevin Kelley (kelley@ruralnet.net) * @version 1.3 */ public class Base64 { /** * returns an array of base64-encoded characters to represent the * passed data array. * * @param data the array of bytes to encode * @return base64-coded character array. */ public static char[] encode(byte[] data) { char[] out = new char[((data.length + 2) / 3) * 4]; // // 3 bytes encode to 4 chars. Output is always an even // multiple of 4 characters. // for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { boolean quad = false; boolean trip = false; int val = (0xFF & data[i]); val <<= 8; if ((i + 1) < data.length) { val |= (0xFF & data[i + 1]); trip = true; } val <<= 8; if ((i + 2) < data.length) { val |= (0xFF & data[i + 2]); quad = true; } out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; val >>= 6; out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; val >>= 6; out[index + 1] = alphabet[val & 0x3F]; val >>= 6; out[index + 0] = alphabet[val & 0x3F]; } return out; } /** * Decodes a BASE-64 encoded stream to recover the original * data. White space before and after will be trimmed away, * but no other manipulation of the input will be performed. * * As of version 1.2 this method will properly handle input * containing junk characters (newlines and the like) rather * than throwing an error. It does this by pre-parsing the * input and generating from that a count of VALID input * characters. **/ public static byte[] decode(char[] data) { // as our input could contain non-BASE64 data (newlines, // whitespace of any sort, whatever) we must first adjust // our count of USABLE data so that... // (a) we don't misallocate the output array, and // (b) think that we miscalculated our data length // just because of extraneous throw-away junk int tempLen = data.length; for (int ix = 0; ix < data.length; ix++) { if ((data[ix] > 255) || codes[data[ix]] < 0) --tempLen; // ignore non-valid chars and padding } // calculate required length: // -- 3 bytes for every 4 valid base64 chars // -- plus 2 bytes if there are 3 extra base64 chars, // or plus 1 byte if there are 2 extra. int len = (tempLen / 4) * 3; if ((tempLen % 4) == 3) len += 2; if ((tempLen % 4) == 2) len += 1; byte[] out = new byte[len]; int shift = 0; // # of excess bits stored in accum int accum = 0; // excess bits int index = 0; // we now go through the entire array (NOT using the 'tempLen' value) for (int ix = 0; ix < data.length; ix++) { int value = (data[ix] > 255) ? -1 : codes[data[ix]]; if (value >= 0)// skip over non-code { accum <<= 6; // bits shift up by 6 each time thru shift += 6; // loop, with new bits being put in accum |= value; // at the bottom. if (shift >= 8)// whenever there are 8 or more shifted in, { shift -= 8; // write them out (from the top, leaving any out[index++] = // excess at the bottom for next iteration. (byte) ((accum >> shift) & 0xff); } } // we will also have skipped processing a padding null byte ('=') here; // these are used ONLY for padding to an even length and do not legally // occur as encoded data. for this reason we can ignore the fact that // no index++ operation occurs in that special case: the out[] array is // initialized to all-zero bytes to start with and that works to our // advantage in this combination. } // if there is STILL something wrong we just have to throw up now! if (index != out.length) { throw new Error("Miscalculated data length (wrote " + index + " instead of " + out.length + ")"); } return out; } // // code characters for values 0..63 // private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray(); // // lookup table for converting base64 characters to value in range 0..63 // private static byte[] codes = new byte[256]; static { for (int i = 0; i < 256; i++) codes[i] = -1; for (int i = 'A'; i <= 'Z'; i++) codes[i] = (byte) (i - 'A'); for (int i = 'a'; i <= 'z'; i++) codes[i] = (byte) (26 + i - 'a'); for (int i = '0'; i <= '9'; i++) codes[i] = (byte) (52 + i - '0'); codes['+'] = 62; codes['/'] = 63; } /////////////////////////////////////////////////// // remainder (main method and helper functions) is // for testing purposes only, feel free to clip it. /////////////////////////////////////////////////// public static void main(String[] args) { boolean decode = false; if (args.length == 0) { System.out.println("usage: java Base64 [-d[ecode]] filename"); System.exit(0); } for (int i = 0; i < args.length; i++) { if ("-decode".equalsIgnoreCase(args[i])) decode = true; else if ("-d".equalsIgnoreCase(args[i])) decode = true; } String filename = args[args.length - 1]; File file = new File(filename); if (!file.exists()) { System.out.println("Error: file '" + filename + "' doesn't exist!"); System.exit(0); } if (decode) { char[] encoded = readChars(file); byte[] decoded = decode(encoded); writeBytes(file, decoded); } else { byte[] decoded = readBytes(file); char[] encoded = encode(decoded); writeChars(file, encoded); } } private static byte[] readBytes(File file) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { InputStream fis = new FileInputStream(file); InputStream is = new BufferedInputStream(fis); int count = 0; byte[] buf = new byte[16384]; while ((count = is.read(buf)) != -1) { if (count > 0) baos.write(buf, 0, count); } is.close(); } catch (Exception e) { e.printStackTrace(); } return baos.toByteArray(); } private static char[] readChars(File file) { CharArrayWriter caw = new CharArrayWriter(); try { Reader fr = new FileReader(file); Reader in = new BufferedReader(fr); int count = 0; char[] buf = new char[16384]; while ((count = in.read(buf)) != -1) { if (count > 0) caw.write(buf, 0, count); } in.close(); } catch (Exception e) { e.printStackTrace(); } return caw.toCharArray(); } private static void writeBytes(File file, byte[] data) { try { OutputStream fos = new FileOutputStream(file); OutputStream os = new BufferedOutputStream(fos); os.write(data); os.close(); } catch (Exception e) { e.printStackTrace(); } } private static void writeChars(File file, char[] data) { try { Writer fos = new FileWriter(file); Writer os = new BufferedWriter(fos); os.write(data); os.close(); } catch (Exception e) { e.printStackTrace(); } } /////////////////////////////////////////////////// // end of test code. /////////////////////////////////////////////////// }
2,解析xml里面的util类
package com.zte.aspportal.comm.util; import java.net.URL; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.log4j.Logger; import org.jaxen.JaxenException; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * 解析XML文件 * @author zw * */ public class Config { // private static String ETC_PATH = System.getProperty("TOMCAT_HOME"); private Document document; private URL confURL; private Logger log = Logger.getLogger(this.getClass()); public Config(String filename) { if (filename.trim().length() == 0) { filename = "config.xml"; } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); confURL = Config.class.getClassLoader().getResource(filename); if (confURL == null) { confURL = ClassLoader.getSystemResource(filename); } if (confURL != null) { log.info(confURL.toString()); } else { log.info(filename + " not found: "); } document = db.parse(confURL.openStream()); } catch (Exception e) { e.printStackTrace(); } } private String getNodeValue(String xpath) { try { DOMXPath path = new DOMXPath(xpath); if (path == null) { log.info("Unresolvable xpath " + xpath); return null; } Node node = (Node) path.selectSingleNode(document .getDocumentElement()); if (node == null) { log.info("Xpath " + xpath + " seems void"); return null; } if (node.hasChildNodes()) { Node child = node.getFirstChild(); if (child != null) return child.getNodeValue(); } else return ""; } catch (JaxenException e) { e.printStackTrace(); } return null; } public long getLongValue(String xpath, long fallback) { try { String value = getNodeValue(xpath); if (value != null) return Long.parseLong(value); } catch (NumberFormatException e) { e.printStackTrace(); } log.info("Using fallback value ( " + fallback + " ) for " + xpath); return fallback; } public String getStringValue(String xpath, String fallback) { String value = getNodeValue(xpath); if (value != null) return value; log.info("Using fallback value ( " + fallback + " ) for " + xpath); return fallback; } public int getIntValue(String xpath, int fallback) { String value = getNodeValue(xpath); if (value != null && !"".equals(value.trim())) { return Integer.valueOf(value); } log.info("Using fallback value ( " + fallback + " ) for " + xpath); return fallback; } }
3,ftp上传下载的util类
package com.zte.aspportal.comm.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class FtpUtil { /** * ftp上传方法 * @param username * @param username * @param password * @param path * @param url * @param filename * @param file * @return */ public static boolean ftpUploadFile(String url,String username, String password, String path, String filename, File file) { boolean success = false; //判断上传路径是否存在,如果不存在,则新建一个 FTPClient ftp = new FTPClient(); try{ int reply; ftp.connect(url); ftp.login(username, password); reply = ftp.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)){ ftp.disconnect(); return success; } // 转到指定上传目录 ftp.changeWorkingDirectory(path); ftp.setFileType(FTP.BINARY_FILE_TYPE); //设置为2进制上传 // 将上传文件存储到指定目录 InputStream input=new FileInputStream(file); ftp.storeFile(new String(filename.getBytes(),Constants.UPLOADENCODING), input); input.close(); ftp.logout(); success = true; }catch(IOException e){ e.printStackTrace(); }finally{ if(ftp.isConnected()){ try{ ftp.disconnect(); }catch (IOException e) { e.printStackTrace(); } } } return success; } /** * Description: 从FTP服务器下载文件 * * @param url * FTP服务器hostname * @param username * FTP登录账号 * @param password * FTP登录密码 * @param remotePath * FTP服务器上的相对路径 * @param fileName * 下载时的默认文件名 * @return * @throws IOException */ public static boolean ftpDownFile(String url, String username, String password, String remotePath, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException { // 初始表示下载失败 boolean success = false; // 创建FTPClient对象 FTPClient ftp = new FTPClient(); try { int reply; // 连接FTP服务器 // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器 ftp.connect(url); // 登录ftp ftp.login(username, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } String realName = remotePath .substring(remotePath.lastIndexOf("/") + 1); // 转到指定下载目录 ftp.changeWorkingDirectory(remotePath.substring(0, remotePath .lastIndexOf("/") + 1)); ftp.setFileType(FTP.BINARY_FILE_TYPE); String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { String codedfilename = URLEncoder.encode(fileName, "UTF8"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { String codedfilename = MimeUtility.encodeText(fileName, "UTF8", "B"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else { response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); } // 设置文件下载头部 // response.setContentType("application/x-msdownload");// 设置编码 // response.setContentType("application/octet-stream; CHARSET=UTF-8"); // response.setHeader("Content-Disposition", "attachement;filename=" // + new String(fileName.getBytes("ISO8859-1"), "UTF-8")); FTPFile[] fs = ftp.listFiles(); // 遍历所有文件,找到指定的文件 for (FTPFile ff : fs) { String ftpFile = new String( ff.getName().getBytes("ISO-8859-1"), "gbk"); if (ftpFile.equals(realName)) { OutputStream out = response.getOutputStream(); InputStream bis = ftp.retrieveFileStream(ff.getName()); // 根据绝对路径初始化文件 // 输出流 int len = 0; byte[] buf = new byte[1024]; while ((len = bis.read(buf)) > 0) { out.write(buf, 0, len); out.flush(); } out.close(); bis.close(); break; } } ftp.logout(); // 下载成功 success = true; } catch (IOException e) { success = false; throw e; } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } }
4,sftp协议的上传下载
package com.zte.aspportal.comm.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Vector; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; import com.jcraft.jsch.ChannelSftp.LsEntry; public class SftpUtil { Logger logger = Logger.getLogger(SftpUtil.class); public static final String OLD_NAME= "oldname"; public static final String NEW_NAME= "newname"; /** * 连接sftp服务器 * @param host 主机 * @param port 端口 * @param username 用户名 * @param password 密码 * @return */ public ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); Session sshSession = jsch.getSession(username, host, port); System.out.println("Session created."); sshSession.setPassword(password); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); sshSession.setConfig(sshConfig); sshSession.connect(); System.out.println("Session connected."); System.out.println("Opening Channel."); Channel channel = sshSession.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; System.out.println("Connected to " + host + "."); } catch (Exception e) { e.printStackTrace(); } return sftp; } /** * 上传文件 * @param directory 上传的目录 * @param uploadFile 要上传的文件 * @param sftp */ public boolean upload(String url,String username,String password,String port,String directory,String filename, File file) { boolean success = false; try { ChannelSftp sftp=this.connect(url, Integer.valueOf(port), username, password); sftp.cd(directory); InputStream input=new FileInputStream(file); sftp.put(input, new String(filename.getBytes(),Constants.UPLOADENCODING)); //关闭连接 sftp.disconnect(); success = true; } catch (Exception e) { e.printStackTrace(); } return success; } /** * 下载文件 * @param directory 下载目录 * @param downloadFile 下载的文件 * @param saveFile 存在本地的路径 * @param sftp */ public String download(String url,String username,String password,String port,String directory, String downloadFile,String saveFile,HttpServletRequest request,HttpServletResponse response) { String success = null; ChannelSftp sftp=connect(url, Integer.valueOf(port), username, password); try { sftp.cd(directory); String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { String codedfilename = downloadFile; response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { String codedfilename = MimeUtility.encodeText(downloadFile.replaceAll(" ", "_"), "UTF8", "B"); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename); } else { response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment;filename=" + downloadFile); } OutputStream out = response.getOutputStream(); InputStream bis = sftp.get(downloadFile); // 根据绝对路径初始化文件 // 输出流 int len = 0; byte[] buf = new byte[1024]; while ((len = bis.read(buf)) > 0) { out.write(buf, 0, len); out.flush(); } out.close(); bis.close(); //关闭连接 sftp.disconnect(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SftpException e) { //success = e.getCause().getMessage(); //logger.info(success); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } /** * * @param url * @param username * @param password * @param directory * @param fileList 格式 修改文件名称列表,其中的每个map中,原先名字键值为SftpUtil.OLD_NAME 需要修改后的名字键值为SftpUtil.NEW_NAME * @return */ public boolean reName(String url,String username,String password,String port,String directory,List<Map<String, String>> fileList) { boolean success = false; try { ChannelSftp sftp=connect(url, Integer.valueOf(port), username, password); sftp.cd(directory); for(int i=0;i<fileList.size();i++){ Map<String, String> map = fileList.get(i); sftp.rename(map.get(OLD_NAME), map.get(NEW_NAME)); } //关闭连接 sftp.disconnect(); success=true; } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } return success; } /** * 返回文件名称中包含fileNameContains所给字符串的文件列表 * @param url * @param username * @param password * @param directory * @param fileNameContains * @return */ public List<String> getFileList(String url,String username,String password,String port,String directory,String fileNameContains){ List<String> fileList = new ArrayList<String>(); try { ChannelSftp sftp=connect(url, Integer.valueOf(port), username, password); sftp.cd(directory); Vector vector = sftp.ls(directory); if(fileNameContains==null){ fileNameContains = ""; } for(int i=0;i<vector.size();i++){ LsEntry lsEntry = (LsEntry)vector.get(i); String fileName = lsEntry.getFilename(); if (fileName.contains(fileNameContains)) { fileList.add(fileName); } } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } return fileList; } public static void main(String[] args) throws UnsupportedEncodingException { ChannelSftp sftp=new SftpUtil().connect("10.10.10.10",22, "user", "password"); try { String string="/home/user/test2/LY/"; // String string="1000000100_L S¨¦verin 48 M Pr¨¦sla"; String string2="/home/user/test2/1000000100_L Sverin 48 M Prsla/"; sftp.cd(new String(string.getBytes("UTF-8"),"ISO-8859-1")); sftp.cd(new String(string.getBytes("UTF-8"),"UTF-8")); sftp.cd(new String(string.getBytes("UTF-8"),"GBK")); sftp.cd(new String(string.getBytes("ISO-8859-1"),"ISO-8859-1")); sftp.cd(new String(string.getBytes("ISO-8859-1"),"UTF-8")); sftp.cd(new String(string.getBytes("ISO-8859-1"),"GBK")); sftp.cd(new String(string.getBytes("GBK"),"ISO-8859-1")); sftp.cd(new String(string.getBytes("GBK"),"UTF-8")); sftp.cd(new String(string.getBytes("GBK"),"GBK")); System.out.println(new String(new String(new String(string.getBytes("UTF-8"), "ISO-8859-1") .getBytes("ISO-8859-1"), "UTF-8").getBytes(), "ISO-8859-1")); sftp.cd(string); } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
5,生成校验码的util类
package com.zte.aspportal.comm.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class RandImgCreater extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest request, HttpServletResponse response){ HttpSession session=request.getSession(true); //设置页面不缓存 response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); // 在内存中创建图象 int width=53, height=18; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文 Graphics g = image.getGraphics(); //生成随机类 Random random = new Random(); // 设定背景色 g.setColor(this.getRandColor(200,250)); g.fillRect(0, 0, width, height); //设定字体 g.setFont(new Font("Times New Roman",Font.BOLD,16)); //画边框 //g.setColor(new Color()); //g.drawRect(0,0,width-1,height-1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 g.setColor(this.getRandColor(160,200)); for (int i=0;i<155;i++){ int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x,y,x+xl,y+yl); } // 取随机产生的认证码(4位数字) String sRand=""; for (int i=0;i<4;i++){ String rand=String.valueOf(random.nextInt(10)); sRand+=rand; // 将认证码显示到图象中 g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g.drawString(rand,13*i+3,16); } // 将认证码存入SESSION session.setAttribute("rand",sRand); // 图象生效 g.dispose(); // 输出图象到页面 try{ ImageIO.write(image, "JPEG", response.getOutputStream()); }catch(Exception e){ e.printStackTrace(); } } private Color getRandColor(int fc,int bc){//给定范围获得随机颜色 Random random = new Random(); if(fc>255) fc=255; if(bc>255) bc=255; int r=fc+random.nextInt(bc-fc); int g=fc+random.nextInt(bc-fc); int b=fc+random.nextInt(bc-fc); return new Color(r,g,b); } }
package com.zte.aspportal.comm.util; import java.util.Date; import java.util.Random; public class RandUtil { public static String gettempName(String filename) { String postfix = ""; postfix = filename.substring(filename.lastIndexOf(".")); Date nowTime = new Date(); String name = nowTime.getTime() + postfix; return name; } public static String getRandomString(int length,int type) { String figureBase = "0123456789"; String letterBase = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; String letterAndFigureBase = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); switch (type) { case 0: for (int i = 0; i < length; i++) { int number = random.nextInt(figureBase.length()); sb.append(figureBase.charAt(number)); } break; case 1: for (int i = 0; i < length; i++) { int number = random.nextInt(letterBase.length()); sb.append(letterBase.charAt(number)); } break; case 2: for (int i = 0; i < length; i++) { int number = random.nextInt(letterAndFigureBase.length()); sb.append(letterAndFigureBase.charAt(number)); } break; default: for (int i = 0; i < length; i++) { int number = random.nextInt(figureBase.length()); sb.append(figureBase.charAt(number)); } break; } return sb.toString(); } }
6,简单的邮件发送stmp3协议的util类
package com.zte.aspportal.comm.util; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * 简单邮件(不带附件的邮件)发送器 * @author zhangwei * */ public class SimpleMailSender { /** * 以文本格式发送邮件 * @param mailInfo 待发送的邮件的信息 */ public boolean sendTextMail(MailSenderInfo mailInfo) throws MessagingException { // 判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { // 如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getEmail(), mailInfo.getPassword()); } // 根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro,authenticator); // 根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); // 创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); // 设置邮件消息的发送者 mailMessage.setFrom(from); // 创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO,to); // 设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); // 设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); // 设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); // 发送邮件 Transport.send(mailMessage); return true; } /** * 以html形式发送邮件 * @param mailInfo 待发送的邮件的信息 */ public static boolean sendHtmlMail(MailSenderInfo mailInfo) { MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getEmail(), mailInfo.getPassword()); } Session sendMailSession = Session.getDefaultInstance(pro, authenticator); sendMailSession.setDebug(true); try { Message mailMessage = new MimeMessage(sendMailSession); Address from = new InternetAddress(mailInfo.getFromAddress()); mailMessage.setFrom(from); Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO,to); mailMessage.setSubject(mailInfo.getSubject()); mailMessage.setSentDate(new Date()); //MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); //创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); //设置HTML内容 html.setContent(mailInfo.getContent(),"text/html; charset=utf-8"); mainPart.addBodyPart(html); // 将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); //发送邮件 mailMessage.saveChanges(); Transport transport = sendMailSession.getTransport("smtp"); transport.connect(mailInfo.getMailServerHost(),mailInfo.getUserName(),mailInfo.getPassword()); transport.sendMessage(mailMessage, mailMessage.getAllRecipients()); transport.close(); return true; } catch (MessagingException ex) { ex.printStackTrace(); } return false; } }
7,常用的日期转换等工具util类
package com.zte.aspportal.comm.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import com.zte.aspportal.user.bean.Developer; /** * 工具类 * @author zw * */ public class SysUtils { public static Logger log = Logger.getLogger(SysUtils.class); /** * 获得当前日期和时间 * * @return String 当前日期和时间,格式:yyyy-MM-dd HH:mi:ss */ public static String getCurDateTime() { SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return nowDate.format(new Date()); } /** * 格式化日期, yyyyMMddHHmmss -> yyyy-MM-dd HH:mm:ss * @param str * @return */ public static String formatDateFullTime(String str){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = null; try { date = sdf.parse(str); } catch (Exception e) { log.error(e); } sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format(date); } /** * 格式化日期,将日期从yyyy-MM-dd HH:mm:ss转换为yyyyMMddHHmmss * * @param strDateTime * String * @return String */ public static String formatDateTime(String strDate) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = sdf.parse(strDate); } catch (ParseException e) { log.error("SysUtils formatDateTime is exception ", e); } sdf = new SimpleDateFormat("yyyyMMddHHmmss"); return sdf.format(date); } /** * 比较两个日期yyyyMMddHHmmss类型大小 * firstDate>secondDate return 1 * firstDate=secondDate return 0 * firstDate<secondDate return -1 * @param firstDate * @param secondDate * @return */ public static int compareDate(String firstDate,String secondDate) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = null; Date date2 = null; try { date = sdf.parse(firstDate); date2 = sdf.parse(secondDate); return date.compareTo(date2); } catch (ParseException e) { log.error("SysUtils formatDateTime is exception ", e); } return -1; } /** * 格式化日期,将日期转换为yyyyMMddHHmmss * * @param date * @return */ public static String formatLongDateTime(Date date) { return new SimpleDateFormat("yyyyMMddHHmmss").format(date); } /** * 格式化日期字符串 * 2011-10-10 转换为20111010 * @param str * @return */ public static String formatStrTime(String str) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = sdf.parse(str); } catch (ParseException e) { log.error("SysUtils formatDateTime is exception ", e); } sdf = new SimpleDateFormat("yyyyMMdd"); return sdf.format(date); } /** * 判断String是否为空 * * @param str * @return */ public static boolean isNull(String str) { boolean flag = false; if (str == null || "".equals(str)) { flag = true; } return flag; } /** * 获得当前日期 * * @return String 当前日期,格式:yyyyMMddHHmmss */ public static String getCurDate() { SimpleDateFormat nowDate = new SimpleDateFormat("yyyyMMddHHmmss"); return nowDate.format(new Date()); } /** * 获取需要的日期格式 * @param currentDate 当前日期格式 * @param formateDate 转换日期格式 * @param date 传入值 * @return */ public static String getFormateDate(String currentDate,String formateDate,String date) { try { Date dt = new SimpleDateFormat(currentDate).parse(date); return new SimpleDateFormat(formateDate).format(dt); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 获取指定年限后的日期 格式:yyyyMMddHHmmss * @return */ public static String getCurYearDate(Integer year){ String date = getCurDate(); Integer yyyy = Integer.parseInt(date.substring(0,4))+year; String result = yyyy+date.substring(4); return result; } /** * 非空判断 * * @param param * 参数 * @return string */ public static String trim(String param) { return null == param ? "" : param.trim(); } /** * 设置当前登录用户信息至session * @param request * @param developer */ public static void setCurrUSERINFO(HttpServletRequest request, Developer developer) { request.getSession().setAttribute("userinfo",developer); } /** * 移除当前登录信息 * @param request */ public static void removeCurrUSERINFO(HttpServletRequest request) { request.getSession().removeAttribute("userinfo"); } /** * 获取当前登录用户信息 * @param request * @return */ public static Developer getCurrUSERINFO(HttpServletRequest request) { Developer developer = (Developer)request.getSession().getAttribute("userinfo"); return developer; } }
8,ftp ,sftp上传下载的开关控制类
package com.zte.aspportal.comm.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import com.jcraft.jsch.ChannelSftp; import com.zte.toolstore.tools.InitConstants; public class UploadUtil { /** * 判断开关中是什么文件上传方式 * @return */ public static boolean getUploadType(){ String uploadtype = InitConstants.getInstance().getString("uploadtype"); if (uploadtype==null||uploadtype.equals("")) { uploadtype="0"; } return Integer.valueOf(uploadtype) == 0 ? false:true; } /** * 上传方法 * @param url * @param username * @param password * @param path * @param filename * @param file * @return */ public static boolean uploadFile(String url,String username, String password, String port,String path, String filename, File file) { boolean success = false; checkDirAndCreate(path); //sftp方式上传 if(getUploadType()){ SftpUtil sftpUtil = new SftpUtil(); success=sftpUtil.upload(url,username,password,port,path,filename,file); return success; } //ftp方式上传 else{ FtpUtil ftpUtil = new FtpUtil(); success= ftpUtil.ftpUploadFile(url, username, password, path, filename, file); return success; } } /** * Description: 从FTP服务器下载文件 * * @param url * FTP服务器hostname * @param username * FTP登录账号 * @param password * FTP登录密码 * @param remotePath * FTP服务器上的相对路径 * @param fileName * 下载时的默认文件名 * @return * @throws IOException */ public static boolean downFile(String url, String username, String password,String port, String remotePath, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException { // 初始表示下载失败 boolean success = false; String success2 = null; if(getUploadType()){//sftp方式下载 SftpUtil sftpUtil = new SftpUtil(); remotePath = remotePath.substring(0,remotePath.lastIndexOf("/")+ 1); success2=sftpUtil.download(url,username,password,port,remotePath,fileName,fileName,request,response); if(success2==null){ success = true; } return success; }else {//ftp方式下载 FtpUtil ftpUtil = new FtpUtil(); success=ftpUtil.ftpDownFile(url, username, password, remotePath, fileName, request, response); return success; } } /** * 检查一个路径是否存在,如果不存在,则创建该目录 * * @param fileDir * 目录路径 * @return 如果目录存在,则返回True,否则返回False。 */ public static boolean checkDirAndCreate(String fileDir) { File file = new File(fileDir); if (!file.exists()) { return file.mkdirs(); } return true; } }
9,解析word的util类
package com.zte.aspportal.comm.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.apache.poi.POIXMLDocument; import org.apache.poi.POIXMLTextExtractor; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.model.PicturesTable; import org.apache.poi.hwpf.usermodel.CharacterRun; import org.apache.poi.hwpf.usermodel.Picture; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFPictureData; import org.apache.struts2.ServletActionContext; import com.zte.aspportal.capability.bean.CapaBilityMethod; import com.zte.aspportal.capability.dao.impl.CapaBilityMethodDaoImpl; import com.zte.toolstore.tools.InitConstants; public class WordParser { /** * 读取word2003文本 */ public String extractMSWordText(File file) { try { InputStream input = new FileInputStream(file); HWPFDocument msWord=new HWPFDocument(input); Range range = msWord.getRange(); String msWordText = range.text(); return msWordText; } catch (IOException e) { e.printStackTrace(); } return null; } /** * 读取word2003图片 */ public void extractImagesIntoDirectory(String directory,File file) throws IOException { InputStream input = new FileInputStream(file); HWPFDocument msWord=new HWPFDocument(input); PicturesTable pTable = msWord.getPicturesTable(); int numCharacterRuns = msWord.getRange().numCharacterRuns(); for (int i = 0; i < numCharacterRuns; i++) { CharacterRun characterRun = msWord.getRange().getCharacterRun(i); if (pTable.hasPicture(characterRun)) { System.out.println("have picture!"); Picture pic = pTable.extractPicture(characterRun, false); String fileName = pic.suggestFullFileName(); OutputStream out = new FileOutputStream(new File(directory + File.separator + fileName)); pic.writeImageContent(out); } } } /** * 读取word2007文本 */ public String extractContent(File document) { String contents=""; String wordDocxPath=document.toString(); try { OPCPackage opcPackage=POIXMLDocument.openPackage(wordDocxPath); XWPFDocument xwpfd=new XWPFDocument(opcPackage); POIXMLTextExtractor ex = new XWPFWordExtractor(xwpfd); //读取文字 contents= ex.getText().trim(); } catch (IOException e) { e.printStackTrace(); } return contents; } /** * 读取word2007图片 */ public String[] extractImage(File document,String imgPath){//document获取word路径,imgPath图片保存路径 String wordDocxPath = document.toString(); String[] photopath = null; try { //载入文档 OPCPackage opcPackage= POIXMLDocument.openPackage(wordDocxPath); XWPFDocument xwpfd = new XWPFDocument(opcPackage); //建立图片文件目录 File file = new File(imgPath); if(!file.exists()){ file.mkdir(); } //获取所有图片 List<XWPFPictureData> piclist=xwpfd.getAllPictures(); photopath = new String[piclist.size()]; for (int i = 0; i < piclist.size(); i++) { XWPFPictureData pic = (XWPFPictureData)piclist.get(i); Integer index = Integer.parseInt(pic.getFileName().substring(5,pic.getFileName().lastIndexOf(".")));//确定图片顺序 //获取图片数据流 byte[] picbyte = pic.getData(); //将图片写入本地文件 String path ="/uploadfiles/cap"+File.separator+UUIDGenerate.getUUID()+".jpg"; FileOutputStream fos = new FileOutputStream(imgPath+path); fos.write(picbyte); photopath[index-1]=path; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return photopath; } /** * 测试 */ public static void main(String[] args) { WordParser word = new WordParser(); File file = new File("d://word/sample1.docx"); String[] photoPath = word.extractImage(file,"D:\\workSpace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\aspportal"); String wordText=word.extractContent(file); System.out.println(wordText); wordText = wordText.replaceAll("\n", "<br/>"); wordText = wordText.replaceAll("\t", " "); String[] wordArray = wordText.split("--------"); Integer methodSize = wordArray.length/6; for(int i=0;i<methodSize;i++) { CapaBilityMethod method = new CapaBilityMethod(); method.setSrvtypeid("2"); method.setMethodname(wordArray[6*i+1].replaceAll("<br/>", "")); method.setWebdesc(wordArray[6*i+2].replaceFirst("<br/>", "")); method.setParams(wordArray[6*i+3].replaceFirst("<br/>", "")); method.setAuth(wordArray[6*i+4].replaceFirst("<br/>", "")); method.setSample(photoPath[i]); method.setErrors(wordArray[6*i+6].replaceFirst("<br/>", "")); CapaBilityMethodDaoImpl methodDao = new CapaBilityMethodDaoImpl(); methodDao.addMethod(method); } } }
发表评论
-
manven构建spring+springmvc+mybaitis框架
2016-04-23 22:51 0最近要离职了,闲暇的时候想自己构建个项目,说干就干。 具体 ... -
有个内存溢出的问题请教啊!
2015-08-18 16:58 975public Map<String, Object ... -
六年JAVA兼职
2014-10-10 14:08 355我叫刘洋,JAVA开发做了六年多了,大大小小的项目做过很多 ... -
新手搭车maven
2014-04-29 15:50 59最近工作太繁忙,一直没有时间来充电。 偶然的一个机会 ... -
关于DB2日常使用中遇到的问题
2013-07-30 10:07 8421 经常需要用到在不drop表的前提下去修改表字段的数据 ... -
我还年轻,我渴望上路.
2012-12-02 09:19 72不知不觉快工作两年多了,最近玩的也比较多,是时候放下玩的心了, ... -
ijetty的应用开发
2012-11-30 16:29 3188最近使用ijetty开发了一 ... -
求助一个关于公式编辑器插件的问题。
2012-08-09 11:27 74附件是一个网页可用的公式编辑器插件。 总体上很符合我想找的 ... -
关于java优化的东东
2012-07-17 11:33 949最近的机器内存又爆满了,除了新增机器内存外,还应该好好revi ... -
struts2国际化文件配置
2012-07-16 14:51 12629struts2的国际化分三种情况:前台页面的国际化,Act ... -
web.xml常用标签命令详解
2012-06-13 14:14 5353web.xml文件是用来初始化配置信息:比如welcome页面 ... -
关于常用的一些linux下命令
2012-06-12 17:14 8971,linux 创建文件 mkdir XXX 创建目录 ... -
做java开发的困惑
2012-06-05 20:23 1024从事java开发也快两年了。 忽然很迷茫了。 也发现越来越 ... -
build的那些东西
2012-05-30 16:01 1138<?xml version="1.0" ... -
项目数据库执行
2012-04-19 15:44 1380DBtool.java package com.zte ... -
HTTPClient发送请求的几种实现
2012-04-01 17:21 139341,可以使用最基本的流对象 URL对象直接将请求封装 然后发送 ... -
静态页面拖拽实现代码
2012-04-01 17:18 1055静态拖拽行: <html> ... -
回忆 struts1/2
2012-04-01 17:14 1081struts1 与 struts2的对比。 action类 ...
相关推荐
在这个压缩包文件“常用的公共类”中,我们可以期待找到一系列与Java开发相关的源代码,它们可能涵盖了诸如Util、Config等类别,这些都是Java开发中的基础和核心部分。 Util类是Java开发中的实用工具类,通常包含了...
在Android Java开发中,工具类(Utils类)是开发者经常使用的辅助代码集合,它们封装了各种通用功能,以便在项目中快速调用。这个名为"java-utils-master"的压缩包很可能是包含了一系列实用工具类的开源项目。下面,...
在这个标题为“Flex3中用到的工具类包,含有json类”的资源中,我们可以看到它包含了处理JSON(JavaScript Object Notation)数据的工具类。JSON是一种轻量级的数据交换格式,由于其简洁和高效的特性,在网络通信中...
本资源"API大全api大全中文版(包含开发中用到的所有api)"是一个集合了多种Java API的宝贵资料,由多年的开发经验积累而成,旨在为开发者提供全面的参考。 在Java世界中,API涵盖了标准库(如Java SE、Java EE)、第...
Java API大全是一个全面涵盖Java开发所需的各种类库和接口的集合,它包含了Java语言的核心类库,如`java.lang`, `java.util`, `java.io`, `java.net`等,以及Java标准扩展,如`javax.swing`(用于图形用户界面)和`...
除了上述的几个主要类别,这个压缩包可能还包含了其他实用工具类,如日期时间处理(DateUtil)、字符串操作(StringUtil)、文件操作(FileUtil)、线程池管理(ThreadPoolUtil)等。这些工具类通常提供了静态方法...
1. **StringUtil.java**:字符串处理工具类,通常包含各种对字符串进行操作的方法,如拼接、分割、格式化、去除空格、检查是否为空等。在Java开发中,对字符串的操作非常频繁,此类能够简化这部分工作。 2. **...
### Android中用Application类实现全局变量 在Android开发过程中,我们常常需要在多个组件之间共享数据,例如存储用户的登录状态、应用配置等信息。通常情况下,开发者会利用`SharedPreferences`或者`...
3. **BufferedImage类**: `java.awt.image.BufferedImage`是Java中用于存储图像数据的类,它提供了对图像像素的直接访问,允许我们进行像素级别的操作,例如添加水印。 4. **水印处理**: 添加水印通常涉及在图像上...
Java支持多语言环境,通过`java.util.ResourceBundle`和`java.text.MessageFormat`类实现国际化。资源文件(如messages.properties)用于存储不同语言的文本,程序根据用户的语言偏好加载相应的文件。 8. **邮件...
其次,日常开发中用到的工具类通常是为了提高代码的可读性和复用性。这些工具类可能包括字符串处理、日期时间操作、IO流处理、JSON序列化和反序列化等。例如,Apache Commons Lang库提供了丰富的字符串操作方法,...
"idea中用到的lib下的jar包"这个主题主要涉及到如何在IntelliJ IDEA中管理和使用这些库中的.jar文件。下面将详细阐述这些.jar文件及其在Java开发中的作用。 1. **c3p0-0.9.1.2.jar**:这是一个数据库连接池库,提供...
这个"案例中用到的Velocity_jar包"是Velocity的核心库,包含了运行Velocity模板引擎所需的所有类和资源。 在Java Web开发中,Velocity被广泛用于生成动态内容,如电子邮件、报告、网页等。它的工作原理是通过解析...
Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。
Java开发中中经常使用的Java工具类分享,工作中用得上,直接拿来使用,不用重复造轮子。
在MVC架构中,`util`包通常包含一些通用的工具类或辅助方法,例如上述的文件上传和下载功能可以封装成一个工具类,以便在项目中复用。这样,我们就可以在不重复编写相同代码的情况下,轻松地在多个地方实现文件上传...