Java代码中通过代理访问外部资源java net穿透代理服务器2007-03-24 10:09:08

目前网络上最流行的协议就是HTTP协议。HTTP协议有许多优点,例如它能够穿越防火墙。同时HTTP也是很多其他协议的基础,例如SOAP协议就是建立在HTTP协议之上的。

Java通过两种API对HTTP提供支持,一种是servlet API,它覆盖了服务器端的编程问题;另一种是java.net包,它通过HttpURLConnection类在客户端提供了对HTTP协议的支持。但是我在使用servlet API的时候曾经遇到过一些问题。本文将介绍我曾遇到过的一些问题和相应的解决办法。

基础知识

通常在企业网络中,一个终端通过代理服务器同互联网连接起来,代理服务器负责监视网络流量和执行安全规则。在java.net API中,软件可以通过两个属性来支持代理服务器,它们分别是http.proxyHost和http.proxyPort。它们必须被设定为相应的代理服务器和端口,下面的代码展示了如何设定这两个属性:

String url = "http://www.digitalcq.com/",
   proxy = "proxy.digitalcq.com",
   port = "8080";
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (
    HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);


在上面的程序中,你需要根据实际情况设定代理服务器和端口。如果你不知道该如何设置的话,可以询问你们公司的网络管理员。

使用验证

通常公司会要求员工在连接到互联网之前登录到代理服务器。通过登录这种机制使公司可以更好的监控员工对互联网的使用,例如监控员工都访问了哪些网站。HttpURLConnection通过验证类支持代理服务器验证。下面是一个如何利用HttpURLConnection类进行验证的例子。首先需要实现一个验证者:

public class SimpleAuthenticator
   extends Authenticator
{
   private String username,
                  password;
    public SimpleAuthenticator(String username,String password)
   {
      this.username = username;
      this.password = password;
   }
    protected PasswordAuthentication getPasswordAuthentication()
   {
      return new PasswordAuthentication(
             username,password.toCharArray());
   }
}


然后,通过Authenticator.setDefault()方法注册验证者:

String url = "http://www.digitalcq.com/",
       proxy = "proxy.digitalcq.com",
       port = "8080",
       username = "usr",
       password = "pwd";
Authenticator.setDefault(new SimpleAuthenticator(
       username,password));
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (
    HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);


问题

上面介绍的都是HttpURLConnection类能够正常工作的情况。但是我在实际情况中遇到了一些网络,在这些网络中,HttpURLConnection类无法正常工作。最后我发现关键的问题在于使用了不正确的DNS配置。在实际情况中,HttpURLConnection类总是先尝试利用DNS服务器来解析地址名称。通常情况下,这种尝试会失败,而代理服务器会将连接重新定向。但是某些DNS服务器会返回一些不正确的响应,从而导致程序抛出UnknownHostException异常。作为一个程序员,系统不会为了你的程序更改DNS服务器的配置,因此你需要找出解决这个问题的方法。我的方案是通过自己实现HTTP协议来解决这个问题。例如一个GET命令可以用下面的代码来实现:

String url = "http://www.digitalcq.com/",
       proxy = "proxy.digitalcq.com",
       port = "8080",
       authentication = "usr:pwd";
URL server = new URL(url);
Socket socket = new Socket(proxy,port);
Writer writer = new OutputStreamWriter(socket.getOutputStream(),
                                       "US-ASCII");
writer.write("GET " + server.toExternalForm() + " HTTP/1.0rn");
writer.write("Host: " + server.getHost() + "rn");
writer.write("Proxy-Authorization: Basic "
             + new sun.misc.BASE64Encoder().encode(
               authentication.getBytes())
             + "rnrn");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(
                            socket.getInputStream(),"US-ASCII"));
String line = reader.readLine();
if(line != null && line.startsWith("HTTP/"))
{
   int sp = line.indexOf(' ');
   String status = line.substring(sp + 1,sp + 4);
   if(status.equals("200"))
   {
      while(line.length() != 0)
         line = reader.readLine();
      readResponse(reader);
   }
   else
      throw new FileNotFoundException("Host reports error " +
                                       status);
}
else
   throw new IOException("Bad protocol");
reader.close();
writer.close();
socket.close();


在上面的代码中,大家可以注意到代理服务器的用户名和密码的格式是:

