開発で使用したUTILクラス
1,暗号化されたUtilクラス
2,xml内のutilクラスを解析する
3,ftpでダウンロードしたutilクラスをアップロード
4,sftpプロトコルのアップロードダウンロード
5,検証コードのutilクラスを生成する
6,簡単なメールstmp 3プロトコルのutilクラスを送信する
7,常用の日付変換等のツールutil類
8,ftp,sftpアップロードダウンロードのスイッチ制御クラス
9,wordの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 <[email protected]> -
* 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 ([email protected])
* @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,簡単なメールstmp 3プロトコルの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("
", "<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);
}
}
}