`
收藏列表
标题 标签 来源
ldap java, ldap
package com.neusoft.ermsuite.sso;

import java.util.Properties;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.LdapContext;

public class UserCheckForPortal {
	private LdapContext ctx = null;
	//private String baseName = ",OU=ou1,DC=hnyctest,DC=com";

	/**
	 * 初始化方法,初始化超级管理员的连接权限
	 */
	public UserCheckForPortal() {
	}
	
	/**
	 * 
	 * ldap验证登陆
	 * @param userDn
	 *            String
	 * @param password
	 *            String
	 * @return boolean
	 */
	public boolean authenticate(String userDn, String password,String ldapUrl,String domain) throws Exception {
		DirContext ctx1;
		boolean result = false;
		try {
			
			Properties ldapEnv = new Properties();
			ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			ldapEnv.put(Context.PROVIDER_URL, ldapUrl.trim());
			ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
			String user = userDn.indexOf(domain) > 0 ? userDn : userDn + domain;
			ldapEnv.put(Context.SECURITY_PRINCIPAL, user);
			ldapEnv.put(Context.SECURITY_CREDENTIALS, password);
			ctx1 = new InitialDirContext(ldapEnv);
			ctx1.close();
			result = true;
			return result;
		} catch (AuthenticationException e) {
			e.printStackTrace();
			System.out.println(e);
			System.err.println(e);
			return false;
		} catch (NamingException e) {
			e.printStackTrace();
			System.out.println(e);
			System.err.println(e);
			return false;
		}

	}
}
java策略枚举 java, enum, strategy pattern(策略模式)
public class EnumTest {
	public static void main(String args[]) {
		int result = Calculator.getInstance("+").exec(1, 2);
		System.out.println(result);		
		result = Calculator.getInstance("-").exec(1, 2);
		System.out.println(result);
	}

}

enum Calculator {
	// 加法运算
	ADD("+") {
		public int exec(int a, int b) {
			return a + b;
		}
	},
	// 减法运算
	SUB("-") {
		public int exec(int a, int b) {
			return a - b;
		}
	};

	String value = "";

	// 定义成员值类型
	private Calculator(String _value) {
		this.value = _value;
	}

	// 获得枚举成员的值
	public String getValue() {
		return this.value;
	}

	// 声明一个抽象函数
	public abstract int exec(int a, int b);

	public static Calculator getInstance(String opt) {
		for (Calculator cal : Calculator.values()) {
			if (opt.equals(cal.getValue())) {
				return cal;
			}
		}
		return Calculator.ADD;
	}
}
Solrj查询 java, solr
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;


public class SolrSearchManager {
	/**
	 * standard query
	 * 
	 * @param args
	 * @throws MalformedURLException 
	 */
	public static void main(String args[]) throws MalformedURLException {
		HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr");
		server.setSoTimeout(1000); // socket read timeout
		server.setConnectionTimeout(100);
		server.setDefaultMaxConnectionsPerHost(100);
		server.setMaxTotalConnections(100);
		server.setFollowRedirects(false); // defaults to false
		// Server side must support gzip or deflate for this to have any effect.
		server.setAllowCompression(true);
		server.setMaxRetries(1); // defaults to 0. > 1 not recommended.
		server.setParser(new XMLResponseParser()); // binary parser is used by
													// default

		SolrQuery query = new SolrQuery();
		query.setQuery("*:*");
		query.addSortField("id", SolrQuery.ORDER.asc);

		try {
			QueryResponse queryResponse = server.query(query);

			// SolrDocumentList docs = rsp.getResults();

			Iterator<SolrDocument> iter = queryResponse.getResults().iterator();

			while (iter.hasNext()) {
				SolrDocument resultDoc = iter.next();

				String id = (String) resultDoc.getFieldValue("id"); // id is the
																	// uniqueKey
				String name = resultDoc.getFieldValue("text_cn") == null ? "" : (String) resultDoc.getFieldValue("text_cn"); 													// field
                System.out.println("name...." + name);
//				if (queryResponse.getHighlighting().get(id) != null) {
//					List<String> highlightSnippets = queryResponse
//							.getHighlighting().get(id).get("content");
//				}
			}

		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
获取字段 java, reflection
    public static Field getField(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (Exception e) {
            return null;
        }
    }
获取默认构造函数 java, reflection
public static Constructor<?> getDefaultConstructor(Class<?> clazz) {
        if (Modifier.isAbstract(clazz.getModifiers())) {
            return null;
        }

        Constructor<?> defaultConstructor = null;
        for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
            if (constructor.getParameterTypes().length == 0) {
                defaultConstructor = constructor;
                break;
            }
        }
        
        if (defaultConstructor == null) {
            if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
                for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                    if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0].equals(clazz.getDeclaringClass())) {
                        defaultConstructor = constructor;
                        break;
                    }
                }
            }
        }
        
        return defaultConstructor;
    }
JSON解析(JSON-LIB) json, java
import java.util.ArrayList;

import net.sf.ezmorph.bean.MorphDynaBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.util.JSONTokener;


public class JSONLibTest {
	public static void main(String args[])
	{   //针对数组的解析
		String param= "[{'userid':'用户名1','telNum':'手机号1','taskid':'任务标识1','sms':'短信1'},{'userid':'用户名2','telNum':'手机号2','taskid':'任务标识2','sms':'短信2'}]";
		JSONArray array = JSONArray.fromObject(param);
	    ArrayList list = (ArrayList) JSONSerializer.toJava(array);    
	    if(list.size()>0){
	    	 for(int i=0 ; i<list.size();i++){
		        	MorphDynaBean obj = (MorphDynaBean)list.get(i);
		        	System.out.println((String) obj.get("userid") + obj.get("telNum") + obj.get("taskid") + obj.get("sms"));
		        }
	    }
	    
	    //针对一般数据的解析    
	    String param2 =  "{'userid':'用户名1','telNum':'手机号1','taskid':'任务标识1','sms':'短信1'}";
	    
	    JSONTokener jsonParser = new JSONTokener(param2);   
		// 此时还未读取任何json文本,直接读取就是一个JSONObject对象。   
		JSONObject object = (JSONObject) jsonParser.nextValue(); 
		
		System.out.println(object.getString("userid") + object.getString("telNum") + object.getString("taskid") + object.getString("sms"));
	}
	
}
正则表达式 java, regexp
    	Pattern p = Pattern.compile("(\\d{5})-?(\\d{9})-?(\\d{2})-?([a-zA-Z]{4})-?(\\d{6})-?(\\d{1})-?(\\d{5})");
    	String str = "90621-119769249-01-BJYC-111011-1-00001";
        Matcher m = p.matcher(str);
        while(m.find()) {
            for(int j = 1; j <= m.groupCount(); j++)
               System.out.println("[" + m.group(j) + "]");
       }  
java安全访问授权 java
grant {
  permission java.security.AllPermission;
};
JAVA学习 java
目前学习
JVM

1、线程
2、泛型
3、反射

框架学习
Struts
Spring
Adapter Pattern java, design pattern, adapter JDK 1.5 java.util.concurrent.Executors
/**
     * Returns a {@link Callable} object that, when
     * called, runs the given task and returns the given result.  This
     * can be useful when applying methods requiring a
     * <tt>Callable</tt> to an otherwise resultless action.
     * @param task the task to run
     * @param result the result to return
     * @throws NullPointerException if task null
     * @return a callable object
     */
    public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }

/**
     * A callable that runs given task and returns given result
     */
    static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable  task, T result) {
            this.task = task; 
            this.result = result;
        }
        public T call() { 
            task.run(); 
            return result; 
        }
    }
Builder Pattern java, builder, design pattern Effective Java 2nd Edition
// Builder Pattern
public class NutritionFacts {
	private final int servingSize;
	private final int servings;
	private final int calories;
	private final int fat;
	private final int sodium;
	private final int carbohydrate;

	public static class Builder {
		// Required parameters
		private final int servingSize;
		private final int servings;
		// Optional parameters - initialized to default values
		private int calories = 0;
		private int fat = 0;
		private int carbohydrate = 0;
		private int sodium = 0;

		public Builder(int servingSize, int servings) {
			this.servingSize = servingSize;
			this.servings = servings;
		}

		public Builder calories(int val) {
			calories = val;
			return this;
		}

		public Builder fat(int val) {
			fat = val;
			return this;
		}

		public Builder carbohydrate(int val) {
			carbohydrate = val;
			return this;
		}

		public Builder sodium(int val) {
			sodium = val;
			return this;
		}

		public NutritionFacts build() {
			return new NutritionFacts(this);
		}
	}

	private NutritionFacts(Builder builder) {
		servingSize = builder.servingSize;
		servings = builder.servings;
		calories = builder.calories;
		fat = builder.fat;
		sodium = builder.sodium;
		carbohydrate = builder.carbohydrate;
	}
	
	public static void main(String args[])
	{
		NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
		calories(100).sodium(35).carbohydrate(27).build();
	}
}
native2ascii java, asc
/**
 * 
 * native2ascii.exe Java code implementation.
 * 
 * 
 * 
 * @author
 * 
 * @version 1.0
 * 
 */

public class Native2AsciiUtils {

	/**
	 * 
	 * prefix of ascii string of native character
	 * 
	 */
	private static String PREFIX = "\\u";

	/**
	 * 
	 * Native to ascii string. It's same as execut native2ascii.exe.
	 * 
	 * 
	 * 
	 * @param str
	 * 
	 * native string
	 * 
	 * @return ascii string
	 * 
	 */

	public static String native2Ascii(String str) {

		char[] chars = str.toCharArray();

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < chars.length; i++) {

			sb.append(char2Ascii(chars[i]));

		}

		return sb.toString();
	}

	/**
	 * 
	 * Native character to ascii string.
	 * 
	 * 
	 * 
	 * @param c
	 * 
	 * native character
	 * 
	 * @return ascii string
	 * 
	 */

	private static String char2Ascii(char c) {

		if (c > 255) {

			StringBuilder sb = new StringBuilder();

			sb.append(PREFIX);

			int code = (c >> 8);

			String tmp = Integer.toHexString(code);

			if (tmp.length() == 1) {

				sb.append("0");

			}

			sb.append(tmp);

			code = (c & 0xFF);

			tmp = Integer.toHexString(code);

			if (tmp.length() == 1) {

				sb.append("0");

			}

			sb.append(tmp);

			return sb.toString();

		} else {

			return Character.toString(c);

		}

	}

	/**
	 * 
	 * Ascii to native string. It's same as execut native2ascii.exe -reverse.
	 * 
	 * 
	 * 
	 * @param str
	 * 
	 * ascii string
	 * 
	 * @return native string
	 * 
	 */

	public static String ascii2Native(String str) {

		StringBuilder sb = new StringBuilder();

		int begin = 0;

		int index = str.indexOf(PREFIX);

		while (index != -1) {

			sb.append(str.substring(begin, index));

			sb.append(ascii2Char(str.substring(index, index + 6)));

			begin = index + 6;

			index = str.indexOf(PREFIX, begin);

		}

		sb.append(str.substring(begin));

		return sb.toString();

	}

	/**
	 * 
	 * Ascii to native character.
	 * 
	 * 
	 * 
	 * @param str
	 * 
	 * ascii string
	 * 
	 * @return native character
	 * 
	 */

	private static char ascii2Char(String str) {

		if (str.length() != 6) {

			throw new IllegalArgumentException(

			"Ascii string of a native character must be 6 character.");

		}

		if (!PREFIX.equals(str.substring(0, 2))) {

			throw new IllegalArgumentException(

			"Ascii string of a native character must start with \"\\u\".");

		}

		String tmp = str.substring(2, 4);

		int code = Integer.parseInt(tmp, 16) << 8;

		tmp = str.substring(4, 6);

		code += Integer.parseInt(tmp, 16);

		return (char) code;

	}
   
	
	public static void main (String args[])
	{
		System.out.println(ascii2Native("\u521d\u59cb\u5316,\u5728\u529e\u7406,\u5ba1\u6838\u4e2d,\u6302\u8d77\u6001,\u5df2\u5b8c\u6210,\u5df2\u7ed3\u675f"));
		System.out.println(native2Ascii("已停止"));
	}
}
Global site tag (gtag.js) - Google Analytics