username:password,

 

JavaIO利用迭代读取文件夹所有目录及文件2007-03-24 10:08:07

import java.io.File;
import java.util.ArrayList;

public class ReadFile {
 public static void main(String args[]) {
  String dir = "D:xxx";

  ArrayList a = getFiles(dir);
  for (int i = 0; i < a.size(); i++) {
   File file = (File) a.get(i);
  }
 }

 public static ArrayList getFiles(String aDir) {
  ArrayList files = new ArrayList();
  File dirx = new File(aDir);
  File[] dirFilesx = dirx.listFiles();

  for (int k = 0; k < dirFilesx.length; k++) {
   System.out.print("|");
   File file = dirFilesx[k];
   String fileName = file.getName();
   System.out.println("-" + fileName);
   if (file.isDirectory()) {
    String dirx1 = aDir + "" + fileName;
    getFiles(dirx1);
   }
   files.add(file);
  }
  return files;

 }

}

java读写UTF-8格式文本2007-02-25 08:25:04

1)java写UTF-8格式文本

File file = new File("fileName.txt");
PrintWriter out = null;
out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
out.println("OK");
out.close;
注:java编译环境也使用UTF-8编码

2)java读UTF-8格式文本

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader (new FileInputStream(file),"UTF-8"));

Tapestry4 Blog :)2007-02-10 20:52:48

Tapestry4 Blog
hibernate3 spring2 tapestry4

 

Tapestry OGNL 三目表达式2007-02-10 15:02:05

使用场景:

当打开的Page是本身链接时候class是current样式 

demo

<a jwcid="@PageLink" page="PostEdit" scheme="http" class="ognl:(page.pageName == 'PostEdit')?'current':''">
Write Page
</a>

 参考资料
e1 ? e2 : e3

Conditional operator

getValue is called on e1 and the result is interpreted as a boolean. getValue is then called on either e2 or e3, depending on whether the result of e1 was true or false respectively, and the result is returned.getValue is called on e1, and then setValue is called on either e2 or e3

 

Java中调用groovy脚本2007-02-01 13:26:52

Java中调用groovy脚本

Test.java
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
import java.io.IOException;
import org.codehaus.groovy.control.CompilationFailedException;
public class Test {
 
 public static void main(String[] args) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException{

   ClassLoader parent = ClassLoader.getSystemClassLoader();
        
   GroovyClassLoader loader = new GroovyClassLoader(parent);
   Class groovyClass = loader.parseClass(new File
               ("Calculator.groovy"));
   GroovyObject groovyObject = (GroovyObject)groovyClass.newInstance();
  
   Object obj = groovyObject.invokeMethod("add",new Object[]{new Integer(2),new Integer(1)});
   System.out.println(obj);

 }

}

Calculator.groovy

import org.springframework.scripting.Calculator
class GroovyCalculator implements Calculator {
    int add(int x, int y) {
        x +y +x*2
    }
}


参考资料
http://openjavaproject.blogdriver.com/openjavaproject/345196.html
http://hi.baidu.com/cuiyuanju/blog/item/88f387dd446bc5345882dd64.html

Tapestry4Localization本地化/国际化2007-01-31 16:53:08

Tapestry4Localization本地化/国际化
1、方法1 -- 使用Tapestry

1)Home.html
<span jwcid="@Insert" value="message:required"/> //使用message前缀

或者使用ognl:messages

<span jwcid="@Insert" value="ognl:messages.format('required', '第{0}个元素','第{1}个元素')"/>

不要使用
<span jwcid="@Insert" value="ognl:getMessage('required')"/>
因为getMessage方法在T4中被@deprecated

-----the key 'title'---- will be first find in Home_zh.properties or Home.properties

if in Home.properties can not be founded

it will find WEB-INF/myapp.properties,
The specification may also have a message catalog; for instance,
for WEB-INF/myapp.application,
the files would be named WEB-INF/myapp.properties,
etc. Again, the name of the file is based on the servlet name ("myapp").

2)
myapp_zh.properties
required=u8bf7u8f93u5165{0}u7684u503c{1}

3)
Home_zh.properties
required=u8bf7u8f93u5165{0}u7684u503c{1}

 

