陌上花开

遇高山,我御风而翔,逢江河,我凌波微波

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::

2012年5月23日 #

标准javascript 是内含支持hash关联数组,经查找资料并测试,有关标准javascript内含的hash关联数组操作备忘如下

1。Hash关联数组定义

// 定义空数组
myhash = { }

// 直接定义数组
myhash = {”key1″:”val1″, “key2″:”val2″ }

// 用Array 定义数组
myhash = new Array();
myhash[”key1″] = “val1″;
myhash[”key2″] = “val2″;

2。向Hash关联数组添加键值

// 添加一个新键 newkey ,键值为 newval
myhash[”newkey”] = “newval”;

3。删除Hash关联数组已有键值

// 删除一个键 newkey ,同时,该键值对应的 newval 也就消失了
delete myhash[”newkey”];

4。遍历Hash关联数组

// 遍历整个hash 数组
for (key in myhash) {
val = myhash[key];
}

5。Hash关联数组简易使用示例

// 转向脚本
<script type=”text/javascript”>
urlhash = { “yahoo”:”www.yahoo.cn“,
“baidu”:”www.baidu.com“,
“google”:”www.google.cn” };

// 交互式使用示例
userinfo = prompt(”请输入您最想去的搜索引擎:(yahoo|baidu|google)”, “yahoo”);
document.write (”您的选择:” + userinfo + “,<a href=http://” + getURL(userinfo) + ” target=_blank>” + “按此即可进入” + “</a>” + userinfo + “。”);

// getURL
// 如果参数未定义,默认返回 www.yahoo.cn 网址
// @param choice 选择名称
// @return url 实际的URL
function getURL(choice) {
url = urlhash[choice];
if (typeof(urlhash[choice]) == “undefined”)
url = “www.yahoo.cn“;
return url;
}

// 获得hash列表的所有 keys
// @param hash hash数组
// @return keys 键名数据
function array_keys(hash) {
keys = [];
for (key in hash)
keys.push(key);
return keys;
}
</script>

posted @ 2012-12-20 11:28 askzs 阅读(18337) | 评论 (1)编辑 收藏

原文地址:http://www.cnblogs.com/Lewis/archive/2010/04/27/1722024.html

 

关于JQuery上传插件Uploadify使用详解网上一大把,基本上内容都一样。我根据网上的步骤配置成功后,会报一些错误,而我根据这些错误去网上找解决方案,却没有相关资料,所以为了不让更多的朋友走弯路,我把我遇到的一些问题进行汇总,也方便我自己以后查阅。

  什么是Uploadify

  Uploadify是JQuery的一个上传插件,支持多文件上传,实现的效果非常不错,带进度显示。

  官网提供的是PHP的DEMO,在这里我详细介绍在Asp.net下的使用.

  下载

    官方下载

    官方文档

    官方演示

  如何使用

  1 创建Web项目,命名为JQueryUploadDemo,从官网上下载最新的版本解压后添加到项目中

  2 在项目中添加UploadHandler.ashx文件用来处理文件的上传。

  3 在项目中添加UploadFile文件夹,用来存放上传的文件。

  进行完上面三步后项目的基本结构如下图:

  

  4 Default.aspx的html页的代码修改如下:

  

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   
<title>Uploadify</title>
   
<link href="JS/jquery.uploadify-v2.1.0/example/css/default.css"
     rel
="stylesheet" type="text/css" />
   
<link href="JS/jquery.uploadify-v2.1.0/uploadify.css"
     rel
="stylesheet" type="text/css" />

   
<script type="text/javascript"
     src
="JS/jquery.uploadify-v2.1.0/jquery-1.3.2.min.js"></script>

   
<script type="text/javascript"
     src
="JS/jquery.uploadify-v2.1.0/swfobject.js"></script>

   
<script type="text/javascript"
   src
="JS/jquery.uploadify-v2.1.0/jquery.uploadify.v2.1.0.min.js"></script>

   
<script type="text/javascript">
        $(document).ready(
function()
        {
            $(
"#uploadify").uploadify({
               
'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf',
               
'script': 'UploadHandler.ashx',
               
'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png',
               
'folder': 'UploadFile',
               
'queueID': 'fileQueue',
               
'auto': false,
               
'multi': true
            });
        }); 
   
</script>

</head>
<body>
   
<div id="fileQueue"></div>
   
<input type="file" name="uploadify" id="uploadify" />
   
<p>
     
<a href="javascript:$('#uploadify').uploadifyUpload()">上传</a>|
     
<a href="javascript:$('#uploadify').uploadifyClearQueue()">取消上传</a>
   
</p>
</body>
</html>

  5  UploadHandler类的ProcessRequest方法代码如下:

  

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType
= "text/plain";  
    context.Response.Charset
= "utf-8";  

    HttpPostedFile file
= context.Request.Files["Filedata"];  
   
string  uploadPath =
        HttpContext.Current.Server.MapPath(@context.Request[
"folder"])+"\\"

   
if (file != null
    { 
      
if (!Directory.Exists(uploadPath)) 
       { 
           Directory.CreateDirectory(uploadPath); 
       }  
       file.SaveAs(uploadPath
+ file.FileName); 
       
//下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
       context.Response.Write("1"); 
    }  
   
else 
    {  
        context.Response.Write(
"0");  
    } 
}

  注意:这里一定要注意,一定要引用using System.IO;命名空间,我出错的原因也是在这里,网上的教程基本上都没提到这一点,所以有很多网友会遇到IOError的错误。

6 运行后效果如下图:

  

  7 选择了两个文件后,点击上传,就可以看到UploadFile文件夹中会增加这两个文件。

  

  上面的代码就简单实现了上传的功能,依靠函数uploadify实现,uploadify函数的参数为json格式,可以对json对象的key值的修改来进行自定义的设置,如multi设置为true或false来控制是否可以进行多文件上传,下面就来介绍下这些key值的意思:

 

uploader : uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框,默认值:uploadify.swf。
script :   后台处理程序的相对路径 。默认值:uploadify.php
checkScript :用来判断上传选择的文件在服务器是否存在的后台处理程序的相对路径
fileDataName :设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata
method : 提交方式Post 或Get 默认为Post
scriptAccess :flash脚本文件的访问模式,如果在本地测试设置为always,默认值:sameDomain 
folder :  上传文件存放的目录 。
queueID : 文件队列的ID,该ID与存放文件队列的div的ID一致。
queueSizeLimit : 当允许多文件生成时,设置选择文件的个数,默认值:999 。
multi : 设置为true时可以上传多个文件。
auto : 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传 。
fileDesc : 这个属性值必须设置fileExt属性后才有效,用来设置选择文件对话框中的提示文本,如设置fileDesc为“请选择rar doc pdf文件”,打开文件选择框效果如下图:

  

fileExt : 设置可以选择的文件的类型,格式如:'*.doc;*.pdf;*.rar' 。
sizeLimit : 上传文件的大小限制 。
simUploadLimit : 允许同时上传的个数 默认值:1 。
buttonText : 浏览按钮的文本,默认值:BROWSE 。
buttonImg : 浏览按钮的图片的路径 。
hideButton : 设置为true则隐藏浏览按钮的图片 。
rollover : 值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。
width : 设置浏览按钮的宽度 ,默认值:110。
height : 设置浏览按钮的高度 ,默认值:30。
wmode : 设置该项为transparent 可以使浏览按钮的flash背景文件透明,并且flash文件会被置为页面的最高层。 默认值:opaque 。
cancelImg :选择文件到文件队列中后的每一个文件上的关闭按钮图标,如下图:

  

上面介绍的key值的value都为字符串或是布尔类型,比较简单,接下来要介绍的key值的value为一个函数,可以在选择文件、出错或其他一些操作的时候返回一些信息给用户。

onInit : 做一些初始化的工作

onSelect :选择文件时触发,该函数有三个参数

  • event:事件对象。
  • queueID:文件的唯一标识,由6为随机字符组成。
  • fileObj:选择的文件对象,有name、size、creationDate、modificationDate、type 5个属性。

代码如下:

  

$(document).ready(function()
{
    $(
"#uploadify").uploadify({
       
'uploader': 'JS/jquery.uploadify-v2.1.0/uploadify.swf',
       
'script': 'UploadHandler.ashx',
       
'cancelImg': 'JS/jquery.uploadify-v2.1.0/cancel.png',
       
'folder': 'UploadFile',
       
'queueID': 'fileQueue',
       
'auto': false,
       
'multi': true,
       
'onInit':function(){alert("1");},
       
'onSelect': function(e, queueId, fileObj)
        {
            alert(
"唯一标识:" + queueId + "\r\n" +
                 
"文件名:" + fileObj.name + "\r\n" +
                 
"文件大小:" + fileObj.size + "\r\n" +
                 
"创建时间:" + fileObj.creationDate + "\r\n" +
                 
"最后修改时间:" + fileObj.modificationDate + "\r\n" +
                 
"文件类型:" + fileObj.type
            );

        }
    });
}); 

 


当选择一个文件后弹出的消息如下图:

onSelectOnce :在单文件或多文件上传时,选择文件时触发。该函数有两个参数event,data,data对象有以下几个属性:

fileCount:选择文件的总数。
filesSelected:同时选择文件的个数,如果一次选择了3个文件该属性值为3。
filesReplaced:如果文件队列中已经存在A和B两个文件,再次选择文件时又选择了A和B,该属性值为2。
allBytesTotal:所有选择的文件的总大小。
 

onCancel : 当点击文件队列中文件的关闭按钮或点击取消上传时触发。该函数有event、queueId、fileObj、data四个参数,前三个参数同onSelect 中的三个参数,data对象有两个属性fileCount和allBytesTotal。

fileCount:取消一个文件后,文件队列中剩余文件的个数。
allBytesTotal:取消一个文件后,文件队列中剩余文件的大小。
 

onClearQueue :当调用函数fileUploadClearQueue时触发。有event和data两个参数,同onCancel 中的两个对应参数。

onQueueFull :当设置了queueSizeLimit并且选择的文件个数超出了queueSizeLimit的值时触发。该函数有两个参数event和queueSizeLimit。

onError :当上传过程中发生错误时触发。该函数有event、queueId、fileObj、errorObj四个参数,其中前三个参数同上,errorObj对象有type和info两个属性。

type:错误的类型,有三种‘HTTP’, ‘IO’, or ‘Security’
info:错误的描述
 

onOpen :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列。该函数有event、queueId、fileObj三个参数,参数的解释同上。

onProgress :点击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列,在onOpen之后触发。该函数有event、queueId、fileObj、data四个参数,前三个参数的解释同上。data对象有四个属性percentage、bytesLoaded、allBytesLoaded、speed:

percentage:当前完成的百分比
bytesLoaded:当前上传的大小
allBytesLoaded:文件队列中已经上传完的大小
speed:上传速率 kb/s
 

onComplete:文件上传完成后触发。该函数有四个参数event、queueId、fileObj、response、data五个参数,前三个参数同上。response为后台处理程序返回的值,在上面的例子中为1或0,data有两个属性fileCount和speed

fileCount:剩余没有上传完成的文件的个数。
speed:文件上传的平均速率 kb/s
注:fileObj对象和上面讲到的有些不太一样,onComplete 的fileObj对象有个filePath属性可以取出上传文件的路径。

 

onAllComplete:文件队列中所有的文件上传完成后触发。该函数有event和data两个参数,data有四个属性,分别为:

filesUploaded :上传的所有文件个数。
errors :出现错误的个数。
allBytesLoaded :所有上传文件的总大小。
speed :平均上传速率 kb/s
 

相关函数介绍

在上面的例子中已经用了uploadifyUpload和uploadifyClearQueue两个函数,除此之外还有几个函数:

uploadifySettings:可以动态修改上面介绍的那些key值,如下面代码

  $('#uploadify').uploadifySettings('folder','JS'); 

如果上传按钮的事件写成下面这样,文件将会上传到uploadifySettings定义的目录中

<a href="javascript:$('#uploadify').uploadifySettings('folder','JS');$('#uploadify').uploadifyUpload()">上传</a>

  uploadifyCancel:该函数接受一个queueID作为参数,可以取消文件队列中指定queueID的文件。

  
  $('#uploadify').uploadifyCancel(id); 

 

  好了,所有的配置都完成了。下面说说我遇到的一些问题。 span style="font-size: 18pt;"> 可能遇到的问题   1.我刚开始配置完成后,并不能正常工作 ,flash(uploadify.swf' )没有加载。后来我查看jquery.uploadify.v2.1.0.js发现该插件是利用swfobject.js动态创建的FLASH,后来我单独做试验还是不能显示flash,无耐之下重启电脑后就可以了。晕倒~~~  2.FLASH终于加载进来了,但上传又失败了。报IOError,如图:  

  

百思不得其解,翻遍了各大网络,终于在国外的一网站看到了这么一句using System.IO; 添加之豁然开朗!!

暂时还没有遇到其它问题,后续发现问题再加。

posted @ 2012-11-20 11:41 askzs 阅读(1138) | 评论 (0)编辑 收藏

ThickBox 是基于 jQuery 用 JavaScript 编写的网页UI对话窗口小部件. 它可以用来展示单一图片, 若干图片, 内嵌的内容, iframed的内容, 或以 AJAX 的混合 modal 提供的内容.

特性:

  • ThickBox 是用超轻量级的 jQuery 库 编写的. 压缩过 jQuery 库只15k, 未压缩过的有39k.
  • ThickBox 的 JavaScript 代码和 CSS 文件只占12k. 所以压缩过的 jQuery 代码和 ThickBox 总共只有27k.
  • ThickBox 能重新调整大于浏览器窗口的图片.
  • ThickBox 的多功能性包括 (图片, iframed 的内容, 内嵌的内容, 和 AJAX 的内容).
  • ThickBox 能隐藏 Windows IE 6 里的元素.
  • ThickBox 能在使用者滚动页面或改变浏览器窗口大小的同时始终保持居中. 点击图片, 覆盖层, 或关闭链接能移除 ThickBox.
  • ThickBox 的创作者决定动画应该因人而异, 所以 ThickBox 不再使用动画了. 这是特性吗? 哦, 有人说是呀.

下载

posted @ 2012-08-13 11:06 askzs 阅读(280) | 评论 (0)编辑 收藏

在项目中,需要用到打印,最早的是使用js调用本地打印,效果不好,样式等不好控制,容易出错,有时候浏览器不兼容造成不能打印,后来用报表,生成破地方格式的然后打印,兼容性强,稳定,比较好用,基本上没有什么问题,但是开发过程慢,报表不好画,action不好控制,总之,开发过程比较痛苦,而且样式变的话报表需要重新画,不好修改,后来发现了 lodop,是个浏览器的插件,需要客户安装,安装后使用方便,打印效果不错,还可以让用户自己调试打印模式,而且支持的打印种类多,可以打印背景图片,套表格式等,就是很方便就是了,安装也方便,下面是详细的介绍说明。
http://mtsoftware.v053.gokao.net/samples/PrintSampIndex.html

最新版本及其技术手册可从如下地址下载:
http://mtsoftware.v053.gokao.net/download.html
http://mt.runon.cn/download.html 


posted @ 2012-08-13 09:35 askzs 阅读(1320) | 评论 (4)编辑 收藏

在Java中有时候需要使程序暂停一点时间,称为延时。普通延时用Thread.sleep(int)方法,这很简单。它将当前线程挂起指定的毫秒数。如

Java 代码复制内容到剪贴板
  1. try
  2. {
  3. Thread.currentThread().sleep(1000);//毫秒
  4. }
  5. catch(Exception e){}

在这里需要解释一下线程沉睡的时间。sleep()方法并不能够让程序"严格"的沉睡指定的时间。例如当使用5000作为sleep()方法的参数时,线 程可能在实际被挂起5000.001毫秒后才会继续运行。当然,对于一般的应用程序来说,sleep()方法对时间控制的精度足够了。

但是如果要使用精确延时,最好使用Timer类:

Java 代码复制内容到剪贴板
  1. Timer timer=new Timer();//实例化Timer类
  2. timer.schedule(new TimerTask(){
  3. public void run(){
  4. System.out.println("退出");
  5. this.cancel();}},500);//五百毫秒

这种延时比sleep精确。上述延时方法只运行一次,
如果需要运行多次, 使用timer.schedule(new MyTask(), 1000, 2000); 则每间隔2秒执行MyTask()

posted @ 2012-06-05 11:35 askzs 阅读(336) | 评论 (0)编辑 收藏

本课题参考自《Spring in action》。并非应用系统中发生的所有事情都是由用户的动作引起的。有时候,系统自己也需要发起一些动作。例如,集抄系统每天早上六点把抄表数据传送 给营销系统。我们有两种选择:或者是每天由用户手动出发任务,或者让应用系统中按照预定的计划自动执行任务。 
在Spring中有两种流行配置:Java的Timer类和OpenSymphony的Quartz来执行调度任务。下面以给商丘做的接口集抄900到中间库的日冻结数据传输为例: 

1. Java Timer调度器 
首先定义一个定时器任务,继承java.util.TimerTask类实现run方法 
import java.util.TimerTask; 
import xj.service.IJdbc1Service; 
import xj.service.IJdbc2Service; 
public class DayDataTimerTask extends TimerTask{ 
private IJdbc2Service jdbc2Service=null; 
private IJdbc1Service jdbc1Service=null; 
public void run(){ 
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
System.out.println("日冻结转接任务开始时间:"+df.format(Calendar.getInstance().getTime())); 
System.out.println("日冻结转接任务结束时间:"+df.format(Calendar.getInstance().getTime())); 


//通过set方法获取service服务,如果没有该方法,则为null 
public void setJdbc2Service(IJdbc2Service jdbc2Service) { 
this.jdbc2Service = jdbc2Service; 


public void setJdbc1Service(IJdbc1Service jdbc1Service) { 
this.jdbc1Service = jdbc1Service; 


Run()方法定义了当任务运行时该做什么。jdbc1Service,jdbc2Service通过依赖注入的方式提供给DayDataTimerTask。如果该任务中没有service服务的set方法,则取到的该service服务为null。 
其次,在Spring配置文件中声明 dayDataTimerTask: 
<!-- 声明定时器任务 --> 
<bean id="dayDataTimerJob" class="xj.action.DayDataTimerTask"> 
<property name="jdbc1Service"> 
<ref bean="jdbc1Service"/> 
</property> 
<property name="jdbc2Service"> 
<ref bean="jdbc2Service"/> 
</property> 
</bean> 
该声明将DayDataTimerTask放到应用上下文中,并在jdbc1Service、jdbc2Service属性中分别装配jdbc1Service、jdbc2Service。在调度它之前,它不会做任何事情。 
<!-- 调度定时器任务 --> 
<bean id="scheduledDayDataTimerJob" class="org.springframework.scheduling.timer.ScheduledTimerTask"> 
<property name="timerTask"> 
<ref bean="dayDataTimerJob"/> 
</property> 
<property name="delay"> 
<value>3000</value> 
</property> 
<property name="period"> 
<value>864000000</value> 
</property> 
</bean> 
属性timerTask告诉ScheduledTimerTask运行哪个TimerTask。再次,该属性装配了指向 scheduledDayDataTimerJob的一个引用,它就是DayDataTimerTask。属性period告诉 ScheduledTimerTask以怎样的频度调用TimerTask的run()方法。该属性以毫秒作为单位,它被设置为864000000,指定 这个任务应该每24小时运行一次。属性delay允许你指定当任务第一次运行之前应该等待多久。在此指定DayDataTimerTask的第一次运行相 对于应用程序的启动时间延迟3秒钟。 
<!-- 启动定时器 --> 
<bean class="org.springframework.scheduling.timer.TimerFactoryBean"> 
<property name="scheduledTimerTasks"> 
<list> 
<ref bean="scheduledDayDataTimerJob"/> 
</list> 
</property> 
</bean> 
Spring的TimerFactoryBean负责启动定时任务。属性scheduledTimerTasks要求一个需要启动的定时器任务的列表。在此只包含一个指向scheduledDayDataTimerJob的引用。 
    Java Timer只能指定任务执行的频度,但无法精确指定它何时运行,这是它的一个局限性。要想精确指定任务的启动时间,就需要使用Quartz[kwɔ:ts]调度器。 

2.Quartz调度器 
Quartz调度器不仅可以定义每隔多少毫秒执行一个工作,还允许你调度一个工作在某个特定的时间或日期执行。 
首先创建一个工作,继承QuartzJobBean类实现executeInternal方法 
import org.quartz.JobExecutionContext; 
import org.quartz.JobExecutionException; 
import org.springframework.dao.DataIntegrityViolationException; 
import org.springframework.scheduling.quartz.QuartzJobBean; 

import xj.service.IJdbc1Service; 
import xj.service.IJdbc2Service; 
public class DayDataQuartzTask extends QuartzJobBean{ 
private IJdbc2Service jdbc2Service=null; 
private IJdbc1Service jdbc1Service=null; 
protected void executeInternal(JobExecutionContext context) throws JobExecutionException{ 
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
System.out.println("日冻结转接任务开始时间:"+df.format(Calendar.getInstance().getTime())); 
System.out.println("日冻结转接任务结束时间:"+df.format(Calendar.getInstance().getTime())); 


//通过set方法获取service服务,如果没有该方法,则为null 
public void setJdbc2Service(IJdbc2Service jdbc2Service) { 
this.jdbc2Service = jdbc2Service; 


public void setJdbc1Service(IJdbc1Service jdbc1Service) { 
this.jdbc1Service = jdbc1Service; 




在Spring配置文件中按照以下方式声明这个工作: 
<!-- 定时启动任务 Quartz--> 
<!—声明工作--> 
<bean id="dayDataJob" class="org.springframework.scheduling.quartz.JobDetailBean"> 
<property name="jobClass"> 
<value>xj.action.DayDataQuartzTask</value> 
</property> 
<property name="jobDataAsMap"> 
<map> 
<entry key="jdbc1Service"> 
<ref bean="jdbc1Service"/> 
</entry> 
<entry key="jdbc2Service"> 
<ref bean="jdbc2Service"/> 
</entry> 
</map> 
</property> 
</bean> 
Quartz的org.quartz.Trigger类描述了何时及以怎样的频度运行一个Quartz工作。Spring提供了两个触发器 SimpleTriggerBean和CronTriggerBean。SimpleTriggerBean与scheduledTimerTasks类 似。指定工作的执行频度,模仿scheduledTimerTasks配置。 
<!-- 调度Simple工作 --> 
<bean id="simpleDayDataJobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> 
<property name="jobDetail"> 
<ref bean="dayDataJob"/> 
</property> 
<property name="startDelay"> 
<value>1000</value> 
</property> 
<property name="repeatInterval"> 
<value>86400000</value> 
</property> 
</bean> 
<!—调度cron工作--> 
<bean id="dayDataJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> 
<property name="jobDetail"> 
<ref bean="dayDataJob"/> 
</property> 
<property name="cronExpression"> 
<value>0 30 2 * * ?</value> 
</property> 
</bean> 
一个cron表达式有6个或7个由空格分隔的时间元素。从左至右,这些元素的定义如下:1、秒(0-59);2、分(0-59);3、小时 (0-23);4、月份中的日期(1-31);5、月份(1-12或JAN-DEC);6、星期中的日期(1-7或SUN-SAT);7、年份 (1970-2099)。 
每一个元素都可以显式地规定一个值(如6),一个区间(如9-12),一个列表(如9,11,13)或一个通配符(如*)。“月份中的日期”和“星期中的日期”这两个元素互斥,应该通过设置一个问号(?)来表明你不想设置的那个字段。

corn表达式API具体见 

http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

我们在此定义该任务在每天凌晨两点半开始启动。 
<!—启动工作--> 
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
<property name="triggers"> 
<list> 
<ref bean="simpleDayDataJobTrigger"/> 
<ref bean="dayDataJobTrigger"/> 
</list> 
</property> 
</bean> 
属性triggers接受一组触发器,在此只装配包含simpleDayDataJobTrigger bea和dayDataJobTrigger bean的一个引用列表。

posted @ 2012-05-30 13:02 askzs 阅读(2713) | 评论 (0)编辑 收藏

     摘要: Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource、TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分。   DataSource、TransactionManager这两部分只是会根据数据访问方式有所变化,比如使用Hibernate进行数据访问时,DataSource实际为SessionFactory,Tran...  阅读全文
posted @ 2012-05-30 10:07 askzs 阅读(348) | 评论 (0)编辑 收藏

mport java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;


public class MbbDemo {
 
 public static  void main(String []args)throws Exception
 {
  File file=new File("d://a.txt");
  FileInputStream fis=new FileInputStream(file);
     FileOutputStream fos=new FileOutputStream("d://acopy.txt");
     FileChannel fChannel=fis.getChannel();
     FileChannel out=fos.getChannel();
     MappedByteBuffer mbb=fChannel.map(FileChannel.MapMode.READ_ONLY, 0,file.length());
     out.write(mbb);
     if(fis!=null)fis.close();
     if(fos!=null)fos.close();
  
  
 }

}

posted @ 2012-05-25 14:11 askzs 阅读(724) | 评论 (0)编辑 收藏

转载自 http://www.ibm.com/developerworks/cn/java/joy-down/

断点续传的原理

其实断点续传的原理很简单,就是在 Http 的请求上和一般的下载有所不同而已。
打个比方,浏览器请求服务器上的一个文时,所发出的请求如下:
假设服务器域名为 wwww.sjtu.edu.cn,文件名为 down.zip。
GET /down.zip HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-
excel, application/msword, application/vnd.ms-powerpoint, */*
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Connection: Keep-Alive

服务器收到请求后,按要求寻找请求的文件,提取文件的信息,然后返回给浏览器,返回信息如下:

200
Content-Length=106786028
Accept-Ranges=bytes
Date=Mon, 30 Apr 2001 12:56:11 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:56:11 GMT

所谓断点续传,也就是要从文件已经下载的地方开始继续下载。所以在客户端浏览器传给 Web 服务器的时候要多加一条信息 -- 从哪里开始。
下面是用自己编的一个"浏览器"来传递请求信息给 Web 服务器,要求从 2000070 字节开始。
GET /down.zip HTTP/1.0
User-Agent: NetFox
RANGE: bytes=2000070-
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2

仔细看一下就会发现多了一行 RANGE: bytes=2000070-
这一行的意思就是告诉服务器 down.zip 这个文件从 2000070 字节开始传,前面的字节不用传了。
服务器收到这个请求以后,返回的信息如下:
206
Content-Length=106786028
Content-Range=bytes 2000070-106786027/106786028
Date=Mon, 30 Apr 2001 12:55:20 GMT
ETag=W/"02ca57e173c11:95b"
Content-Type=application/octet-stream
Server=Microsoft-IIS/5.0
Last-Modified=Mon, 30 Apr 2001 12:55:20 GMT

和前面服务器返回的信息比较一下,就会发现增加了一行:
Content-Range=bytes 2000070-106786027/106786028
返回的代码也改为 206 了,而不再是 200 了。

知道了以上原理,就可以进行断点续传的编程了。


Java 实现断点续传的关键几点

  1. (1) 用什么方法实现提交 RANGE: bytes=2000070-。
    当然用最原始的 Socket 是肯定能完成的,不过那样太费事了,其实 Java 的 net 包中提供了这种功能。代码如下:

    URL url = new URL("http://www.sjtu.edu.cn/down.zip");
    HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();

    // 设置 User-Agent
    httpConnection.setRequestProperty("User-Agent","NetFox");
    // 设置断点续传的开始位置
    httpConnection.setRequestProperty("RANGE","bytes=2000070");
    // 获得输入流
    InputStream input = httpConnection.getInputStream();

    从输入流中取出的字节流就是 down.zip 文件从 2000070 开始的字节流。大家看,其实断点续传用 Java 实现起来还是很简单的吧。接下来要做的事就是怎么保存获得的流到文件中去了。

  2. 保存文件采用的方法。
    我采用的是 IO 包中的 RandAccessFile 类。
    操作相当简单,假设从 2000070 处开始保存文件,代码如下:
    RandomAccess oSavedFile = new RandomAccessFile("down.zip","rw");
    long nPos = 2000070;
    // 定位文件指针到 nPos 位置
    oSavedFile.seek(nPos);
    byte[] b = new byte[1024];
    int nRead;
    // 从输入流中读入字节流,然后写到文件中
    while((nRead=input.read(b,0,1024)) > 0)
    {
    oSavedFile.write(b,0,nRead);
    }

怎么样,也很简单吧。接下来要做的就是整合成一个完整的程序了。包括一系列的线程控制等等。


断点续传内核的实现

主要用了 6 个类,包括一个测试类。
SiteFileFetch.java 负责整个文件的抓取,控制内部线程 (FileSplitterFetch 类 )。
FileSplitterFetch.java 负责部分文件的抓取。
FileAccess.java 负责文件的存储。
SiteInfoBean.java 要抓取的文件的信息,如文件保存的目录,名字,抓取文件的 URL 等。
Utility.java 工具类,放一些简单的方法。
TestMethod.java 测试类。

下面是源程序:

/* 
 /*
 * SiteFileFetch.java 
 */ 
 package NetFox; 
 import java.io.*; 
 import java.net.*; 
 public class SiteFileFetch extends Thread { 
 SiteInfoBean siteInfoBean = null; // 文件信息 Bean 
 long[] nStartPos; // 开始位置
 long[] nEndPos; // 结束位置
 FileSplitterFetch[] fileSplitterFetch; // 子线程对象
 long nFileLength; // 文件长度
 boolean bFirst = true; // 是否第一次取文件
 boolean bStop = false; // 停止标志
 File tmpFile; // 文件下载的临时信息
 DataOutputStream output; // 输出到文件的输出流
 public SiteFileFetch(SiteInfoBean bean) throws IOException 
 { 
 siteInfoBean = bean; 
 //tmpFile = File.createTempFile ("zhong","1111",new File(bean.getSFilePath())); 
 tmpFile = new File(bean.getSFilePath()+File.separator + bean.getSFileName()+".info");
 if(tmpFile.exists ()) 
 { 
 bFirst = false; 
 read_nPos(); 
 } 
 else 
 { 
 nStartPos = new long[bean.getNSplitter()]; 
 nEndPos = new long[bean.getNSplitter()]; 
 } 
 } 
 public void run() 
 { 
 // 获得文件长度
 // 分割文件
 // 实例 FileSplitterFetch 
 // 启动 FileSplitterFetch 线程
 // 等待子线程返回
 try{ 
 if(bFirst) 
 { 
 nFileLength = getFileSize(); 
 if(nFileLength == -1) 
 { 
 System.err.println("File Length is not known!"); 
 } 
 else if(nFileLength == -2) 
 { 
 System.err.println("File is not access!"); 
 } 
 else 
 { 
 for(int i=0;i<nStartPos.length;i++) 
 { 
 nStartPos[i] = (long)(i*(nFileLength/nStartPos.length)); 
 } 
 for(int i=0;i<nEndPos.length-1;i++) 
 { 
 nEndPos[i] = nStartPos[i+1]; 
 } 
 nEndPos[nEndPos.length-1] = nFileLength; 
 } 
 } 
 // 启动子线程
 fileSplitterFetch = new FileSplitterFetch[nStartPos.length]; 
 for(int i=0;i<nStartPos.length;i++) 
 { 
 fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean.getSSiteURL(), 
 siteInfoBean.getSFilePath() + File.separator + siteInfoBean.getSFileName(), 
 nStartPos[i],nEndPos[i],i); 
 Utility.log("Thread " + i + " , nStartPos = " + nStartPos[i] + ", nEndPos = " 
 + nEndPos[i]); 
 fileSplitterFetch[i].start(); 
 } 
 // fileSplitterFetch[nPos.length-1] = new FileSplitterFetch(siteInfoBean.getSSiteURL(),
 siteInfoBean.getSFilePath() + File.separator 
 + siteInfoBean.getSFileName(),nPos[nPos.length-1],nFileLength,nPos.length-1); 
 // Utility.log("Thread " +(nPos.length-1) + ",nStartPos = "+nPos[nPos.length-1]+",
 nEndPos = " + nFileLength); 
 // fileSplitterFetch[nPos.length-1].start(); 
 // 等待子线程结束
 //int count = 0; 
 // 是否结束 while 循环
 boolean breakWhile = false; 
 while(!bStop) 
 { 
 write_nPos(); 
 Utility.sleep(500); 
 breakWhile = true; 
 for(int i=0;i<nStartPos.length;i++) 
 { 
 if(!fileSplitterFetch[i].bDownOver) 
 { 
 breakWhile = false; 
 break; 
 } 
 } 
 if(breakWhile) 
 break; 
 //count++; 
 //if(count>4) 
 // siteStop(); 
 } 
 System.err.println("文件下载结束!"); 
 } 
 catch(Exception e){e.printStackTrace ();} 
 } 
 // 获得文件长度
 public long getFileSize() 
 { 
 int nFileLength = -1; 
 try{ 
 URL url = new URL(siteInfoBean.getSSiteURL()); 
 HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection ();
 httpConnection.setRequestProperty("User-Agent","NetFox"); 
 int responseCode=httpConnection.getResponseCode(); 
 if(responseCode>=400) 
 { 
 processErrorCode(responseCode); 
 return -2; //-2 represent access is error 
 } 
 String sHeader; 
 for(int i=1;;i++) 
 { 
 //DataInputStream in = new DataInputStream(httpConnection.getInputStream ()); 
 //Utility.log(in.readLine()); 
 sHeader=httpConnection.getHeaderFieldKey(i); 
 if(sHeader!=null) 
 { 
 if(sHeader.equals("Content-Length")) 
 { 
 nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader)); 
 break; 
 } 
 } 
 else 
 break; 
 } 
 } 
 catch(IOException e){e.printStackTrace ();} 
 catch(Exception e){e.printStackTrace ();} 
 Utility.log(nFileLength); 
 return nFileLength; 
 } 
 // 保存下载信息(文件指针位置)
 private void write_nPos() 
 { 
 try{ 
 output = new DataOutputStream(new FileOutputStream(tmpFile)); 
 output.writeInt(nStartPos.length); 
 for(int i=0;i<nStartPos.length;i++) 
 { 
 // output.writeLong(nPos[i]); 
 output.writeLong(fileSplitterFetch[i].nStartPos); 
 output.writeLong(fileSplitterFetch[i].nEndPos); 
 } 
 output.close(); 
 } 
 catch(IOException e){e.printStackTrace ();} 
 catch(Exception e){e.printStackTrace ();} 
 } 
 // 读取保存的下载信息(文件指针位置)
 private void read_nPos() 
 { 
 try{ 
 DataInputStream input = new DataInputStream(new FileInputStream(tmpFile)); 
 int nCount = input.readInt(); 
 nStartPos = new long[nCount]; 
 nEndPos = new long[nCount]; 
 for(int i=0;i<nStartPos.length;i++) 
 { 
 nStartPos[i] = input.readLong(); 
 nEndPos[i] = input.readLong(); 
 } 
 input.close(); 
 } 
 catch(IOException e){e.printStackTrace ();} 
 catch(Exception e){e.printStackTrace ();} 
 } 
 private void processErrorCode(int nErrorCode) 
 { 
 System.err.println("Error Code : " + nErrorCode); 
 } 
 // 停止文件下载
 public void siteStop() 
 { 
 bStop = true; 
 for(int i=0;i<nStartPos.length;i++) 
 fileSplitterFetch[i].splitterStop(); 
 } 
 } 
 

 /* 
 **FileSplitterFetch.java 
 */ 
 package NetFox; 
 import java.io.*; 
 import java.net.*; 
 public class FileSplitterFetch extends Thread { 
 String sURL; //File URL 
 long nStartPos; //File Snippet Start Position 
 long nEndPos; //File Snippet End Position 
 int nThreadID; //Thread's ID 
 boolean bDownOver = false; //Downing is over 
 boolean bStop = false; //Stop identical 
 FileAccessI fileAccessI = null; //File Access interface 
 public FileSplitterFetch(String sURL,String sName,long nStart,long nEnd,int id)
 throws IOException 
 { 
 this.sURL = sURL; 
 this.nStartPos = nStart; 
 this.nEndPos = nEnd; 
 nThreadID = id; 
 fileAccessI = new FileAccessI(sName,nStartPos); 
 } 
 public void run() 
 { 
 while(nStartPos < nEndPos && !bStop) 
 { 
 try{ 
 URL url = new URL(sURL); 
 HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection (); 
 httpConnection.setRequestProperty("User-Agent","NetFox"); 
 String sProperty = "bytes="+nStartPos+"-"; 
 httpConnection.setRequestProperty("RANGE",sProperty); 
 Utility.log(sProperty); 
 InputStream input = httpConnection.getInputStream(); 
 //logResponseHead(httpConnection); 
 byte[] b = new byte[1024]; 
 int nRead; 
 while((nRead=input.read(b,0,1024)) > 0 && nStartPos < nEndPos 
 && !bStop) 
 { 
 nStartPos += fileAccessI.write(b,0,nRead); 
 //if(nThreadID == 1) 
 // Utility.log("nStartPos = " + nStartPos + ", nEndPos = " + nEndPos); 
 } 
 Utility.log("Thread " + nThreadID + " is over!"); 
 bDownOver = true; 
 //nPos = fileAccessI.write (b,0,nRead); 
 } 
 catch(Exception e){e.printStackTrace ();} 
 } 
 } 
 // 打印回应的头信息
 public void logResponseHead(HttpURLConnection con) 
 { 
 for(int i=1;;i++) 
 { 
 String header=con.getHeaderFieldKey(i); 
 if(header!=null) 
 //responseHeaders.put(header,httpConnection.getHeaderField(header)); 
 Utility.log(header+" : "+con.getHeaderField(header)); 
 else 
 break; 
 } 
 } 
 public void splitterStop() 
 { 
 bStop = true; 
 } 
 } 
 
 /* 
 **FileAccess.java 
 */ 
 package NetFox; 
 import java.io.*; 
 public class FileAccessI implements Serializable{ 
 RandomAccessFile oSavedFile; 
 long nPos; 
 public FileAccessI() throws IOException 
 { 
 this("",0); 
 } 
 public FileAccessI(String sName,long nPos) throws IOException 
 { 
 oSavedFile = new RandomAccessFile(sName,"rw"); 
 this.nPos = nPos; 
 oSavedFile.seek(nPos); 
 } 
 public synchronized int write(byte[] b,int nStart,int nLen) 
 { 
 int n = -1; 
 try{ 
 oSavedFile.write(b,nStart,nLen); 
 n = nLen; 
 } 
 catch(IOException e) 
 { 
 e.printStackTrace (); 
 } 
 return n; 
 } 
 } 
 
 /* 
 **SiteInfoBean.java 
 */ 
 package NetFox; 
 public class SiteInfoBean { 
 private String sSiteURL; //Site's URL 
 private String sFilePath; //Saved File's Path 
 private String sFileName; //Saved File's Name 
 private int nSplitter; //Count of Splited Downloading File 
 public SiteInfoBean() 
 { 
 //default value of nSplitter is 5 
 this("","","",5); 
 } 
 public SiteInfoBean(String sURL,String sPath,String sName,int nSpiltter)
 { 
 sSiteURL= sURL; 
 sFilePath = sPath; 
 sFileName = sName; 
 this.nSplitter = nSpiltter; 
 } 
 public String getSSiteURL() 
 { 
 return sSiteURL; 
 } 
 public void setSSiteURL(String value) 
 { 
 sSiteURL = value; 
 } 
 public String getSFilePath() 
 { 
 return sFilePath; 
 } 
 public void setSFilePath(String value) 
 { 
 sFilePath = value; 
 } 
 public String getSFileName() 
 { 
 return sFileName; 
 } 
 public void setSFileName(String value) 
 { 
 sFileName = value; 
 } 
 public int getNSplitter() 
 { 
 return nSplitter; 
 } 
 public void setNSplitter(int nCount) 
 { 
 nSplitter = nCount; 
 } 
 } 
 
 /* 
 **Utility.java 
 */ 
 package NetFox; 
 public class Utility { 
 public Utility() 
 { 
 } 
 public static void sleep(int nSecond) 
 { 
 try{ 
 Thread.sleep(nSecond); 
 } 
 catch(Exception e) 
 { 
 e.printStackTrace (); 
 } 
 } 
 public static void log(String sMsg) 
 { 
 System.err.println(sMsg); 
 } 
 public static void log(int sMsg) 
 { 
 System.err.println(sMsg); 
 } 
 } 
 
 /* 
 **TestMethod.java 
 */ 
 package NetFox; 
 public class TestMethod { 
 public TestMethod() 
 { ///xx/weblogic60b2_win.exe 
 try{ 
 SiteInfoBean bean = new SiteInfoBean("http://localhost/xx/weblogic60b2_win.exe",
     "L:\\temp","weblogic60b2_win.exe",5); 
 //SiteInfoBean bean = new SiteInfoBean("http://localhost:8080/down.zip","L:\\temp",
     "weblogic60b2_win.exe",5); 
 SiteFileFetch fileFetch = new SiteFileFetch(bean); 
 fileFetch.start(); 
 } 
 catch(Exception e){e.printStackTrace ();} 
 } 
 public static void main(String[] args) 
 { 
 new TestMethod(); 
 } 
 }


posted @ 2012-05-23 15:13 askzs 阅读(661) | 评论 (0)编辑 收藏

我要啦免费统计