`
收藏列表
标题 标签 来源
maven常用仓库 maven
<repositories>
        <!-- For testing against latest Spring snapshots -->
        <repository>
            <id>org.springframework.maven.snapshot</id>
            <name>Spring Maven Snapshot Repository</name>
            <url>http://maven.springframework.org/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <!-- For developing against latest Spring milestones -->
        <repository>
            <id>org.springframework.maven.milestone</id>
            <name>Spring Maven Milestone Repository</name>
            <url>http://maven.springframework.org/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>glassfish-maven-repository.dev.java.net</id>
            <name>GlassFish Maven Repository</name>
            <url>http://download.java.net/maven/glassfish</url>
        </repository>
        <repository>
            <id>thirdparty-releases</id>
            <name>JBoss Thirdparty Releases</name>
            <url>https://repository.jboss.org/nexus/content/repositories/thirdparty-releases</url>
        </repository>
        <repository>
            <id>java.net</id>
            <url>http://download.java.net/maven/2/</url>
        </repository>
    </repositories>
java使用logback组件替换log4j组件 java
如果需要替换日志组件需要在web.xml文件配置
<context-param>
	<param-name>logbackConfigLocation</param-name>
	<param-value>classpath:logback.xml</param-value>
</context-param>
<listener>
	<listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
</listener>
同时需要在pom中添加依赖
<dependency>
	<groupId>org.logback-extensions</groupId>
	<artifactId>logback-ext-spring</artifactId>
	<version>0.1.2</version>
</dependency>
-----------------------------------------------------
javascript 时区问题 javascript, timezone
function parseDateByMsOverTimeZone(ms){
	if(ms){
		var date = new Date(parseInt($.trim(ms)));
                //夏令时
		var tzo= Math.max(new Date(new Date().getYear(), 0, 1).getTimezoneOffset(),new Date(new Date().getYear(), 6, 1).getTimezoneOffset())/60;
		if(tzo > 0){
			date = new Date(date.getTime() + tzo*60*60*1000);
		}
		return (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
	}else{
		return '';
	}
}

http://norbertlindenberg.com/ecmascript/intl.html#sec-12.1
http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/
java获取classpath的路径并保存文件到classpath下 java.file, classpath 因为FileOutputStream必须要根据根路径+文件名来保存,因此只要我们获取到根路径即可保存文件。
Java中如何获取application当前运行的classpath路径
className.getResource("/");
例如:Integer.class.getResource("/");
返回值类似
E:/GIT/Anjular/target/classes/ 或者D:/Workspace/SPO/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Angular/WEB-INF/classes
然后可以推算到Application的根路径是
E:/GIT/Anjular/ 或者D:/Workspace/SPO/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Angular/

ClassPathResource res = new ClassPathResource("temp/test.cvs");
String fileName = "partner" + DateUtil.formatDate(new Date(), "yyyyMMdd_hhmmss") + ".cvs";
System.out.println(res.getURL().getPath().replace("test.cvs", fileName));
FileOutputStream fos = FileUtils.openOutputStream(new File(res.getURL().getPath().replace("test.cvs", fileName)));


package com.hp.angular.portal.controller;

import java.net.URISyntaxException;
import java.net.URL;

import org.springframework.util.ResourceUtils;

/**
 * 
 * This class is used to get the running application classpath
 * 
 * @author heji
 *
 */
public class ClassPathUtils {
	private static URL url = Integer.class.getResource("/");
	
	public static String getClassPath(){
		try {
			return ResourceUtils.toURI(url).getPath().substring(1);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String getRootPathForApplication(){
		String path = getClassPath();
		path = path.substring(0,path.lastIndexOf("/classes"));
		return path.substring(0,path.lastIndexOf("/")+1);
	}
	
	public static void main(String[] args) {
		System.out.println(getRootPathForApplication());
	}
}
Ubuntu下安装Java Ubuntu下安装Java
    sudo add-apt-repository ppa:eugenesan/java

  sudo apt-get update

  sudo apt-get install oracle-java6-installer

http://www.cnblogs.com/Wisp/articles/3099494.html
此链接介绍原因安装失败
Mybatis There is no getter for property named 'rowidOrg' in 'class java.lang.String', mybatis 参考9楼的答案
<if test="classid!=null and classid != ''">
   and ka_classid = #{classid}
  </if>

改为

 and ka_classid = #{classid}

把标签去掉就可以了,标签是针对JAVABEAN或者MAP的,STRING不能用标签

假如我们传入一个null给classid 则会出现invalid column type 1111

此时我们需要做的是设置它的类型,
#{classid,jdbcType=VARCHAR}

或者在我们的方法中
methodName(@Param(value="orgId") String orgId)加上一个Annotation即可
wsimport 自动生成的代码调用 java, soap
假如我们使用wsimport自动生成代码,
wsimport -s ./src http://localhost:8080/customer-manager/services/OrganizationNationalIdentificationService?wsdl -p com.hp.it.mdm.core.ws.test

自动生成代码后会有一系列的java文件
CreateUpdateOrganizationNationalIdentificationRequest.java
CreateUpdateOrganizationNationalIdentificationResponse.java
Message.java
ObjectFactory.java
OrganizationNationalIdentificationService.java
OrganizationNationalIdentificationServiceService.java
package-info.java
Response.java

测试代码
package com.hp.it.mdm.core.ws.test;

import java.util.ArrayList;

/**
 * @author jian.he3@hp.com
 *
 */
public class OrganizationNationalIdentificationTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		OrganizationNationalIdentificationServiceService factory = new OrganizationNationalIdentificationServiceService();
		OrganizationNationalIdentificationService service = factory.getOrganizationNationalIdentificationServicePort();
		Holder<String> countryCode = new Holder<String>("CN");
		Holder<String> organizationNationalIdentificationTypeCode = new Holder<String>("ACD");
		Holder<String> organizationNationalIdentificationValueName = new Holder<String>("test");
		Holder<String> recordStatus = new Holder<String>("N");
		String rowidIdentificationIssuerOrganization = "222";
		Holder<String> rowidObject = new Holder<String>("123");
		Holder<String> rowidOrganization = new Holder<String>("345");
		Holder<List<Message>> errors = new Holder<List<Message>>(new ArrayList<Message>());
		Holder<List<Message>> messages =  new Holder<List<Message>>(new ArrayList<Message>());
		//at this line,you will feel curious,service is an interface without an impletention
		//because the core api will automatic generate the proxy to call the remote service
		//@WebParam(name = "organizationNationalIdentificationTypeCode", targetNamespace = "", mode = WebParam.Mode.INOUT)
		//WebParam.Mode.INOUT also can use in and out
		service.createUpdateOrganizationNationalIdentification(countryCode, organizationNationalIdentificationTypeCode, organizationNationalIdentificationValueName, recordStatus, rowidIdentificationIssuerOrganization, rowidObject, rowidOrganization, errors, messages);
		System.out.println(errors.value.size());
		System.out.println(messages.value.size());
	}

}
Java 读取ClassPath下的文件 java, io, classpath java如何读取classpath下的文件,并输出成String
/**
 * Copyright 2010 Hewlett-Packard. All rights reserved. <br>
 * HP Confidential. Use is subject to license terms.
 */
package com.hp.it.mdm.core.ws;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

/**
 *
 * @author jian.he3@hp.com
 *
 */
public class XMLUtil {
	private String fileName = "template.txt";
	private String template = "";
	private String getTemplate(){
		InputStream in = ClassLoader.getSystemResourceAsStream(fileName);  
		try {
			template = IOUtils.toString(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return template;
		
	}
	
	public static void main(String[] args) {
		System.out.println(new XMLUtil().getTemplate());
	}
}

pom
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.0.1</version>
</dependency>
ToStringUtil java
 * Copyright 2010 Hewlett-Packard. All rights reserved. <br>
package com.hp.it;

import java.beans.IntrospectionException;

/**
 *
 * Dynamicly generate toString() through refelection approach
 *
 * @author jian.he3@hp.com
 *
 */
public class ToStringUtil {

	/**
	 * 
	 * @param obj that you want to generate 
	 * @return 
	 */
	public static String tostring(Object obj){
		StringBuffer buffer = new StringBuffer();
		buffer.append(obj.getClass().getSimpleName() + " [");
		Class<?> clazz = obj.getClass();
		
		Field[] fields = clazz.getDeclaredFields();
		int idx = 0;
		for(Field field : fields){
			String fieldName = field.getName();
			buffer.append(fieldName + "=" + getFieldValue(fieldName, clazz, obj));
			if(++idx < fields.length){
				buffer.append(", ");
			}
		}
		buffer.append("]");
		return buffer.toString();
	}
	
	private static Object getFieldValue(String fieldName,Class<?> clazz,Object obj){
		try {
			PropertyDescriptor descriptor = new PropertyDescriptor(fieldName, clazz);
			Method method = descriptor.getReadMethod();
			Object object = method.invoke(obj);
			return object;
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
jersey call soap service soap
call soap
====================
package com.hp.it;

import java.net.URI;

import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;

public class JerseyCallSoapWSTest {

	private ClientConfig config = new DefaultClientConfig();
	public static String url = "http://localhost:8080/customer-manager";
	public static String restfulAction = "services/PersonLookupService";
	String text = "";
	public void testCallSoapWS(){
		Client client = Client.create(config);
		client.addFilter(new LoggingFilter());
		WebResource service = client.resource(getBaseURI(url));
		ClientResponse response = service.path(restfulAction)
                 .type("text/xml")
                 //.accept(MediaType.APPLICATION_JSON)
                 .post(ClientResponse.class,getTextValue());
		System.out.println(response.getEntity(String.class));
	}
	
	private static URI getBaseURI(String uri) {
        return UriBuilder.fromUri(uri).build();
    }
	
	private String getTextValue(){
		StringBuilder builder = new StringBuilder();
		builder.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:per=\"http://personlookup.webservice.person.mdm.it.hp.com/\">");
		builder.append("<soapenv:Header/>");
		builder.append("<soapenv:Body>");
		builder.append("<per:personGet>");
		builder.append("<addressIndicator>Y</addressIndicator>");
		builder.append("<associationOrgainizationIndicator>Y</associationOrgainizationIndicator>");
		builder.append("<associationPersonIndicator>Y</associationPersonIndicator>");
		builder.append("<associationSiteIndicator>Y</associationSiteIndicator>");
		builder.append("<characterScriptCode>?</characterScriptCode>");
		builder.append("<countryCode>?</countryCode>");
		builder.append("<emailsIndicator>N</emailsIndicator>");
		builder.append("<languageCode>?</languageCode>");
		builder.append("<personIdentifier>Y</personIdentifier>");
		builder.append("<personNamesIndicator>N</personNamesIndicator>");
		builder.append("<socialMediaIndicator>N</socialMediaIndicator>");
		builder.append("<telephoneIndicator>N</telephoneIndicator>");
		builder.append("<uniformResourceIndicator>N</uniformResourceIndicator>");
		builder.append("</per:personGet>");
		builder.append("</soapenv:Body>");
		builder.append("</soapenv:Envelope>");
		return builder.toString();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new JerseyCallSoapWSTest().testCallSoapWS();
	}

}

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

call rest 
====================
ClientResponse response = service.path(restfulAction)
                            .header("Cookie","SMSESSION=1234")
                            .header("X-HP-Application-Process-UID", "hpit:w-mdcp-prd")
                            .header("uid", "lihuan.wang@hp.com")
                            .type("application/x-www-form-urlencoded")
                            .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,formData);
System.out.println(response.getEntity(String.class));
====================

依赖的jar
asm-3.1.jar
jersey-client-1.14.jar
jersey-core-1.14.jar
jersey-server-1.14.jar
DataTable 后台分页 javascript, jquery
html
<!DOCTYPE html>
<html>
<head>
<link href="http://datatables.net/download/build/nightly/jquery.dataTables.css"
	rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<style type="text/css">
body {
	font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
	margin: 0;
	padding: 0;
	color: #333;
	background-color: #fff;
}


div.container {
	min-width: 980px;
	margin: 0 auto;
}
</style>
<script type="text/javascript">
$(document).ready( function () {
	var table = $(document).ready(function() {
    $('#example').dataTable( {
        "bPaginate": true,
        "bLengthChange": true,
        "bFilter": true,
        "bSort": true,
        "bInfo": true,
        "sScrollY": "1000",
        "bScrollCollapse": true,
        "bSearchable": false,
        "bAutoWidth": true,
        "bProcessing": true, 
        "sAjaxSource": "page.do",
        "bServerSide":true,
        "fnServerData" : function(sSource, aoData, fnCallback) {
            $.ajax({
             "dataType" : 'json',
             "type" : "GET",
             "url" : sSource,
             "data" : aoData,
             "success" : fnCallback
            });
         },
        //"sPaginationType": "full_numbers",
        "aoColumnDefs": [
          { "bSearchable": false, "aTargets": [ 0 ] }
        ] ,
        "aoColumns" : [ 
		               	{"mData" : "name","sWidth": "100px"},//2
		                {"mData" : "position","sWidth": "100px"},//3
		                {"mData" : "office","sWidth": "150px"},//4
		                {"mData" : "age","sWidth": "150px"},//4
		                {"mData" : "startDate","sWidth": "200px"},//5
		                {"mData" : "salary","sWidth": "150px"}//7
		],
    } );
} );
} );
</script>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
	<div class="container">
		<table id="example" class="display" width="100%">
			<thead>
				<tr>
					<th>Name</th>
					<th>Position</th>
					<th>Office</th>
					<th>Age</th>
					<th>Start date</th>
					<th>Salary</th>
				</tr>
			</thead>
			<tbody></tbody>
		</table>
	</div>
</body>
</html>

Controller:
package com.hp.it.mdm.portal.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("Page")
public class PageController {

	static List<Person> persons = new ArrayList<Person>();
	static{
		initData();
	}
	
	@RequestMapping(value="/page",method = RequestMethod.GET)
	public @ResponseBody
	DataTable test(Model model,@RequestParam int iDisplayStart,
            @RequestParam int iDisplayLength, @RequestParam int sEcho) {
		System.out.println("page...");
		System.out.println("para0---"+iDisplayStart);
		System.out.println("para1---"+iDisplayLength);
		System.out.println("para2---"+sEcho);
		int start = iDisplayStart*iDisplayLength;
		int end = (iDisplayStart+1)*iDisplayLength >= persons.size() ? persons.size() : (iDisplayStart+1)*iDisplayLength;
		List<Person> list = persons.subList(start,end);
		DataTable dataTable = new DataTable();
		dataTable.setsEcho(sEcho+"");
		dataTable.setiTotalRecords(persons.size() + "");
		dataTable.setiTotalDisplayRecords(list.size() + "");
		dataTable.setAaData(list);
		return dataTable;
	}
	
	private static void initData(){
		String[] data = {
				"Elton Baldwin|Data Coordinator|Edinburgh|64|2012/04/09|$6,730",
				"Gavin Joyce|Developer|Edinburgh|42|2010/12/22|$4,525",
				"Jonas Alexander|Developer|San Francisco|30|2010/07/14|$5,300",
				"Suki Burks|Developer|London|53|2009/10/22|$2,875",
				"Thor Walton|Developer|New York|61|2013/08/11|$3,600",
				"Garrett Winters|Director|Edinburgh|63|2011/07/25|$5,300",
				"Hermione Butler|Director|London|47|2011/03/21|$4,080",
				"Jackson Bradshaw|Director|New York|65|2008/09/26|$5,000",
				"Russell Chavez|Director|Edinburgh|20|2011/08/14|$3,300",
				"Hope Fuentes|Financial Controller|San Francisco|41|2010/02/12|$4,200",
				"Howard Hatfield|Financial Controller|San Francisco|51|2008/12/16|$4,080",
				"Jenette Caldwell|Financial Controller|New York|30|2011/09/03|$4,965",
				"Jenna Elliott|Financial Controller|Edinburgh|33|2008/11/28|$5,300",
				"Elton Baldwin|Financial Controller|Edinburgh|22|2013/03/03|$4,200",
				"Quinn Flynn|Financial Controller|London|37|2008/12/11|$4,200",
				"Brielle Williamson|Integration Specialist|New York|61|2012/12/02|$4,525",
				"Martena Mccray|Integration Specialist|Edinburgh|46|2011/03/09|$4,080",
				"Michelle House|Integration Specialist|Edinburgh|37|2011/06/02|$3,750",
				"Rhona Davidson|Integration Specialist|Edinburgh|55|2010/10/14|$6,730",
				"Cedric Kelly|Javascript Developer|Edinburgh|22|2012/03/29|$3,600",
				"Colleen Hurst|Javascript Developer|San Francisco|39|2009/09/15|$5,000",
				"Charde Marshall|Regional Director|San Francisco|36|2008/10/16|$5,300",
				"Shad Decker|Regional Director|San Edinburgh|37|2005/12/16|$7,360",
				"Cara Stevens|Sales Assistant|New York|46|2011/12/06|$4,800",
				"Doris Wilder|Sales Assistant|Edinburgh|23|2010/09/20|$4,965",
				"Haley Kennedy|SeniorMarketing|Designer|London|43|2012/12/18|$4,800",
				"Zenaida Frank|Software Engineer|New York|63|2010/01/04|$4,800",
				"Donna Snider|System Architect|New York|27|2011/01/25|$3,120",
				"Gloria Little|Systems Administrator|New York|59|2009/04/10|$3,120",
				"Lael Greer|Systems Administrator|London|21|2009/02/27|$3,120",
				"Ashton Cox|Technical Author|San Francisco|66|2009/01/12|$4,800",
				"Gavin Cortez|Technical Author|San Francisco|22|2008/10/26|$6,730"
				};
		for(String str : data){
			String[] temp = str.split("\\|");
			Person p = new Person();
			p.setName(temp[0]);
			p.setPosition(temp[1]);
			p.setOffice(temp[2]);
			p.setAge(temp[3]);
			p.setStartDate(temp[4]);
			p.setSalary(temp[5]);
			persons.add(p);
		}
	}
	
	class DataTable {
		private String sEcho;
		private String iTotalRecords;
		private String iTotalDisplayRecords;
		private List<Person> aaData;

		public String getsEcho() {
			return sEcho;
		}

		public void setsEcho(String sEcho) {
			this.sEcho = sEcho;
		}

		public String getiTotalRecords() {
			return iTotalRecords;
		}

		public void setiTotalRecords(String iTotalRecords) {
			this.iTotalRecords = iTotalRecords;
		}

		public String getiTotalDisplayRecords() {
			return iTotalDisplayRecords;
		}

		public void setiTotalDisplayRecords(String iTotalDisplayRecords) {
			this.iTotalDisplayRecords = iTotalDisplayRecords;
		}

		public List<Person> getAaData() {
			return aaData;
		}

		public void setAaData(List<Person> aaData) {
			this.aaData = aaData;
		}
	}
}

class Person {
	private String name;
	private String position;
	private String office;
	private String age;
	private String startDate;
	private String salary;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public String getOffice() {
		return office;
	}

	public void setOffice(String office) {
		this.office = office;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getSalary() {
		return salary;
	}

	public void setSalary(String salary) {
		this.salary = salary;
	}
}
clone javascript
if(typeof Object.create !== 'function'){
  Object.create = function(o){
    var F = function(){};
    F.prototype = o;
    return new F();
  }
}

var another_object = Object.create(object);
动态添加行,删除行 javascript
function addRow(table,index){

	var tdString = '</td><td>';
	var specialTdString = '</td><td class="special">';
	var appendValue = '<tr><td>';
	var $select = table.find("tr").eq(1).find("td").eq(0).html().replace(0,index);

	var $checkbox = '<input type="checkbox" name="salesTerritoryRuleItems[' +index + '].blnExcluded" value="false">';
	appendValue += $select + tdString +
				$checkbox + tdString + 
				'<input type="text" class="autocomplete ui-autocomplete-input" name="salesTerritoryRuleItems[' +index + '].salesTerritoryRuleItemStringValue" autocomplete="off">'
				+ specialTdString +
				'<img src="image/binoculars.png" id="searchIcon" class="searchIcon" height="20px" width="20px" style="display:none"/><input type="text" class="businessAreaGroup  ui-autocomplete-input" name="salesTerritoryRuleItems[' +index + '].businessAreaGroupStringValue" hidden="true" autocomplete="off" style="display: none;">'
				+ tdString
				//+ table.find("tr").eq(1).find("td").last().html()
				+'<span class="image"><img alt="Add" src="image/Addrow.gif" style="display: inline;" class="addRow" id="dd"></span>'
				+'<span class="image"><img alt="Remove" src="image/Deleterow.gif"  class="removeRow"></span>';
	appendValue += '</td></tr>';
	table.append(appendValue);
	$('.removeRow').show();
}

function removeRow($table,$row){
	if($("#table tr").length == 3){
		$table.find('.removeRow').hide();
	}
	$row.remove();
	$table.find('tbody tr:not(:first)').each(function(index){$(this)
		.find('input').each(function(){this.name=this.name.replace(/\d/g,index+1);});});
	$table.find('tbody tr:not(:first)').each(function(index){$(this)
		.find('select').each(function(){this.name=this.name.replace(/\d/g,index+1);});});
	
	//only last row can show the add row icon 
	$table.find('tbody tr:last :has(".addRow")').find("img").first().show();
	// if the first row, then do not show the remove icon 
	

}
从Jar文件读取properties文件 java, properties
package com.hp.io.chapt11;

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.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class Jarer {
	public static int BUFFER_SIZE = 1024;
	
	static void createJarArchive(File archiveFile, File[] tobeJared) throws Exception {
	    byte buffer[] = new byte[BUFFER_SIZE];
	    FileOutputStream stream = new FileOutputStream(archiveFile);
	    JarOutputStream out = new JarOutputStream(stream, new Manifest());
	    for (int i = 0; i < tobeJared.length; i++) {
	      if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory())
	        continue; // Just in case...
	      System.out.println(tobeJared[i].getPath());
	      System.out.println(tobeJared[i].getCanonicalPath());
	      System.out.println(tobeJared[i].getAbsolutePath());
	      JarEntry jarAdd = new JarEntry(tobeJared[i].getPath());
	      jarAdd.setTime(tobeJared[i].lastModified());
	      out.putNextEntry(jarAdd);
	      FileInputStream in = new FileInputStream(tobeJared[i]);
	      while (true) {
	        int nRead = in.read(buffer, 0, buffer.length);
	        if (nRead <= 0)
	          break;
	        out.write(buffer, 0, nRead);
	      }
	      in.close();
	    }
	    out.close();
	    stream.close();
	  }
	
	public static void makeJarFile(){
		File[] files = {new File("src/main/resources/test.properties")};
		try {
			createJarArchive(new File("jar.jar"), files);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void loadJarProperties(){
		InputStream is = null;
		JarInputStream jis = null;
		try {
			JarFile jf = new JarFile("io-M1.jar");
//			Enumeration<JarEntry> entry = jf.entries();
//			while(entry.hasMoreElements()){
//				System.out.println(entry.nextElement().getName());;
//			}
			JarEntry je = jf.getJarEntry("test.properties");
			Properties pro = new Properties();
			pro.load(jf.getInputStream(je));
			System.out.println(pro.getProperty("A"));
			jf.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(is != null){
				is.close();
				}
				if(jis != null){
					jis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		makeJarFile();
		loadJarProperties();
	}

}
Java并发,所有线程都就绪之后在开始执行 java, thread
public class TestHarness {
	public long timeTasks(int nThreads, final Runnable task) throws InterruptedException{
		
		final CountDownLatch startGate = new CountDownLatch(1);
		final CountDownLatch endGate = new CountDownLatch(nThreads);
		for(int i=0;i< nThreads;i++){
			Thread t = new Thread(){
				public void run(){
					try{
						startGate.await();
						try{
							task.run();
						}finally{
							endGate.countDown();
						}
					}catch (InterruptedException ignored) {
					}
				}
			};
			t.start();
		}
		long start = System.nanoTime();
		startGate.countDown();
		endGate.await();
		long end = System.nanoTime();
		return end - start;
	}
}
Oracle PLSQL发邮件 oracle
declare
  smtp_conn       utl_smtp.connection;
  user_name       varchar2(100) := utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw('jian.he3@hp.com')));
  user_paswd      varchar2(100) := utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw('*******')));
  lv_mail_header  varchar2(200) := 'From:jian.he3@hp.com' || utl_tcp.CRLF ||
                                   'To:jian.he3@hp.com' || utl_tcp.CRLF ||
                                   'Subject:This is A Test' || utl_tcp.CRLF;
  lv_mail_content varchar2(200) := utl_tcp.CRLF || 'English Content!!!';
begin
  smtp_conn := utl_smtp.open_connection('smtp.hp.com', 25);
  -- do not need to authencate
  --utl_smtp.helo(smtp_conn, 'smtp.hp.com');
  --utl_smtp.command(smtp_conn, 'AUTH LOGIN');
  --utl_smtp.command(smtp_conn, user_name);
  --utl_smtp.command(smtp_conn, user_paswd);
  utl_smtp.mail(smtp_conn, '<jian.he3@hp.com>');
  utl_smtp.rcpt(smtp_conn, '<jian.he3@hp.com>');
  utl_smtp.open_data(smtp_conn);
  utl_smtp.write_data(smtp_conn, lv_mail_header);
  utl_smtp.write_raw_data(smtp_conn, utl_raw.cast_to_raw(lv_mail_content));
  utl_smtp.close_data(smtp_conn);
  utl_smtp.quit(smtp_conn);
exception
  when others then
    utl_smtp.quit(smtp_conn);
    raise;
end;
Oracle utl_file写入文件 oracle
-- Create directory 
-- Need System Privilege 
create or replace directory WRITE_DIR as 'c:\test';

grant read,write on directory write_dir to scott;

create or replace procedure busy_busy
is
--http://blog.donews.com/gxgx/archive/2005/01/20/248187.aspx
-- MUST USE DIRECTORY
   fileid UTL_FILE.file_type;
   c_file_dir CONSTANT VARCHAR2(250) := 'WRITE_DIR';
   c_file_name CONSTANT VARCHAR2(250) := 'temp.txt';
   procedure clean_up is
   begin
       if UTL_FILE.is_open(fileid) then
          UTL_FILE.fclose(fileid);
       end if;
   end clean_up;
begin
   fileid := UTL_FILE.fopen(c_file_dir,c_file_name,'a');
   UTL_FILE.put(fileid,'simple line without carriage return!!!');
   UTL_FILE.put_line(fileid,'line with carriage return!!!');
   clean_up;
EXCEPTION
   when NO_DATA_FOUND then
      clean_up;
      RAISE;
end;
StopWatch java
package com.hp.thread.chapter08;

import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * A simple timer that measures elapsed time and intervals. Useful for logging code execution times.
 * <p>A stopwatch conceptually maintains two timers, the elapsed timer and the interval timer.
 * Both timers start when the stopwatch is started. The elapsed timer can be queried at any time with
 * {@link #elapsed()} and returns the time since the stopwatch was started. The interval timer can be queried with
 * {@link #interval()}. The interval timer is reset to zero every time it is read.</p>
 *
 * @author   Quintin May
 */
public class StopWatch {
    
    private static final long ONE_SECOND = SECONDS.toMillis(1);
    private static final long ONE_MINUTE = MINUTES.toMillis(1);
    private static final long ONE_HOUR = HOURS.toMillis(1);

    private final long start;
    private long interval;

    private StopWatch() {
        interval = start = System.currentTimeMillis();
    }
    
    /**
     * Creates and starts a stopwatch.
     * @return the stopwatch.
     */
    public static StopWatch start() {
        return new StopWatch();
    }

    /**
     * Formats a number of milliseconds representing a time duration into a human-readable string.
     * @param milliseconds  the milliseconds.
     * @return the formatted string.
     */
    public static String duration(long milliseconds) {
        long used;

        StringBuilder duration = new StringBuilder();

        if (milliseconds >= ONE_HOUR) {
            used = milliseconds / ONE_HOUR;
            milliseconds -= used * ONE_HOUR;
            duration.append(used)
                    .append("h");
        }

        if (milliseconds >= ONE_MINUTE) {
            used = milliseconds / ONE_MINUTE;
            milliseconds -= used * ONE_MINUTE;
            duration.append(used)
                    .append("m");
        }

        used = 0;

        if (milliseconds >= ONE_SECOND) {
            used = milliseconds / ONE_SECOND;
            milliseconds -= used * ONE_SECOND;
        }

        String ms = "00" + String.valueOf(milliseconds);
        ms = ms.substring(ms.length() - 3);
        duration.append(used)
                .append(".")
                .append(ms)
                .append("s");

        return duration.toString();
    }

    /**
     * Returns the number of milliseconds since the stopwatch was {@link #start() started}.
     * @return the number of milliseconds.
     */
    public long elapsed() {
        return System.currentTimeMillis() - start;
    }

    /**
     * Returns the number of milliseconds since {@link #start()} or the previous call to {@link #interval()}.
     * The interval timer is reset to zero when this method is invoked. The "lap" time.
     * @return the number of milliseconds.
     */
    public long interval() {
        long now = System.currentTimeMillis();
        long elapsed = now - interval;
        interval = now;

        return elapsed;
    }

    /**
     * Returns the elapsed time in a formatted string.
     * @return the elapsed time in a formatted string.
     */
    @Override
    public String toString() {
        return duration(elapsed());
    }
}
反射生成toString() java
/**
 * Copyright 2010 Hewlett-Packard. All rights reserved. <br>
 * HP Confidential. Use is subject to license terms.
 */
/**
 * Copyright 2010 Hewlett-Packard. All rights reserved. <br>
 * HP Confidential. Use is subject to license terms.
 */
package com.hp.it.cmu.ep.client;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

import com.hp.it.cmu.ep.client.dataOwnerGroup.UpdateDataOwnerGroupTrigger;

/**
 *
 * Dynamicly generate toString() through refelection approach
 *
 * @author jian.he3@hp.com
 *
 */
public class ToStringUtil {

	/**
	 * 
	 * @param obj that you want to generate 
	 * @return 
	 */
	public static String tostring(Object obj){
		StringBuffer buffer = new StringBuffer();
		buffer.append(obj.getClass().getSimpleName() + " [");
		Class<?> clazz = obj.getClass();
		
		Field[] fields = clazz.getDeclaredFields();
		int idx = 0;
		for(Field field : fields){
			String fieldName = field.getName();
			buffer.append(fieldName + "=" + getFieldValue(fieldName, clazz, obj));
			if(++idx < fields.length){
				buffer.append(", ");
			}
		}
		buffer.append("]");
		return buffer.toString();
	}
	
	private static Object getFieldValue(String fieldName,Class<?> clazz,Object obj){
		try {
			PropertyDescriptor descriptor = new PropertyDescriptor(fieldName, clazz);
			Method method = descriptor.getReadMethod();
			Object object = method.invoke(obj);
			return object;
		} catch (IntrospectionException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	@Test
	public static void main(String[] args) {
		UpdateDataOwnerGroupTrigger trigger = new UpdateDataOwnerGroupTrigger();
		trigger.setDataOwnerGroupId(222L);
		trigger.setDataOwnerGroupName("SOUTH AMERICAN");
		trigger.setDataOwnerGroupDescription("dataOwnerGroupDescription");
		System.out.println(tostring(trigger));
	}
	
}
Encrypting a String with DES java, encrypt http://docs.oracle.com/javase/1.4.2/docs/guide/security/jce/JCERefGuide.html#Examples
package cn.com.rits.easyscan.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class EncryptUtil {
	private static SecretKey key;
	private static Cipher cipher;
	private static final String KEY = "AES";
	static{
		try {
			KeyGenerator keygen = KeyGenerator.getInstance(KEY);
			SecureRandom random = new SecureRandom();
			keygen.init(random);
			key = keygen.generateKey();
			cipher = Cipher.getInstance(KEY);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}
	
	public static byte[] encrypt(String plaintext){
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] cleartext = plaintext.getBytes("utf-8");
			byte[] ciphertext = cipher.doFinal(cleartext);
			return ciphertext;
			
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String decrypt(byte[] text){
		try {
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] ciphertext = text;
			byte[] cleartext = cipher.doFinal(ciphertext);
			return new String(cleartext,"utf-8");
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	//这个方法是正确的
	public static void crypt(){
		try {
			KeyGenerator keygen = KeyGenerator.getInstance(KEY);
			SecretKey desKey = keygen.generateKey();
			Cipher cipher = Cipher.getInstance(KEY);
			cipher.init(Cipher.ENCRYPT_MODE, desKey);
			byte[] cleartext = "this is just an example".getBytes();
			byte[] ciphertext = cipher.doFinal(cleartext);
			System.out.println(new String(ciphertext,"utf-8"));
			cipher.init(Cipher.DECRYPT_MODE, desKey);
			byte[] cleartext1 = cipher.doFinal(ciphertext);
			System.out.println(new String(cleartext1,"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		System.out.println(decrypt(encrypt("12345678")));
//		crypt();
		byte[] ciphertext = encrypt("123456");
		System.out.println(ciphertext);
		System.out.println(String.valueOf(ciphertext));
		String cleartext = decrypt(ciphertext);
		System.out.println(cleartext);
	}
}



======================================================================================
package cn.com.rits.easyscan.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class EncryptUtil2 {
	private static SecretKey key;
	private static Cipher cipher;
	private static KeySpec dks;
	private static final String SECRET = "tojaoomy";
	private static final String KEY = "DES";
	private static final int COUNT = 19;
	 // 8-byte Salt
    private static byte[] salt = {
        (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
        (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
    };

	static{
		try {
			dks = new PBEKeySpec(SECRET.toCharArray(), salt, COUNT);

//			keygen.init(random);
//			key = keygen.generateKey();
			key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(dks);
			cipher = Cipher.getInstance(key.getAlgorithm());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
	}
	
	public static byte[] encrypt(String plaintext){
		try {
			AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, COUNT);
			cipher.init(Cipher.ENCRYPT_MODE,key,paramSpec);
			byte[] cleartext = plaintext.getBytes("utf-8");
			byte[] ciphertext = cipher.doFinal(cleartext);
			return ciphertext;
			
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String decrypt(byte[] text){
		try {
			AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, COUNT);
			cipher.init(Cipher.DECRYPT_MODE,key,paramSpec);
			byte[] ciphertext = text;
			byte[] cleartext = cipher.doFinal(ciphertext);
			return new String(cleartext,"utf-8");
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	//这个方法是正确的
	public static void crypt(){
		try {
			KeyGenerator keygen = KeyGenerator.getInstance(KEY);
			SecretKey desKey = keygen.generateKey();
			Cipher cipher = Cipher.getInstance(KEY);
			cipher.init(Cipher.ENCRYPT_MODE, desKey);
			byte[] cleartext = "this is just an example".getBytes();
			byte[] ciphertext = cipher.doFinal(cleartext);
			System.out.println(new String(ciphertext,"utf-8"));
			cipher.init(Cipher.DECRYPT_MODE, desKey);
			byte[] cleartext1 = cipher.doFinal(ciphertext);
			System.out.println(new String(cleartext1,"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		System.out.println(decrypt(encrypt("12345678")));
//		crypt();
		byte[] ciphertext = encrypt("123456");
		System.out.println(ciphertext);
		System.out.println(String.valueOf(ciphertext));
		String cleartext = decrypt(ciphertext);
		System.out.println(cleartext);
	}
}
=====================================================================================
package cn.com.rits.easyscan.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;   
import java.security.InvalidKeyException;   
import java.security.NoSuchAlgorithmException;   
import java.security.SecureRandom;   
  
import javax.crypto.BadPaddingException;   
import javax.crypto.Cipher;   
import javax.crypto.IllegalBlockSizeException;   
import javax.crypto.KeyGenerator;   
import javax.crypto.NoSuchPaddingException;   
import javax.crypto.SecretKey;   

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
  
public class EncryptUtil4 {   
    private static SecretKey key;   
    private static Cipher cipher;   
    private static final String KEY = "AES";   
    private static final String FILE = "secret.cer";
    static{   
        try {   
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE)); 
            try {
				Object obj = ois.readObject();
				key = (SecretKey)obj;   
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
            cipher = Cipher.getInstance(KEY);   
        } catch (NoSuchAlgorithmException e) {   
            e.printStackTrace();   
        } catch (NoSuchPaddingException e) {   
            e.printStackTrace();   
        } catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}   
    }   
       
    public static void store(){
    	KeyGenerator keygen;
		try {
			keygen = KeyGenerator.getInstance(KEY);
			SecureRandom random = new SecureRandom();   
			keygen.init(random);   
			SecretKey key = keygen.generateKey();  
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE));
			oos.writeObject(key);
			oos.close();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}   
    }
    
           
    
    public static String encrypt(String plaintext){   
        try {   
            cipher.init(Cipher.ENCRYPT_MODE, key);   
            byte[] cleartext = plaintext.getBytes("utf-8");   
            byte[] ciphertext = cipher.doFinal(cleartext);   
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(ciphertext);
//            return ciphertext;   
               
        } catch (InvalidKeyException e) {   
            e.printStackTrace();   
        } catch (IllegalBlockSizeException e) {   
            e.printStackTrace();   
        } catch (BadPaddingException e) {   
            e.printStackTrace();   
        } catch (UnsupportedEncodingException e) {   
            e.printStackTrace();   
        }   
        return null;   
    }   
       
    public static String decrypt(byte[] text){   
        try {   
            cipher.init(Cipher.DECRYPT_MODE, key);   
            byte[] ciphertext = text;   
            byte[] cleartext = cipher.doFinal(ciphertext);   
            return new String(cleartext,"utf-8");   
        } catch (InvalidKeyException e) {   
            e.printStackTrace();   
        } catch (IllegalBlockSizeException e) {   
            e.printStackTrace();   
        } catch (BadPaddingException e) {   
            e.printStackTrace();   
        } catch (UnsupportedEncodingException e) {   
            e.printStackTrace();   
        }   
        return "";   
    }   
    
    public static String decrypt(String text){   
        try {   
            cipher.init(Cipher.DECRYPT_MODE, key);   
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] ciphertext = decoder.decodeBuffer(text);   
            byte[] cleartext = cipher.doFinal(ciphertext);   
            return new String(cleartext,"utf-8");   
        } catch (InvalidKeyException e) {   
            e.printStackTrace();   
        } catch (IllegalBlockSizeException e) {   
            e.printStackTrace();   
        } catch (BadPaddingException e) {   
            e.printStackTrace();   
        } catch (UnsupportedEncodingException e) {   
            e.printStackTrace();   
        } catch (IOException e) {
			e.printStackTrace();
		}   
        return "";   
    }   
       
    //这个方法是正确的   
    public static void crypt(){   
        try {   
            KeyGenerator keygen = KeyGenerator.getInstance(KEY);   
            SecretKey desKey = keygen.generateKey();   
            Cipher cipher = Cipher.getInstance(KEY);   
            cipher.init(Cipher.ENCRYPT_MODE, desKey);   
            byte[] cleartext = "this is just an example".getBytes();   
            byte[] ciphertext = cipher.doFinal(cleartext);   
            System.out.println(new String(ciphertext,"utf-8"));   
            cipher.init(Cipher.DECRYPT_MODE, desKey);   
            byte[] cleartext1 = cipher.doFinal(ciphertext);   
            System.out.println(new String(cleartext1,"utf-8"));   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
       
    public static void main(String[] args) {   
//      System.out.println(decrypt(encrypt("12345678")));   
//      crypt();   
//    	store();
        String cleartext = decrypt("IIkID8Urw0QWSVSexk9UxA==");   
        System.out.println(cleartext);   
    }   
}   
======================================================================================
完全版
package cn.com.rits.easyscan.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptUtil {
	private static SecretKey key;
	private static Cipher cipher;
	private static SecureRandom random;
	private static KeySpec dks;
	private static final String SECRET = "12345678";
	private static final String KEY = "DES";

	static{
		try {
			random = new SecureRandom();
			dks = new DESKeySpec(SECRET.getBytes("utf-8"));
//			keygen.init(random);
//			key = keygen.generateKey();
			key = SecretKeyFactory.getInstance(KEY).generateSecret(dks);
			cipher = Cipher.getInstance(KEY);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public static String encrypt(String plaintext){   
        try {   
            cipher.init(Cipher.ENCRYPT_MODE, key);   
            byte[] cleartext = plaintext.getBytes("utf-8");   
            byte[] ciphertext = cipher.doFinal(cleartext);   
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(ciphertext);
//            return ciphertext;   
               
        } catch (InvalidKeyException e) {   
            e.printStackTrace();   
        } catch (IllegalBlockSizeException e) {   
            e.printStackTrace();   
        } catch (BadPaddingException e) {   
            e.printStackTrace();   
        } catch (UnsupportedEncodingException e) {   
            e.printStackTrace();   
        }   
        return null;   
    }   
	
	/*public static byte[] encrypt(String plaintext){
		try {
			cipher.init(Cipher.ENCRYPT_MODE,key,random);
			byte[] cleartext = plaintext.getBytes("utf-8");
			byte[] ciphertext = cipher.doFinal(cleartext);
			return ciphertext;
			
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}*/
	
	public static String decrypt(byte[] text){
		try {
			cipher.init(Cipher.DECRYPT_MODE,key,random);
			byte[] ciphertext = text;
			byte[] cleartext = cipher.doFinal(ciphertext);
			return new String(cleartext,"utf-8");
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String decrypt(String text){   
        try {   
            cipher.init(Cipher.DECRYPT_MODE, key);   
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] ciphertext = decoder.decodeBuffer(text);   
            byte[] cleartext = cipher.doFinal(ciphertext);   
            return new String(cleartext,"utf-8");   
        } catch (InvalidKeyException e) {   
            e.printStackTrace();   
        } catch (IllegalBlockSizeException e) {   
            e.printStackTrace();   
        } catch (BadPaddingException e) {   
            e.printStackTrace();   
        } catch (UnsupportedEncodingException e) {   
            e.printStackTrace();   
        } catch (IOException e) {
			e.printStackTrace();
		}   
        return "";   
    }   
	
	//这个方法是正确的
	public static void crypt(){
		try {
			KeyGenerator keygen = KeyGenerator.getInstance(KEY);
			SecretKey desKey = keygen.generateKey();
			Cipher cipher = Cipher.getInstance(KEY);
			cipher.init(Cipher.ENCRYPT_MODE, desKey);
			byte[] cleartext = "this is just an example".getBytes();
			byte[] ciphertext = cipher.doFinal(cleartext);
			System.out.println(new String(ciphertext,"utf-8"));
			cipher.init(Cipher.DECRYPT_MODE, desKey);
			byte[] cleartext1 = cipher.doFinal(ciphertext);
			System.out.println(new String(cleartext1,"utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		crypt();
		String ciphertext = encrypt("123456");
		System.out.println(ciphertext);
		String cleartext = decrypt(ciphertext);
		System.out.println(cleartext);
	}
}
JDK Logger log, java http://www.vogella.com/articles/Logging/article.html
package cn.com.rits.easyscan.log;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class EasyScanLog {
	private static Map factory = new HashMap();
	private static FileHandler fh = null;
	
	static{
		try {
			fh = new FileHandler(System.getProperty("user.dir") + "/log.log",
					1025, 1, true);
			fh.setEncoding("UTF-8");
			fh.setFormatter(new SimpleFormatter());
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static void factory(String name) {
		Logger log = Logger.getLogger(name);
		factory.put(name, log);
		log.addHandler(fh);
	}
	
	public synchronized static Logger getInstance(String name){
		Logger logger = (Logger) factory.get(name);
		if(logger == null){
			factory(name);
		}
		return logger;
	}
	
	public static void close(){
		if(fh != null){
			fh.close();
		}
	}
	
	
}
KXML2完全解析xml xml
package cn.com.rits.easyscan.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jcifs.smb.NtlmPasswordAuthentication;

import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import cn.com.rits.easyscan.bean.AdminBasicSettingBean;
import cn.com.rits.easyscan.bean.DepartmentBean;
import cn.com.rits.easyscan.bean.DeptBasicSettingBean;
import cn.com.rits.easyscan.bean.DeptCommonSettingBean;
import cn.com.rits.easyscan.bean.DeptEmailSettingBean;
import cn.com.rits.easyscan.bean.DeptFileNameSettingBean;
import cn.com.rits.easyscan.bean.DeptScanStyleSettingBean;
import cn.com.rits.easyscan.bean.DeptServerSettingBean;
import cn.com.rits.easyscan.smb.ShareFolder;

public class XMLUtil {
//	public static final String FILE = "./xml/conf.xml";
//	public String file = "xml.xml";
	public String file = "conf.xml";
	public String installPath ;
	
	
	/**
	 * 
	 * @param installPath Xlet的安装路径
	 */
	public XMLUtil(String installPath) {
//		System.out.println("-----------------");
		this.installPath = installPath;
//		System.out.println("----------------- file : " + file);
	}
	
	public Document parse(){
		return parse(installPath + file);
	}
	
	//
	public Document parse(String url){
		InputStream is = null;
		Document doc = null;
		try {
			is = new FileInputStream(url);
			KXmlParser parse = new KXmlParser();
			//parse by encoding UTF-8
			parse.setInput(is, "UTF-8");
			//parse contains namespaces
			parse.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
			doc = new Document();
			doc.parse(parse);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return doc;
	}
	
	/**
	 * 
	 * @return 返回管理员的基本设定
	 */
	public AdminBasicSettingBean getAdminBasicSettingBean(){
		AdminBasicSettingBean adminBasicSettingBean = new AdminBasicSettingBean();
		Document document = parse();
		Element root = document.getRootElement();
		Element element = getElement(root, "administratorSetting");
		element = getElement(element, "basicSetting");
		Element elementPassword = getElement(element, "password");
		Element elementEmailInform = getElement(element, "emailInform");
		String password = elementPassword.getText(0).trim();
		boolean emailInform = Boolean.valueOf(elementEmailInform.getText(0).trim());
//		System.out.println("password : " + password);
//		System.out.println("emailInform : " + emailInform);
		adminBasicSettingBean.setPassword(password);
		adminBasicSettingBean.setEmailInform(emailInform);
		return adminBasicSettingBean;
	}
	
	public Map<String,DepartmentBean> getDepts(){
		Map<String,DepartmentBean> depts = new HashMap<String,DepartmentBean>();
		Element parent = getElement("configuration/administratorSetting/departmentSetting");
		Element[] elements = getElementsByName(parent, "dept");
//		System.out.println("length : " + elements.length);
		for(Element e : elements){
			Element basicSetting = getElement(e, "basicSetting");
			DepartmentBean departmentBean = new DepartmentBean();
			DeptBasicSettingBean deptBasicSettingBean = new DeptBasicSettingBean();
			DeptCommonSettingBean deptCommonSettingBean = getDeptCommonSettingBean(basicSetting);
			deptBasicSettingBean.setDeptCommonSettingBean(deptCommonSettingBean);
			DeptServerSettingBean deptServerSettingBean = getDeptServerSettingBean(basicSetting);
			deptBasicSettingBean.setDeptServerSettingBean(deptServerSettingBean);
			DeptEmailSettingBean deptEmailSettingBean = getDeptEmailSettingBean(basicSetting);
			deptBasicSettingBean.setDeptEmailSettingBean(deptEmailSettingBean);
//			System.out.println(deptCommonSettingBean);
//			System.out.println(deptServerSettingBean);
//			System.out.println(deptEmailSettingBean);
			Element fileNameSetting = getElement(e, "fileNameSetting");
			DeptFileNameSettingBean deptFileNameSettingBean = getDeptFileNameSettingBean(fileNameSetting);
			Element styleSetting = getElement(e, "styleSetting");
			List<DeptScanStyleSettingBean> deptScanStyleSettingBeans = getDeptScanStypleSettingBean(styleSetting);
			departmentBean.setDeptBasicSettingBean(deptBasicSettingBean);
			departmentBean.setDeptFileNameSettingBean(deptFileNameSettingBean);
			departmentBean.setDeptScanStyleSettingBeans(deptScanStyleSettingBeans);
			depts.put(deptCommonSettingBean.getName(), departmentBean);
		}
		return depts;
	}
	
	/**
	 * 
	 * @param basicSetting 部门设定->部门基本设定
	 * @return DeptCommonSettingBean
	 */
	private DeptCommonSettingBean getDeptCommonSettingBean(Element basicSetting){
		DeptCommonSettingBean deptCommonSettingBean = new DeptCommonSettingBean();
		Element commonSetting = getElement(basicSetting, "commonSetting");
		String name = getElement(commonSetting, "name").getText(0).trim();
		String password = getElement(commonSetting, "password").getText(0).trim();
		deptCommonSettingBean.setName(name);
		deptCommonSettingBean.setPassword(password);
		return deptCommonSettingBean;
	}
	
	/**
	 * 
	 * @param serverSetting 部门设定 -> 服务器设定
	 * @return DeptServerSettingBean
	 */
	private DeptServerSettingBean getDeptServerSettingBean(Element basicSetting){
		DeptServerSettingBean deptServerSettingBean = new DeptServerSettingBean();
		Element serverSetting = getElement(basicSetting, "serverSetting");
		String serverIP = getElement(serverSetting, "serverIP").getText(0).trim();
		String rootDir = getElement(serverSetting, "rootDir").getText(0).trim();
		String domain = getElement(serverSetting, "domain").getText(0).trim();
		String username = getElement(serverSetting, "username").getText(0).trim();
		String password = getElement(serverSetting, "password").getText(0).trim();
		int displayLay = Integer.parseInt(getElement(serverSetting, "displayLay").getText(0).trim());
		String title1 = getElement(serverSetting, "title1").getText(0).trim();
		String title2 = getElement(serverSetting, "title2").getText(0).trim();
		String title3 = getElement(serverSetting, "title3").getText(0).trim();
		ShareFolder shareFolder = new ShareFolder();
		NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, username, password);
		shareFolder.setAuth(auth);
		shareFolder.setIp(serverIP);
		shareFolder.setRootDir(rootDir);
		deptServerSettingBean.setShareFolder(shareFolder);
		deptServerSettingBean.setDisplayLay(displayLay);
		deptServerSettingBean.setFirstLevelTitle(title1);
		deptServerSettingBean.setSecondLevelTitle(title2);
		deptServerSettingBean.setThirdLevelTitle(title3);
		return deptServerSettingBean;
	}
	
	/**
	 * 
	 * @param basicSetting
	 * @return
	 */
	private DeptEmailSettingBean getDeptEmailSettingBean(Element basicSetting) {
		DeptEmailSettingBean deptDeptEmailSettingBean = new DeptEmailSettingBean();
		Element emailSetting = getElement(basicSetting, "emailSetting");
		boolean inform = Boolean.valueOf(getElement(emailSetting, "inform").getText(0).trim());
		boolean customiseEmail = Boolean.valueOf(getElement(emailSetting, "customiseEmail").getText(0).trim());
		String defaultEmail = getElement(emailSetting, "defaultEmail").getText(0).trim();
		deptDeptEmailSettingBean.setInform(inform);
		deptDeptEmailSettingBean.setCustomizeEmail(customiseEmail);
		deptDeptEmailSettingBean.setDefaultEmailAddress(defaultEmail);
		return deptDeptEmailSettingBean;
	}
	
	/**
	 * 
	 * @param fileNameSetting
	 * @return 返回命名规则JavaBean
	 */
	private DeptFileNameSettingBean getDeptFileNameSettingBean(Element fileNameSetting){
		DeptFileNameSettingBean deptFileNameSettingBean = new DeptFileNameSettingBean();
		int type = Integer.parseInt(fileNameSetting.getText(0).trim());
		deptFileNameSettingBean.setType(type);
		return deptFileNameSettingBean;
	}
	
	private List<DeptScanStyleSettingBean> getDeptScanStypleSettingBean(Element styleSetting){
		List<DeptScanStyleSettingBean> deptScanStyleSettingBeans = new ArrayList<DeptScanStyleSettingBean>();
		Element[] elements = getElementsByName(styleSetting, "style");
		for(Element e : elements){
			DeptScanStyleSettingBean deptScanStyleSettingBean = new DeptScanStyleSettingBean();
			String name = getElement(e, "name").getText(0).trim();
			int orientation = Integer.parseInt(getElement(e, "orientation").getText(0).trim());
			String paperSize = getElement(e, "paperSize").getText(0).trim();
			int resolution = Integer.parseInt(getElement(e, "resolution").getText(0).trim());
			String color = getElement(e, "color").getText(0).trim();
			int density = Integer.parseInt(getElement(e, "density").getText(0).trim());
			String format = getElement(e, "format").getText(0).trim();
			boolean batch = Boolean.valueOf(getElement(e, "batch").getText(0).trim());
			String duplex = getElement(e, "duplex").getText(0).trim();
			deptScanStyleSettingBean.setName(name);
			deptScanStyleSettingBean.setOrientation(orientation);
			deptScanStyleSettingBean.setPaperSize(paperSize);
			deptScanStyleSettingBean.setResolution(resolution);
			deptScanStyleSettingBean.setColor(color);
			deptScanStyleSettingBean.setDensity(density);
			deptScanStyleSettingBean.setFormat(format);
			deptScanStyleSettingBean.setBatch(batch);
			deptScanStyleSettingBean.setDuplex(duplex);
			deptScanStyleSettingBeans.add(deptScanStyleSettingBean);
		}
//		System.out.println("deptScanStyleSettingBeans size : " + deptScanStyleSettingBeans.size());
		return deptScanStyleSettingBeans;
	}
	
	@SuppressWarnings("all")
	private static Element[] getElementsByName(Element parent, String name) {
		if (parent == null || name == null) {
			return null;
		}

		ArrayList elements = new ArrayList();
		int childCount = parent.getChildCount();
		for (int i = 0; i < childCount; i++) {
			Element tmpElement = getElementByIndexAndName(parent, name, i);
			if (tmpElement != null) {
				elements.add(tmpElement);
//				System.out.println("add : " + tmpElement.getName());
			}
		}

		if (elements.isEmpty()) {
			return null;
		}
		return (Element[]) elements.toArray(new Element[0]);
	}
	
	/**
	 * Get the child element by the element's index and name.
	 * @param parent the parentElm
	 * @param name the tag name
	 * @param index the tag index
	 * @return element
	 */
	private static Element getElementByIndexAndName(Element parent, String name, int index) {
		if (parent == null || name == null) {
			return null;
		}

		try {
			Element tmpElement = parent.getElement(index);
//			System.out.println(tmpElement.getName());
			// if the node at the given index is a text node, null is returned.
			if (!tmpElement.getName().equals(name)) {
				return null;
			} else {
				return tmpElement;
			}
		} catch (NullPointerException e) {
			// if the node at the given index is a text node, null is returned.
//			e.printStackTrace();
			return null;
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 
	 * @param regex 类似Windows的绝对路径表达式   root/child/child
	 * @return 对应的节点
	 */
	public Element getElement(String regex){
		Element root = parse().getRootElement();
//		String[] re = regex.split("/");
//		if(re.length == 1){
//			return element;
//		}else{
//			for(int i = 1; i < re.length;i++){
//				element = getElement(element, re[i]);
//			}
//		}
		//原始的regex => root/child/child
		regex = regex.substring(regex.indexOf("/")+1);
		//现在regex=>child/child/
		//因为root代表根路径
		return getElementFromElement(root, regex);
		 
	}
	
	/**
	 * 
	 * @param element   已知的节点    root
	 * @param regex		已知节点下的路径 	child/child
	 * @return
	 */
	public Element getElementFromElement(Element element,String regex){
		String[] re = regex.split("/");
		for(int i = 0; i < re.length;i++){
			element = getElement(element, re[i]);
		}
		return element;
	}
	
	/**
	 * 
	 * @param element  节点的父节点
	 * @param name	子节点的名称
	 * @return
	 */
	public Element getElement(Element element,String name){
		return element.getElement("",name);
	}
	
	public static void testConf(){
//		System.out.println(new XMLUtil("./xml/").parse().getRootElement().getName());
		XMLUtil util = new XMLUtil("./xml/"); 
		util.getAdminBasicSettingBean();
//		util.getDepts();
		System.out.println(util.getDepts());
//		String str = "abcss";
//		String[] s = str.split("/");
//		System.out.println(s.length);
//		System.out.println(util.getElement("configuration/administratorSetting/departmentSetting/dept/basicSetting/commonSetting/name").getText(0).trim());
//		System.out.println(util.getElementFromElement(util.parse().getRootElement(),"administratorSetting/departmentSetting/dept/basicSetting/commonSetting/name").getText(0).trim());
	}
	
	public static void testXml(){
		XMLUtil util = new XMLUtil("./xml/"); 
		util.file = "xml.xml";
		Element root = util.parse().getRootElement();
		System.out.println(root.getChildCount());
		Element ele = (Element) root.getChild(5);
		System.out.println(ele.getText(0));
	}
	public static void main(String[] args) {
//		testXml();
		testConf();
	}
}
===========================================================================================
XML配置文件式样
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
	<!-- 管理员设定 -->
	<administratorSetting>
		<!-- 基本设定 -->
		<basicSetting>
			<!-- 管理员密码 加密DES -->
			<password encryptType="DES">123456</password>
			<!-- 邮件通知默认关闭 -->
			<emailInform>false</emailInform>
		</basicSetting>
		<!-- 部门设定 -->
		<departmentSetting>
			<dept>
				<!-- 部门基本设定 -->
				<basicSetting>
					<!-- 共通设定 -->
					<commonSetting>
						<!-- 部门名称 -->
						<name>
							管理部
						</name>
						<!--部门密码 需加密-->
						<password encryptType="DES">
							rst123456
						</password>
					</commonSetting>
					<!-- 服务器设定 -->
					<serverSetting>
						<!-- 服务器IP地址 -->
						<serverIP>172.25.73.15</serverIP>
						<!-- 根目录 -->
						<rootDir>share</rootDir>
						<!-- 域 -->
						<domain>domrst</domain>
						<username>username</username>
						<password encryptType="DES">hejian</password>
						<!-- 显示目录层数 -->
						<displayLay>3</displayLay>
						<!-- 第一级目录名称 -->
						<title1>类型</title1>
						<!-- 第二级目录名称 -->
						<title2>名称</title2>
						<!-- 第三级目录名称 -->
						<title3>管理人</title3>
					</serverSetting>
					<!-- 邮件通知设定 -->
					<emailSetting>
						<!-- true 通知开启  false 通知关闭-->
						<inform>false</inform>
						<!-- 用户是否手动录入Email地址  true 用户手动录入 false 采用默认的邮件地址-->
						<customiseEmail>false</customiseEmail>
						<!-- 默认邮件地址 对用户不可见 -->
						<defaultEmail>admin@rst.ricoh.com</defaultEmail>
					</emailSetting>
				</basicSetting>
				<!-- 文件名设定 -->
				<!--
					文件名  日期时间  文件名
					1	文件名夹
					2	文件名夹_日期时间
					3	文件名夹_日期时间_文件名
					4	日期时间
					5	日期时间_文件名
					6	文件名
					 -->
				<fileNameSetting>
					1
				</fileNameSetting>
				<!-- 扫描样式设定 -->
				<styleSetting>
					<style>
						<!-- 样式名称 -->
						<name>身份证</name>
						<!-- 原稿方向
						1	上
						2	左
						 -->
						<orientation>1</orientation>
						<!-- 纸张大小	A3,A4,B4,B5 -->
						<paperSize>A4</paperSize>
						<!-- 分辨率	200,300,400,600 -->
						<resolution>300</resolution>
						<!-- 色彩 -->
						<color></color>
						<!-- 浓度	  1-7 -->
						<density>4</density>
						<!-- 文件格式 	tiff多页	pdf多页-->
						<format>tiff</format>
						<!-- 批量扫描 	true是	false否 -->
						<batch>false</batch>
						<!-- 单双面	single单面	duplex双面-->
						<duplex>single</duplex>
					</style>
					<style>
						<!-- 样式名称 -->
						<name>文书</name>
						<!-- 原稿方向
						1	上
						2	左
						 -->
						<orientation>1</orientation>
						<!-- 纸张大小	A3,A4,B4,B5 -->
						<paperSize>A4</paperSize>
						<!-- 分辨率	200,300,400,600 -->
						<resolution>300</resolution>
						<!-- 色彩 -->
						<color></color>
						<!-- 浓度	  1-7 -->
						<density>4</density>
						<!-- 文件格式 	tiff多页	pdf多页-->
						<format>tiff</format>
						<!-- 批量扫描 	true是	false否 -->
						<batch>false</batch>
						<!-- 单双面	single单面	duplex双面-->
						<duplex>single</duplex>
					</style>
				</styleSetting>
			</dept>
			<dept>
				<!-- 部门基本设定 -->
				<basicSetting>
					<!-- 共通设定 -->
					<commonSetting>
						<!-- 部门名称 -->
						<name>
							财务部
						</name>
						<!--部门密码 需加密-->
						<password encryptType="DES">
							rst123456
						</password>
					</commonSetting>
					<!-- 服务器设定 -->
					<serverSetting>
						<!-- 服务器IP地址 -->
						<serverIP>172.25.73.15</serverIP>
						<!-- 根目录 -->
						<rootDir>share</rootDir>
						<!-- 域 -->
						<domain>domrst</domain>
						<username>username</username>
						<password encryptType="DES">hejian</password>
						<!-- 显示目录层数 -->
						<displayLay>3</displayLay>
						<!-- 第一级目录名称 -->
						<title1>类型</title1>
						<!-- 第二级目录名称 -->
						<title2>名称</title2>
						<!-- 第三级目录名称 -->
						<title3>管理人</title3>
					</serverSetting>
					<!-- 邮件通知设定 -->
					<emailSetting>
						<!-- true 通知开启  false 通知关闭-->
						<inform>false</inform>
						<!-- 用户是否手动录入Email地址  true 用户手动录入 false 采用默认的邮件地址-->
						<customiseEmail>false</customiseEmail>
						<!-- 默认邮件地址 对用户不可见 -->
						<defaultEmail>admin@rst.ricoh.com</defaultEmail>
					</emailSetting>
				</basicSetting>
				<!-- 文件名设定 -->
				<!--
					文件名  日期时间  文件名
					1	文件名夹
					2	文件名夹_日期时间
					3	文件名夹_日期时间_文件名
					4	日期时间
					5	日期时间_文件名
					6	文件名
					 -->
				<fileNameSetting>
					1
				</fileNameSetting>
				<!-- 扫描样式设定 -->
				<styleSetting>
					<style>
						<!-- 样式名称 -->
						<name>身份证</name>
						<!-- 原稿方向
						1	上
						2	左
						 -->
						<orientation>1</orientation>
						<!-- 纸张大小	A3,A4,B4,B5 -->
						<paperSize>A4</paperSize>
						<!-- 分辨率	200,300,400,600 -->
						<resolution>300</resolution>
						<!-- 色彩 -->
						<color></color>
						<!-- 浓度	  1-7 -->
						<density>4</density>
						<!-- 文件格式 	tiff多页	pdf多页-->
						<format>tiff</format>
						<!-- 批量扫描 	true是	false否 -->
						<batch>false</batch>
						<!-- 单双面	single单面	duplex双面-->
						<duplex>single</duplex>
					</style>
					<style>
						<!-- 样式名称 -->
						<name>文书</name>
						<!-- 原稿方向
						1	上
						2	左
						 -->
						<orientation>1</orientation>
						<!-- 纸张大小	A3,A4,B4,B5 -->
						<paperSize>A4</paperSize>
						<!-- 分辨率	200,300,400,600 -->
						<resolution>300</resolution>
						<!-- 色彩 -->
						<color></color>
						<!-- 浓度	  1-7 -->
						<density>4</density>
						<!-- 文件格式 	tiff多页	pdf多页-->
						<format>tiff</format>
						<!-- 批量扫描 	true是	false否 -->
						<batch>false</batch>
						<!-- 单双面	single单面	duplex双面-->
						<duplex>single</duplex>
					</style>
				</styleSetting>
			</dept>
		</departmentSetting>
	</administratorSetting>
</configuration>
log4j.xml配置 xml, java, log4j http://readwall.blog.163.com/blog/static/1012713220121215563578/
<?xml version="1.0" encoding="UTF-8"?>     
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">     
        
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/' >     
        
    <appender name="myConsole" class="org.apache.log4j.ConsoleAppender">     
        <layout class="org.apache.log4j.PatternLayout">     
            <param name="ConversionPattern"        
                value="[%d{dd HH:mm:ss,SSS\} %-5p] [%t] %c{2\} - %m%n" />     
        </layout>     
        <!--过滤器设置输出的级别-->     
        <filter class="org.apache.log4j.varia.LevelRangeFilter">     
            <param name="levelMin" value="debug" />     
            <param name="levelMax" value="warn" />     
            <param name="AcceptOnMatch" value="true" />     
        </filter>     
    </appender>     
     
    <appender name="myFile" class="org.apache.log4j.RollingFileAppender">        
        <param name="File" value="D:/output.log" /><!-- 设置日志输出文件名 -->     
        <!-- 设置是否在重新启动服务时,在原有日志的基础添加新日志 -->     
        <param name="Append" value="true" />     
        <param name="MaxBackupIndex" value="10" />     
        <layout class="org.apache.log4j.PatternLayout">     
            <param name="ConversionPattern" value="%p (%c:%L)- %m%n" />     
        </layout>     
    </appender>     
       
    <appender name="activexAppender" class="org.apache.log4j.DailyRollingFileAppender">     
        <param name="File" value="E:/activex.log" />       
        <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />       
        <layout class="org.apache.log4j.PatternLayout">     
         <param name="ConversionPattern"       
            value="[%d{MMdd HH:mm:ss SSS\} %-5p] [%t] %c{3\} - %m%n" />     
        </layout>       
    </appender>     
        
    <!-- 指定logger的设置,additivity指示是否遵循缺省的继承机制-->     
    <logger name="com.runway.bssp.activeXdemo" additivity="false">     
        <priority value ="info"/>       
        <appender-ref ref="activexAppender" />       
    </logger>     
     
    <!-- 根logger的设置-->     
    <root>     
        <priority value ="debug"/>     
        <appender-ref ref="myConsole"/>     
        <appender-ref ref="myFile"/>        
    </root>     
</log4j:configuration>


(1). 输出方式appender一般有5种: 

             org.apache.log4j.RollingFileAppender(滚动文件,自动记录最新日志) 
             org.apache.log4j.ConsoleAppender (控制台) 
             org.apache.log4j.FileAppender (文件) 
             org.apache.log4j.DailyRollingFileAppender (每天产生一个日志文件) 
             org.apache.log4j.WriterAppender (将日志信息以流格式发送到任意指定的地方) 



(2). 日记记录的优先级priority,优先级由高到低分为 
            OFF ,FATAL ,ERROR ,WARN ,INFO ,DEBUG ,ALL。 
            Log4j建议只使用FATAL ,ERROR ,WARN ,INFO ,DEBUG这五个级别。 



(3). 格式说明layout中的参数都以%开始,后面不同的参数代表不同的格式化信息(参数按字母表顺序列出): 
                %c        输出所属类的全名,可在修改为 %d{Num} ,Num类名输出的维(如:"org.apache.elathen.ClassName",%C{2}将输出elathen.ClassName) 
                %d       输出日志时间其格式为 %d{yyyy-MM-dd HH:mm:ss,SSS},可指定格式 如 %d{HH:mm:ss} 
                %l        输出日志事件发生位置,包括类目名、发生线程,在代码中的行数 
                %n       换行符 
                %m      输出代码指定信息,如info(“message”),输出message 
                %p       输出优先级,即 FATAL ,ERROR 等 
                %r        输出从启动到显示该log信息所耗费的毫秒数 
                %t        输出产生该日志事件的线程名



xml declaration and DTD
xml配置文件的头部包括两个部分:xml声明和DTD声明。头部的格式如下:


<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

log4j:configuration (root element)

•xmlns:log4j [#FIXED attribute] : 定义log4j的名字空间,取定值"http://jakarta.apache.org/log4j/"
•appender [* child] : 一个appender子元素定义一个日志输出目的地
•logger [* child] : 一个logger子元素定义一个日志写出器
•root [? child] : root子元素定义了root logger


appender
appender元素定义一个日志输出目的地。


•name [#REQUIRED attribute] : 定义appender的名字,以便被后文引用
•class [#REQUIRED attribute] : 定义appender对象所属的类的全名
•param [* child] : 创建appender对象时传递给类构造方法的参数
•layout [? child] : 该appender使用的layout对象


layout
layout元素定义与某一个appender相联系的日志格式化器。


•class [#REQUIRED attribute] : 定义layout对象所属的类的全名
•param [* child] : 创建layout对象时传递给类构造方法的参数


logger
logger元素定义一个日志输出器。


•name [#REQUIRED attribute] : 定义logger的名字,以便被后文引用
•additivity [#ENUM attribute] : 取值为"true"(默认)或者"false",是否继承父logger的属性
•level [? child] : 定义该logger的日志级别
•appender-ref [* child] : 定义该logger的输出目的地


root
root元素定义根日志输出器root logger。


•param [* child] : 创建root logger对象时传递给类构造方法的参数
•level [? child] : 定义root logger的日志级别
•appender-ref [* child] : 定义root logger的输出目的地


level
level元素定义logger对象的日志级别。


•class [#IMPLIED attribute] : 定义level对象所属的类,默认情况下是"org.apache.log4j.Level类
•value [#REQUIRED attribute] : 为level对象赋值。可能的取值从小到大依次为"all"、"debug"、"info"、"warn"、"error"、"fatal"和"off"。当值为"off"时表示没有任何日志信息被输出
•param [* child] : 创建level对象时传递给类构造方法的参数


appender-ref
appender-ref元素引用一个appender元素的名字,为logger对象增加一个appender。


•ref [#REQUIRED attribute] : 一个appender元素的名字的引用
•appender-ref元素没有子元素


param
param元素在创建对象时为类的构造方法提供参数。它可以成为appender、layout、filter、errorHandler、level、categoryFactory和root等元素的子元素。


•name and value [#REQUIRED attributes] : 提供参数的一组名值对
•param元素没有子元素
在xml文件中配置appender和layout
创建不同的Appender对象或者不同的Layout对象要调用不同的构造方法。可以使用param子元素来设定不同的参数值。

创建ConsoleAppender对象
ConsoleAppender的构造方法不接受其它的参数。


... ... ... ... <appender name="console.log" class="org.apache.log4j.ConsoleAppender">   <layout ... >     ... ...   </layout> </appender> ... ... ... ...
创建FileAppender对象
可以为FileAppender类的构造方法传递两个参数:File表示日志文件名;Append表示如文件已存在,是否把日志追加到文件尾部,可能取值为"true"和"false"(默认)。


... ... ... ... <appender name="file.log" class="org.apache.log4j.FileAppender">   <param name="File" value="/tmp/log.txt" />   <param name="Append" value="false" />   <layout ... >     ... ...   </layout> </appender> ... ... ... ...
创建RollingFileAppender对象
除了File和Append以外,还可以为RollingFileAppender类的构造方法传递两个参数:MaxBackupIndex备份日志文件的个数(默认是1个);MaxFileSize表示日志文件允许的最大字节数(默认是10M)。


... ... ... ... <appender name="rollingFile.log" class="org.apache.log4j.RollingFileAppender">   <param name="File" value="/tmp/rollingLog.txt" />   <param name="Append" value="false" />   <param name="MaxBackupIndex" value="2" />   <param name="MaxFileSize" value="1024" />   <layout ... >     ... ...   </layout> </appender> ... ... ... ...
创建PatternLayout对象
可以为PatternLayout类的构造方法传递参数ConversionPattern。


... ... ... ... <layout class="org.apache.log4j.PatternLayout>   <param name="Conversion" value="%d [%t] %p - %m%n" /> </layout> ... ... ... ...     

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


 The Apache Log4J project offers a framework for logging aspects in Java software components. Today Apache Log4j is a defacto standard to realize priority/level based log messages in Java and .Net environments. The developer has to understand the following Log4J elements and classes to use this logging framework. 

•Appenders - defines handlers how to persist log entries, for example FileAppenders, SMTPAppenders, JDBCAppenders and so on
•Level/Priority - diffentent levels of logging entries, e.g. INFO, DEBUG, ERROR, TRACE, ...
•Logger - defines relations between packages and appenders, e.g. all classes of org.developers.* should be save per special appender
•...

You can configure your logging parameters per log4j.xml file, which should be saved at the root directory of your jar or source folder. The following log4j.xml file contains an basic configuration: 
  <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > <log4j:configuration>   <!-- APPENDERS LIST -->   <!-- show log entries on console -->   <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">     <layout class="org.apache.log4j.PatternLayout">       <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/>     </layout>   </appender>     <!-- log all logs to a separate log file every day -->   <appender name="orgDevelopersLogFileAppender" class="org.apache.log4j.DailyRollingFileAppender">     <param name="file" value="org-file.log" />     <param name="datePattern" value="'.'yyyy-MM-dd" />     <param name="append" value="true" />     <layout class="org.apache.log4j.PatternLayout">       <param name="ConversionPattern" value="%d [%t] %-5p %C{6} (%F:%L) - %m%n"/>     </layout>   </appender>    <!-- log all logs to a separate log file every day -->   <appender name="comDevelopersLogFileAppender" class="org.apache.log4j.DailyRollingFileAppender">     <param name="file" value="file.log" />     <param name="datePattern" value="'.'yyyy-MM-dd" />     <param name="append" value="true" />     <layout class="org.apache.log4j.PatternLayout">       <param name="ConversionPattern" value="%d [%t] %-5p %C{6} (%F:%L) - %m%n"/>     </layout>   </appender>    <!-- send all error logs to my email address -->   <appender name="mailAppender" class="org.apache.log4j.net.SMTPAppender">     <param name="SMTPHost" value="localhost" />     <param name="From" value="info@developers-blog.org" />     <param name="To" value="rafael@developers-blog.org" />     <param name="Subject" value="[BLOG ERROR LOG] ErrorList" />     <!-- if your buffer contains 50 mails, an email should be sent -->     <param name="BufferSize" value="50" />     <!-- send only errors per email -->     <param name="threshold" value="error" />     <layout class="org.apache.log4j.PatternLayout">       <param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />     </layout>   </appender>    <!-- LOGGER LIST -->   <!-- log all classes in org.developers package -->   <logger name="org.developers">     <!-- level info logs -->     <level value="INFO" />     <appender-ref ref="orgDevelopersLogFileAppender"/>   </logger>   <logger name="com.developers">     <!-- level debug logs -->     <level value="DEBUG" />     <appender-ref ref="mailAppender"/>   </logger>    <root>     <priority value="debug"></priority>     <!-- log all log entries on console -->     <appender-ref ref="consoleAppender"/>     <!-- push all error logs to mailAppender -->     <appender-ref ref="mailAppender"/>   </root> </log4j:configuration> 

JsUnit 测试 javascript,jsunit
<html>
	<script type="text/javascript" src="E:\develop Software\jsunit\jsunit2_2\jsunit\app\jsUnitCore.js"></script>
	<script type="text/javascript">
		function add(num1,num2){
			return num1 + num2;
		}
		
		function sub(num1,num2){
			return num1 - num2;
		}
		
		function mul(num1,num2){
			return num1 * num2;
		}
		
		function div(num1,num2){
			return num1 / num2;
		}
	
		//和JunitTest相似,但是方法名必须以test开头
		function testAdd(){
			var result = add(1,2);
			assertEquals(3,result)
		}
		
		function testSub(){
			var result = sub(2,1);
			assertEquals(1,result)
		}
		
		//只执行一次,类似于Junit的BeforeClass
		//注意:并没有与AfterClass对应的函数
		function setUpPage(){
			alert("setUpPage")
			
			//必须放在最后一行
			setUpPageStatus = "complete"
		}
		
		function setUp(){
			alert("setUp")
		}
		
		function tearDown(){
			alert("tearDown")
		}
		
		function tearDownPage(){
			alert("tearDownPage")
		}
                  //测试套件名必须为suite()
		function suite(){
			var testSuite = new top.jsUnitTestSuite();
			testSuite.addTestPage("test1.html");
			testSuite.addTestPage("test1.html");
			testSuite.addTestPage("test1.html");
			return testSuite;
		}
	</script>
</html>
Ant 执行批处理 ant, batch http://blog.csdn.net/zengxiangbo/article/details/2949669
<?xml version="1.0" encoding="UTF-8"?>
<!-- ====================================================================== 
     Feb 14, 2012 10:53:08 AM                                                        

     make jar package    
     description
                   
     hejian                                                                
     ====================================================================== -->
<project name="make jar package" default="copy" basedir="./.." >
	<property name="fromDir" value="./bin"></property>
	<!-- 
	<property name="toDir" value="C:\\Embedded_Software_Architecture_Emulator_10.00d\\dsdk\\hdd\\ts\\sdk\\dsdk\\xlet\\201204190"></property>
	-->
	<property name="toDir" value="C:\\Embedded_Software_Architecture_Emulator_10.00d\\dsdk\\mnt\\sd2\\sdk\\dsdk\\dist\\201204190"></property>
	<property name="toSignDir" value="D:\\software develop document\\jarsign"></property>
	<description>
            description
    </description>

    <!-- ================================= 
          target: jar              
         ================================= -->
    <target name="jar" description="description">
    	<echo>making jar file start...</echo>
        <jar destfile="${toSignDir}/SimpleScan.jar">
        	<fileset dir="${fromDir}">
        		<include name="**/*.class"/>
        		<include name="*.properties"/>
        	</fileset>
        </jar>
    	<echo>making jar file end</echo>
    </target>

	<!--  执行批处理文件,exec默认是不执行batch文件的,但是用下列方式执行即可 -->
	<target name="copy" depends="jar">
		<exec executable="cmd" dir="${toSignDir}\\">
			<arg value="/c"/>
			<arg value="SignJar.bat"/>
			<arg value="-p"/>
		</exec>
	</target>

	
</project>
javascript 继承 javascript
<html>

	<script type="text/javascript">
	//javascript 继承冒充
		function Parent(username){
			this.username = username;
			this.sayHello = function(){
				alert(this.username);
			}
			
		}
		
		function Child(username,password){
			this.method = Parent;
			this.method(username);
			delete this.method;
			//上面3行代码实现继承
			//可能您会有疑问,为什么就实现继承了呢
			//A:因为javascript的this关键字和java的this不同
			//js的this是指传递对象的引用,Child的this.method调用之后
			//this传递到Parent的方法之中,但Parent的this指向Child
			//另外,还有一点需要说明一下,Parent的this关键字只有在用new关键字创建对象是指向当前对象
			
			this.password = password;
			this.sayWorld = function(){
				alert(this.password);
			}
		}
		
		var parent = new Parent("hejian");
		var child = new Child("sunjia","123456");
		
		//parent.sayHello();
		//child.sayHello();
		//child.sayWorld();
		
		/////////////////////////////////////////
		//利用call实现继承,因为call方法是Function对象的方法,
		//其中call方法第一个参数,被传递给方法的this
		
		function Child2(username,password){
			Parent.call(this,username);
			this.password = password;
			this.sayWorld = function(){
				alert(this.password);
			}
		}
		
		//var child2 = new Child2("sunjia", "hejian");
		//child2.sayHello();
	    //child2.sayWorld();
		
		/*function Test(str){
			alert(this.name + ", " + str);
		}
		
		var object = new Object();
		object.name = "hejian";
		Test.call(object, "tojaoomy");
		*/
		
		//第三种继承方式,apply方式,和call一样,apply也是Function对象的方法
		//但是apply的第二个参数是一个数组
		function Child3(username,password){
			Parent.apply(this,[username]);
			this.password = password;
			this.sayWorld = function(){
				alert(this.password);
			}
		}
		
		var child3 = new Child3("sunjia", "hejian");
		child3.sayHello();
		child3.sayWorld();
	</script>
</html>
MYSQL存储过程及调用 mysql, procedure
下文将教您如何创建MySQL存储过程,并附上了详细的步骤,如果您在MySQL存储过程方面遇到过问题,不妨一看,对您会有所帮助。

--选择数据库

mysql> use test;  Database changed --创建示例用表

mysql> create table zzm(
    -> id int primary key auto_increment,
    -> name varchar(10));
Query OK, 0 rows affected (0.32 sec)

--更改命令结束符(因为在procedure中经常要用到默认的命令结束符--分号(;)
--所以在创建procedure的时候需要定义新的结束符以说明创建procedure的命令结束)
--这里将结束符号改成美元符号--$
mysql> delimiter $
--创建MySQL存储过程pro_hj
--此存储过程的过程名是pro_hj,该过程包含两个参数,
--一个是输入类型的(以IN标示),参数名是nameid,类型是int,
--一个是输出类型的(以OUT标示),参数名是person_name,类型是varchar(10)
--此存储过程的作用是查询出zzm表的全部内容,会输出结果集(data set),然后
--再查询表中记录的ID是nameid的字段name,将其输出到第二个输出类型的参数里面,这个查询
--不会输出结果集。

mysql> create procedure pro_hj(IN nameid int,OUT person_name varchar(10))
    -> begin
    -> select * from test.zzm;
    -> select zzm.name into person_name from test.zzm where zzm.id = nameid;
    -> end
    -> $
Query OK, 0 rows affected (0.18 sec)

插入测试数据

mysql> delimiter ;
mysql> insert into zzm (name) values('hejian');

调用存储过程之前先申明一个变量:
mysql> set @p_name='';
Query OK, 0 rows affected (0.03 sec)

调用存储过程:
mysql> call pro_hj(1,@p_name);
+----+--------+
| id | name   |
+----+--------+
|  1 | hejian |
+----+--------+
1 row in set (0.03 sec)

Query OK, 0 rows affected (0.04 sec)

调试结果:
mysql> select @p_name;
+---------+
| @p_name |
+---------+
| hejian  |
+---------+
1 row in set (0.00 sec)

-----------------------------------------
ok,再附上一篇《mysql申明变量以及赋值》

sql server中变量要先申明后赋值:

局部变量用一个@标识,全局变量用两个@(常用的全局变量一般都是已经定义好的);

申明局部变量语法:declare @变量名 数据类型;例如:declare @num int;

赋值:有两种方法式(@num为变量名,value为值)

set @num=value;   或   select @num=value;

如果想获取查询语句中的一个字段值可以用select给变量赋值,如下:

select @num=字段名 from 表名 where ……

mysql中变量不用事前申明,在用的时候直接用“@变量名”使用就可以了。

第一种用法:set @num=1; 或set @num:=1; //这里要使用变量来保存数据,直接使用@num变量

第二种用法:select @num:=1; 或 select @num:=字段名 from 表名 where ……

注意上面两种赋值符号,使用set时可以用“=”或“:=”,但是使用select时必须用“:=赋值”
SAAJ manipulate a SOAP Message java, webservice, soap
package jp.co.ricoh.bct.reboot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class SOAPService {

	private static final String GET_SESSION = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" ><SOAP-ENV:Body><m:startSession xmlns:m = \"http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement\" ><stringIn>SCHEME=QkFTSUM=;UID=YWRtaW4=;PWD=</stringIn></m:startSession></SOAP-ENV:Body></SOAP-ENV:Envelope>";
	private static final String REBOOT_MACHINE = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" ><SOAP-ENV:Body><m:rebootDevice xmlns:m = \"http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement\" ><sessionId>145499788121002</sessionId><deviceId>0</deviceId></m:rebootDevice></SOAP-ENV:Body></SOAP-ENV:Envelope>";
	private static final String url = "http://10.10.10.76/DH/devicemanagement";
	public static void invokeServiceToGetSessionId(String url,String inputXml){
		SOAPMessage reply = null;
		try {
			//create soap connection
			SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
			SOAPConnection conn = scf.createConnection();

			//create soap message
			MessageFactory factory = MessageFactory.newInstance();
			SOAPMessage msg = factory.createMessage();
			
			MimeHeaders headers = msg.getMimeHeaders();
			headers.addHeader("SOAPAction", "http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement#startSession");
			
			SOAPPart sp = msg.getSOAPPart();
			StreamSource source = new StreamSource(new StringReader(inputXml));
			sp.setContent(source);
			msg.saveChanges();
			msg.writeTo(System.out);
			reply = conn.call(msg, url);
			SOAPBody part = reply.getSOAPPart().getEnvelope().getBody();
			if(part.hasFault()){
				System.out.println(part.getFault().getFaultCode());
				System.out.println(part.getFault().getFaultString());
			}
			//read content from the response
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			Source sourceContent = reply.getSOAPPart().getContent();
			StreamResult result = new StreamResult(System.out);
			transformer.transform(sourceContent, result);
			
			conn.close();
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		} catch (SOAPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
	
	public static void invokeServiceToRebootMachine(String url,String inputXml){
		SOAPMessage reply = null;
		try {
			//create soap connection
			SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
			SOAPConnection conn = scf.createConnection();

			//create soap message
			MessageFactory factory = MessageFactory.newInstance();
			SOAPMessage msg = factory.createMessage();
			
			MimeHeaders headers = msg.getMimeHeaders();
			headers.addHeader("SOAPAction", "http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement#startSession");
			
			SOAPPart sp = msg.getSOAPPart();
			StreamSource source = new StreamSource(new StringReader(inputXml));
			sp.setContent(source);
			msg.saveChanges();
			reply = conn.call(msg, url);
			SOAPBody part = reply.getSOAPPart().getEnvelope().getBody();
			if(part.hasFault()){
				System.out.println(part.getFault().getFaultCode());
				System.out.println(part.getFault().getFaultString());
			}
			System.out.println();
			conn.close();
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		} catch (SOAPException e) {
			e.printStackTrace();
		}
	}
	
	public static void getSessionIdByHttpURLConnection(){
		String xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" ><SOAP-ENV:Body><m:startSession xmlns:m = \"http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement\" ><stringIn>SCHEME=QkFTSUM=;UID=YWRtaW4=;PWD=</stringIn></m:startSession></SOAP-ENV:Body></SOAP-ENV:Envelope>";
		try {
			URI uri = new URI("http://10.10.10.76/DH/devicemanagement");
			URL url = uri.toURL();
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("SOAPAction", "http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement#startSession");
			httpURLConnection.setRequestProperty("Content-type", "text/xml");
			OutputStream os = httpURLConnection.getOutputStream();
			PrintWriter out = new PrintWriter(os);
			out.println(xml);
			out.flush();
			StringBuilder sb = new StringBuilder();
			System.out.println(httpURLConnection.getResponseCode());
			if (HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode())   
	        {   
	            
	               
	            InputStream is = httpURLConnection.getInputStream();   
	            BufferedReader br = new BufferedReader(new InputStreamReader(is));   
	               
	            for (String line = br.readLine(); line != null; line = br.readLine())   
	            {   
	                sb.append(line);   
	            }   
	            is.close();   
	        }   
	           
	        // Release resource   
	        os.close();   
	        out.close();   
	        httpURLConnection.disconnect();   
	           
	        String soapResponse = sb.toString();   
	        System.out.println("=============");
	        System.out.println(soapResponse);   

		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void rebootMachineByHttpURLConnection(){
		String xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" ><SOAP-ENV:Body><m:rebootDevice xmlns:m = \"http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement\" ><sessionId>145499788121002</sessionId><deviceId>0</deviceId></m:rebootDevice></SOAP-ENV:Body></SOAP-ENV:Envelope>";
		try {
			URI uri = new URI("http://10.10.10.76/DH/devicemanagement");
			URL url = uri.toURL();
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("SOAPAction", "http://www.ricoh.co.jp/xmlns/soap/rdh/devicemanagement#rebootDevice");
			httpURLConnection.setRequestProperty("Content-type", "text/xml");
			OutputStream os = httpURLConnection.getOutputStream();
			PrintWriter out = new PrintWriter(os);
			out.println(xml);
			out.flush();
			StringBuilder sb = new StringBuilder();
			System.out.println(httpURLConnection.getResponseCode());
			if (HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode())   
	        {   
	            
	               
	            InputStream is = httpURLConnection.getInputStream();   
	            BufferedReader br = new BufferedReader(new InputStreamReader(is));   
	               
	            for (String line = br.readLine(); line != null; line = br.readLine())   
	            {   
	                sb.append(line);   
	            }   
	            is.close();   
	        }   
	           
	        // Release resource   
	        os.close();   
	        out.close();   
	        httpURLConnection.disconnect();   
	           
	        String soapResponse = sb.toString();   
	        System.out.println("=============");
	        System.out.println(soapResponse);   

		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
//		invokeService("","");
//		String result = BASE64Util.encoder("admin");
//		System.out.println(result);
//		result = BASE64Util.decoder("QkFTSUM=");
//		System.out.println(result);
//		getSessionIdByHttpURLConnection();
//		rebootMachineByHttpURLConnection();
		invokeServiceToGetSessionId(url, GET_SESSION);
	}
}


Reference:
http://stackoverflow.com/questions/1046407/soapaction-issue-under-java-1-3
http://yunchow.iteye.com/blog/741673
http://java.boot.by/wsd-guide/ch05s04.html
http://www.ibm.com/developerworks/cn/xml/x-jaxmsoap/
http://oss.org.cn/ossdocs/one_and_net/app7/12.1.htm
Java Edit INI Sufix File java
package jp.co.ricoh.twitter.ini;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class UseIni {

	public static String getProfileString(String file,String section,
		String variable,String defaultValue)throws IOException {
		String strLine, value = "";
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		boolean isInSection = false;
		try {
			while ((strLine = bufferedReader.readLine()) != null){
				strLine = strLine.trim(); 
				strLine = strLine.split("[;]")[0];
				Pattern p;
				Matcher m;
				p = Pattern.compile("\\[\\s*.*\\s*\\]");
				m = p.matcher((strLine));    
				if (m.matches()){
					p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
					m = p.matcher(strLine);
					if (m.matches()){
						isInSection = true;
					}else{
						isInSection = false;
					}
				}

				if (isInSection == true){
					strLine = strLine.trim();
					String[] strArray = strLine.split("=");
					if (strArray.length == 1){
						value = strArray[0].trim();
						if (value.equalsIgnoreCase(variable)){
							value = "";
							return value;
						}
					}else if (strArray.length == 2){
						value = strArray[0].trim();
						if (value.equalsIgnoreCase(variable)) {
							value = strArray[1].trim();
							return value;
						}
					}else if (strArray.length > 2){
						value = strArray[0].trim();
						if (value.equalsIgnoreCase(variable)){
							value = strLine.substring(strLine.indexOf("=") + 1).trim();
							return value;
						}
					}
				}
			}
		}finally{
			bufferedReader.close();
		}
		return defaultValue;
	}

	public static boolean setProfileString(String file,String section,
		String variable,String value)throws IOException{
		String fileContent, allLine,strLine, newLine, remarkStr;
		String getValue;
		BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
		boolean isInSection = false;
		fileContent = "";
		try {
			while ((allLine = bufferedReader.readLine()) != null) {
				allLine = allLine.trim();
				if (allLine.split("[;]").length > 1){
					remarkStr = ";" + allLine.split(";")[1];
				}else{
					remarkStr = "";
				}
				strLine = allLine.split(";")[0];
				Pattern p;
				Matcher m;
				p = Pattern.compile("\\[\\s*.*\\s*\\]");
				m = p.matcher((strLine));
				if (m.matches()) {
					p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
					m = p.matcher(strLine);
					if (m.matches()){
						isInSection = true;
					} else {
						isInSection = false;
					}
				}
				if (isInSection == true){
					strLine = strLine.trim();
					String[] strArray = strLine.split("=");
					getValue = strArray[0].trim();
					if (getValue.equalsIgnoreCase(variable)){
						newLine = getValue + "=" + value + " " + remarkStr;
						fileContent += newLine + "\r\n";
						while ((allLine = bufferedReader.readLine()) != null){
							fileContent += allLine + "\r\n";
						}
						bufferedReader.close();
						BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter(file, false));
						bufferedWriter.write(fileContent);
						bufferedWriter.flush();
						bufferedWriter.close();
						return true;
					}
				}else{
//					System.out.println("not contained...");
//					System.out.println("=================" + fileContent);
				}
				
				fileContent += allLine + "\r\n";
			}
		}catch(IOException ex){
			throw ex;
		}finally{
			bufferedReader.close();
		}
		return false;
	}
	
	public static boolean addProfileString(String file,String section,
			String variable,String value)throws IOException{
			String fileContent, allLine,strLine, newLine, remarkStr;
			String getValue;
			BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
			boolean isInSection = false;
			fileContent = "";
			try {
				while ((allLine = bufferedReader.readLine()) != null) {
					allLine = allLine.trim();
					if (allLine.split("[;]").length > 1){
						remarkStr = ";" + allLine.split(";")[1];
					}else{
						remarkStr = "";
					}
					strLine = allLine.split(";")[0];
					Pattern p;
					Matcher m;
					p = Pattern.compile("\\[\\s*.*\\s*\\]");
					m = p.matcher((strLine));
					if (m.matches()) {
						p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
						m = p.matcher(strLine);
						if (m.matches()){
							isInSection = true;
						} else {
							isInSection = false;
						}
					}
					if (isInSection == true){
						
						String result = getProfileString(file, section, variable, "");
						if(result!=null && !result.equals("")){
							return true;
						}
						bufferedReader.close();
						bufferedReader = new BufferedReader(new FileReader(file));
						String str = "[" + section + "]";
						
						fileContent = "";
System.out.println("section " + str);						
System.out.println("before fileContent " + fileContent);	
						while ((allLine = bufferedReader.readLine()) != null){
							fileContent += allLine + "\r\n";
							if(str.equalsIgnoreCase(allLine)){
								newLine = variable + "=" + value + "\r\n";
								fileContent += newLine;
							}
						}
						bufferedReader.close();
						BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter(file, false));
System.out.println("after fileContent " + fileContent);						
						bufferedWriter.write(fileContent);
						bufferedWriter.flush();
						bufferedWriter.close();
						return true;
					}					
					fileContent += allLine + "\r\n";
				}
			}catch(IOException ex){
				throw ex;
			}finally{
				bufferedReader.close();
			}
			return false;
		}
	
	public static boolean deleteProfileString(String file,String section,
			String variable)throws IOException{
			String fileContent, allLine,strLine,remarkStr;
			String getValue;
			BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
			boolean isInSection = false;
			fileContent = "";
			try {
				while ((allLine = bufferedReader.readLine()) != null) {
					allLine = allLine.trim();
					if (allLine.split("[;]").length > 1){
						remarkStr = ";" + allLine.split(";")[1];
					}else{
						remarkStr = "";
					}
					strLine = allLine.split(";")[0];
					Pattern p;
					Matcher m;
					p = Pattern.compile("\\[\\s*.*\\s*\\]");
					m = p.matcher((strLine));
					if (m.matches()) {
						p = Pattern.compile("\\[\\s*" + section + "\\s*\\]");
						m = p.matcher(strLine);
						if (m.matches()){
							isInSection = true;
						} else {
							isInSection = false;
						}
					}
					if (isInSection == true){
						strLine = strLine.trim();
						String[] strArray = strLine.split("=");
						getValue = strArray[0].trim();
						if (getValue.equalsIgnoreCase(variable)){
//							newLine = getValue + "=" + value + " " + remarkStr;
//							fileContent += newLine + "\r\n";
							while ((allLine = bufferedReader.readLine()) != null){
								fileContent += allLine + "\r\n";
							}
							bufferedReader.close();
							BufferedWriter bufferedWriter =new BufferedWriter(new FileWriter(file, false));
							bufferedWriter.write(fileContent);
							bufferedWriter.flush();
							bufferedWriter.close();
							return true;
						}
					}else{
//						System.out.println("not contained...");
//						System.out.println("=================" + fileContent);
					}
					
					fileContent += allLine + "\r\n";
				}
			}catch(IOException ex){
				throw ex;
			}finally{
				bufferedReader.close();
			}
			return false;
		}
}

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

package jp.co.ricoh.twitter.ini;

import java.io.IOException;
import java.net.URL;

public class Test {
	public static String filePath = "";
	public static String VERSION = "Version";
	public static String FEATURE = "Feature";
	
	public static final String GSNX_ESCPB = "GSNX-ESCPB";
	public static final String VERSION_VALUE = "1.0";
	public static final String GSNX_EELPB = "GSNX-EELPB";
	
	public static final String FEATURE_GSNX_ESCPB_VALUE = "GlobalScan NX Script Plug-in";
	public static final String FEATURE_GSNX_EELPB_VALUE = "GlobalScan NX Enhanced Lookup Plug-in";
	public static void add_escpb(){
		try {
			UseIni.addProfileString(filePath, VERSION, GSNX_ESCPB, VERSION_VALUE);
			UseIni.addProfileString(filePath, FEATURE, GSNX_ESCPB, FEATURE_GSNX_ESCPB_VALUE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void add_eelpb(){
		try {
			UseIni.addProfileString(filePath, VERSION, GSNX_EELPB, VERSION_VALUE);
			UseIni.addProfileString(filePath, FEATURE, GSNX_EELPB, FEATURE_GSNX_EELPB_VALUE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void delete_escpb(){
		try {
			UseIni.deleteProfileString(filePath, VERSION, GSNX_ESCPB);
			UseIni.deleteProfileString(filePath, FEATURE, GSNX_ESCPB);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void delete_eelpb(){
		try {
			UseIni.deleteProfileString(filePath, VERSION, GSNX_EELPB);
			UseIni.deleteProfileString(filePath, FEATURE, GSNX_EELPB);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception {
		filePath = args[0] + "\\bin\\RLicAct.inf";
		if(args[1].equalsIgnoreCase("install")){
			if(args[2].equalsIgnoreCase(GSNX_ESCPB)){
				add_escpb();
			}else if(args[2].equalsIgnoreCase(GSNX_EELPB)){
				add_eelpb();
			}
		}else if(args[1].equalsIgnoreCase("uninstall")){
			if(args[2].equalsIgnoreCase(GSNX_ESCPB)){
				delete_escpb();
			}else if(args[2].equalsIgnoreCase(GSNX_EELPB)){
				delete_eelpb();
			}
		}
	}

}
Twitter twitter
package jp.co.ricoh.twitter.example;

import java.util.Properties;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class test {

	public static void test1() {
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		.setUser("tojaoomy")
		.setPassword("beubbc69");

		Twitter t = new TwitterFactory(cb.build()).getInstance();
		try {
			t.updateStatus("My name is HeJian");
		} catch (TwitterException e) {
			e.printStackTrace();
		}
	}

	public static void test2() {
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
		.setOAuthConsumerKey("DIPaPM6lgKVmTPFPLfpA")
		.setOAuthConsumerSecret(
				"HUfrSCTxzTWwYyafrimHzYx0qVsj1KUMNtEoWw82Us")
		.setOAuthAccessToken(
				"557452495-FW74dpS0NhRgMnrZgah7yd84vmxuVYA2EAZqDVQ5")
		.setOAuthAccessTokenSecret(
				"5Jc5bct1iUltsRnMN7Mq6jolJPBfRROxz1In3nNji6U");

		Twitter t = new TwitterFactory(cb.build()).getInstance();
		try {
			t.updateStatus("My name is HeJian");
		} catch (TwitterException e) {
			e.printStackTrace();
		}
	}

	public static void getSweet(){
		ConfigurationBuilder cb = new ConfigurationBuilder();
		cb.setDebugEnabled(true)
				.setOAuthConsumerKey("DIPaPM6lgKVmTPFPLfpA")
				.setOAuthConsumerSecret(
						"HUfrSCTxzTWwYyafrimHzYx0qVsj1KUMNtEoWw82Us")
				.setOAuthAccessToken(
						"557452495-FW74dpS0NhRgMnrZgah7yd84vmxuVYA2EAZqDVQ5")
				.setOAuthAccessTokenSecret(
						"5Jc5bct1iUltsRnMN7Mq6jolJPBfRROxz1In3nNji6U");

		Twitter t = new TwitterFactory(cb.build()).getInstance();
		try {
			System.out.println(t.getFavorites().size());;
		} catch (TwitterException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		Properties props = new Properties(System.getProperties());
		props.put("http.proxySet", "true");
		props.put("http.proxyHost", "10.6.248.80");
		props.put("http.proxyPort", "8080");
		props.put("http.proxyUser", "y3750143");
		props.put("http.proxyPassword", "oyl3750143");
		Properties newProp = new Properties(props);
		System.setProperties(newProp);

		test2();
//		getSweet();
	}
}



http://twitter4j.org/en/configuration.html
Global site tag (gtag.js) - Google Analytics