2、方法2 --使用spring的MessageSource
1)利用spring加载messges_*local.properties
 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
  <!--<property name="basename" value="classpath:messages"/>-->
   <property name="basenames">
      <list>
        <value>classpath:messages</value>
      </list>
    </property>  
 </bean>
把messageSource注入到Tapestry Components/Pages中

2)BasePage.java

import org.springframework.context.MessageSource;
//need inject //or direct impl it;
public abstract BasePage extends org.apache.tapestry.html.BasePage{

 public abstract MessageSource getMessageSource();

}


3)HomePage.java extends BasePage.java

4)Home.page
  <inject property="messageSource" object="spring:messageSource" />
5)Home.html

<span jwcid="@Insert" value="ognl:messageSource.getMessage('required',new java.lang.Object [] {'Login','!'}, 'Default', null)"/>

6)messges_zh.properties
required=u8bf7u8f93u5165{0}u7684u503c{1}
------------------------------------------------------------------
7)或者再封装以下
public abstract BasePage extends org.apache.tapestry.html.BasePage{
 public abstract MessageSource getMessageSource();
 public String getCustomMessage(java.lang.String arg0,java.lang.Object[] arg1,java.lang.String arg2,java.util.Locale arg3){
  return this.getMessageSource().getMessage(arg0,arg1,arg2,arg3);
 }
}
then in the Home.html

<span jwcid="@Insert" value="ognl:getCustomMessage('required',new java.lang.Object [] {'Login','!'}, 'Default', null)"/>

 

 

 

 

同步和异步2007-01-25 21:58:06

同步和异步用来描述过程运行的方式 

同步:所有的子过程按照时间顺序执行,完成一步才能进行下一步。

异步:所有的子过程可以单独运行,每个子过程不用等别的过程完成。看上去像多线程一样

 

Spring2.0中的定时调度(Scheduling)使用OpenSymphony Quartz调度器使用笔记2007-01-22 15:40:49

Spring2.0中的定时调度(Scheduling)使用OpenSymphony Quartz调度器使用笔记
1)、加入spring-framework-2.0.2libquartzquartz-1.6.0.jar 包
2)、使用commons-collections-3.1.jar,不要使用旧的commons-collections-2.1.1.jar
3)、书写Job实现类
package example
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class ExampleJob extends QuartzJobBean{
 protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
  
  //System.out.println(System.currentTimeMillis());
  //dofoo
 }
 private int timeout;
   public void setTimeout(int timeout) {
     this.timeout = timeout;
   }
}
4)、书写beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd      
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean name="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
  <property name="jobClass" value="example.ExampleJob" />
  <property name="jobDataAsMap">
    <map>
      <entry key="timeout" value="5" />
    </map>
  </property>
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
    <!-- see the example of method invoking job above -->
    <property name="jobDetail" ref="jobDetail" />
    <!-- 10 seconds -->
    <property name="startDelay" value="10000" />
    <!-- repeat every 50 seconds -->
    <property name="repeatInterval" value="50000" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="triggers">
        <list>
            <ref bean="simpleTrigger" />
        </list>
    </property>
</bean>
</beans>      

读取文件到byte[]数组2007-01-22 09:53:58

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

public class FileUtil {

 public byte[] getFileByte(String fileName) throws FileNotFoundException {
  FileInputStream fileInputStream = new FileInputStream(fileName);
  return getFileByte(fileInputStream);
 }

 public byte[] getFileByte(URL url) throws IOException {
  if (url != null) {
   return getFileByte(url.openStream());
  } else {
   return null;
  }
 }

 public byte[] getFileByte(InputStream in) {
  ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
  try {
   copy(in, out);
  } catch (IOException e) {
   e.printStackTrace();
  }
  return out.toByteArray();

 }

 private void copy(InputStream in, OutputStream out) throws IOException {

  try {
   byte[] buffer = new byte[4096];
   int nrOfBytes = -1;
   while ((nrOfBytes = in.read(buffer)) != -1) {
    out.write(buffer, 0, nrOfBytes);
   }
   out.flush();
  } catch (IOException e) {

  }finally {
   try {
    if (in != null) {
     in.close();
    }
   } catch (IOException ex) {
   }
   try {
    if (out != null) {
     out.close();
    }
   } catch (IOException ex) {
   }
  }

 }

}

首页 更多主题 上一页 只显示标题